【问题标题】:Adding two smaller subplots to the side of my main plot in matplotlib subplots在 matplotlib 子图中的主图旁边添加两个较小的子图
【发布时间】:2021-03-23 16:45:53
【问题描述】:

目前我的图表仅显示左侧的主要大图表。

但是,我现在想将两个较小的图添加到主图的右侧;每个单独的数据集。

我正在努力研究如何做到这一点。下面的照片显示了我想要的输出。

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()

【问题讨论】:

标签: python matplotlib subplot


【解决方案1】:

@max 的答案很好,但你也可以做 matplotlib>=3.3 是

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')

注意,重复的名称'Left' 被使用了两次,表示该子图在布局中占据了两个位置。还要注意width_ratios的使用。

【讨论】:

  • 谢谢!一个问题 - 如果我愿意,我如何将“左侧绘图”放大 2 倍?
  • 比什么大?使用width_ratio?
【解决方案2】:

这是一个棘手的问题。本质上,您可以在图形 (add_gridspec()) 上放置一个网格,然后在不同的网格元素中和上方打开子图 (add_subplot())。

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)

【讨论】:

    猜你喜欢
    • 2011-11-23
    • 2021-05-27
    • 2020-03-03
    • 2016-04-28
    • 2012-03-04
    • 2012-06-21
    • 2012-05-20
    • 1970-01-01
    • 2019-01-13
    相关资源
    最近更新 更多