【问题标题】:Set height and width of figure created with plt.subplots in matplotlib?在 matplotlib 中设置使用 plt.subplots 创建的图形的高度和宽度?
【发布时间】:2016-05-24 14:02:29
【问题描述】:

在matplotlib中,我知道如何设置图形的高宽和DPI:

fig = plt.figure(figsize=(4, 5), dpi=100)

但是,如果我想创建小的多个地块,我似乎无法创建这样的图形,我必须使用这个:

fig, subplots = plt.subplots(nrows=4, ncols=4)

如何设置使用这样的子图创建的图形的高度和宽度以及 DPI?

【问题讨论】:

标签: python matplotlib


【解决方案1】:

您实际上可以指定高度和宽度plt.savefig('Desktop/test.png',dpi=500) ,即使它没有在帮助中列为关键字(我认为它已传递给图形调用(?)):

fig,axs=plt.subplots(nrows,ncols,figsize=(width,height)) 

由于某种原因,dpi 被忽略了。但是,您可以在保存图形时使用它,当它很重要时:

plt.savefig('test.png',dpi=1000)

【讨论】:

    【解决方案2】:

    gridspec 模块的工作示例:

    import matplotlib.pyplot as plt
    from matplotlib import gridspec
    
    fig = plt.figure(figsize=(18,18))
    
    gs = gridspec.GridSpec(3, 3)
    
    ax1 = fig.add_subplot(gs[0,:])
    ax1.plot([1,2,3,4,5], [10,5,10,5,10], 'r-')
    
    ax2 = fig.add_subplot(gs[1,:-1])
    ax2.plot([1,2,3,4], [1,4,9,16], 'k-')
    
    ax3 = fig.add_subplot(gs[1:, 2])
    ax3.plot([1,2,3,4], [1,10,100,1000], 'b-')
    
    ax4 = fig.add_subplot(gs[2,0])
    ax4.plot([1,2,3,4], [0,0,1,1], 'g-')
    
    ax5 = fig.add_subplot(gs[2,1])
    ax5.plot([1,2,3,4], [1,0,0,1], 'c-')
    
    gs.update(wspace=0.5, hspace=0.5)
    
    plt.show()
    

    但我更喜欢将它包装在一个函数中并像这样使用它:

    def mySubplotFunction(fig,gs,x,y,c,ax=None):
    
        if not ax:
            ax = fig.add_subplot(gs)
        ax.plot(x, y, c)
    
        return fig, ax
    

    用法:

    fig2 = plt.figure(figsize=(9,9))
    fig2, ax1 = mySubplotFunction(fig2,gs[0,:],[1,2,3,4,5],[10,5,10,5,10],'r-');
    fig2, ax2 = mySubplotFunction(fig2,gs[1,:-1],[1,2,3,4],[1,4,9,16],'k-');
    

    【讨论】:

      猜你喜欢
      • 2021-06-09
      • 1970-01-01
      • 2020-09-01
      • 2012-03-01
      • 2014-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多