【问题标题】:Plot only specific subplots of a grid of subplots仅绘制子图网格的特定子图
【发布时间】:2022-10-04 21:17:04
【问题描述】:

我根据自己的喜好创建了一个子图网格。 我通过定义fig,ax = plt.subplots(2,6,figsize=(24,8)) 来启动绘图

到目前为止,一切都很好。我用它们各自的内容填充了这些子图。现在我想单独绘制一个或两个特定的子图。我试过了:

ax[idx][idx].plot()

这不起作用并返回一个空列表

我努力了:

fig_single,ax_single = plt.subplots(2,1)
ax_single[0]=ax[idx][0]
ax_single[1]=ax[idx][1]

这将返回:

TypeError: 'AxesSubplot' object does not support item assignment

如何在不通过调用相应的绘图函数再次绘制这些子图的情况下继续进行?

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    你很近。

    fig,ax = plt.subplots(nrows=2,ncols=6,sharex=False,sharey=False,figsize=(24,8)) 
    #set either sharex=True or sharey=True if you wish axis limits to be shared 
    #=> very handy for interactive exploration of timeseries data, ...
    
    r=0 #first row
    c=0 #first column
    ax[r,c].plot() #plot your data, instead of ax[r][c].plot()
    ax[r,c].set_title() #name title for a subplot
    ax[r,c].set_ylabel('Ylabel ') #ylabel for a subplot
    ax[r,c].set_xlabel('X axis label') #xlabel for a subplot
    

    更完整/更灵活的方法是分配 r,c:

    for i in range(nrows*ncols):
        r,c = np.divmod(i,ncols)
        ax[r,c].plot() #....
    

    之后您仍然可以进行修改,例如设置_ylim,设置_标题,...

    因此,如果要命名第 11 个子图的标签:

    ax[2,4].set_ylabel('11th subplot ylabel')
    

    您通常希望在最后使用fig.tight_layout(),以便图形正确使用可用区域。

    完整示例:

    import numpy as np
    import matplotlib.pyplot as plt
    
    x = np.linspace(0,180,180)
    
    nrows = 2
    ncols = 6
    
    fig,ax = plt.subplots(nrows=nrows,ncols=ncols,sharex=False,sharey=False,figsize=(24,8))
    for i in range(nrows*ncols):
        r,c = np.divmod(i,ncols)
        y = np.sin(x*180/np.pi*(i+1))
        ax[r,c].plot(x,y)
        ax[r,c].set_title('%s'%i)
    
    fig.suptitle('Overall figure title')
    fig.tight_layout()
    

    【讨论】:

      猜你喜欢
      • 2019-02-05
      • 1970-01-01
      • 1970-01-01
      • 2021-09-15
      • 2022-08-16
      • 2012-11-21
      • 2011-12-19
      • 2012-09-04
      • 1970-01-01
      相关资源
      最近更新 更多