Adding two smaller subplots to the side of my main plot in matplotlib subplots

帅比萌擦擦* 提交于 2021-01-29 06:44:35

问题


Currently my chart is showing only the main big chart on the left.

However, I now want to add the two smaller plots to the right-hand side of my main plot; with each individual set of data.

I am struggling with subplots to figure out how to do this. My photo below shows my desired output.

filenamesK = glob("C:/Users/Ke*.csv")
filenamesZ = glob("C:/Users/Ze*.csv")


K_Z_Averages = {'K':[], 'Z':[]}


# We will create a function for plotting, instead of nesting lots of if statements within a long for-loop.
def plot_data(filename, fig_ax, color):
    
    df = pd.read_csv(f, sep=',',skiprows=24) # Read in the csv.
    df.columns=['sample','Time','ms','Temp1'] # Set the column names
    df=df.astype(str) # Set the data type as a string.

    df["Temp1"] = df["Temp1"].str.replace('\+ ', '').str.replace(' ', '').astype(float) # Convert to float
    # Take the average of the data from the Temp1 column, starting from sample 60  until sample 150.
    avg_Temp1 = df.iloc[60-1:150+1]["Temp1"].mean()
    
    # Append this average to a K_Z_Averages, containing a column for average from each K file and the average from each Z file.
    # Glob returns the whole path, so you need to replace 0 for 10.
    K_Z_Averages[os.path.basename(filename)[0]].append(avg_Temp1)
    
    fig_ax.plot(df[["Temp1"]], color=color)

fig, ax = plt.subplots(figsize=(20, 15))

for f in filenamesK:
    plot_data(f, ax, 'blue')

for f in filenamesZ:
    plot_data(f, ax, 'red')
    

plt.show()


回答1:


@max 's answer is fine, but something you can also do matplotlib>=3.3 is

import matplotlib.pyplot as plt
fig = plt.figure(constrained_layout=True)
axs = fig.subplot_mosaic([['Left', 'TopRight'],['Left', 'BottomRight']],
                          gridspec_kw={'width_ratios':[2, 1]})
axs['Left'].set_title('Plot on Left')
axs['TopRight'].set_title('Plot Top Right')
axs['BottomRight'].set_title('Plot Bottom Right')

Note hw the repeated name 'Left' is used twice to indicate that this subplot takes up two slots in the layout. Also note the use of width_ratios.




回答2:


This is a tricky question. Essentially, you can place a grid on a figure (add_gridspec()) and than open subplots (add_subplot()) in and over different grid elements.

import matplotlib.pyplot as plt

# open figure
fig = plt.figure()
# add grid specifications
gs = fig.add_gridspec(2, 3)
# open axes/subplots
axs = []
axs.append( fig.add_subplot(gs[:,0:2]) ) # large subplot (2 rows, 2 columns)
axs.append( fig.add_subplot(gs[0,2]) )   # small subplot (1st row, 3rd column)
axs.append( fig.add_subplot(gs[1,2]) )   # small subplot (2nd row, 3rd column)



来源:https://stackoverflow.com/questions/65265401/adding-two-smaller-subplots-to-the-side-of-my-main-plot-in-matplotlib-subplots

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!