【问题标题】:How to adjust the plot size in Matplotlib?如何调整 Matplotlib 中的绘图大小?
【发布时间】:2018-01-04 15:02:42
【问题描述】:

我正在尝试从我创建的绘图中删除空白:

可以看到,右边和底部都有一个很大的白点,如何修复?这是我的脚本:

fig = plt.figure(figsize=(7,7))
        
        
ax1 = plt.subplot2grid((4,3), (0,0),)
ax2 = plt.subplot2grid((4,3), (1,0),)
ax3 = plt.subplot2grid((4,3), (0,1),)
ax4 = plt.subplot2grid((4,3), (1,1),)
        
data = self.dframe[i]
        
tes = print_data(data, self.issues, self.color, self.type_user)
    
tes.print_top(data=data, top=10, ax=ax1, typegraph="hbar", problem=self.issues[i], tone=self.color[i])
tes.print_top(data=data, top=10, ax=ax2, typegraph="prod_bar", problem=self.issues[i], tone=self.color[i])
tes.print_top(data=data, top=10, ax=ax3, typegraph="reg_hbar", problem=self.issues[i], tone=self.color[i])
tes.print_top(data=data, top=10, ax=ax4, typegraph=self.type_user, problem=self.issues[i], tone=self.color[i])
        
problem = self.issues[i]
plt.tight_layout()
name = problem + str('.PNG')
plt.close(fig)
fig.savefig(name)

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    你正在创建太多的子图!

    如果我们看这一行:

    ax1 = plt.subplot2grid((4,3), (0,0),)
    

    我们可以看到 subplot2grid 的第一个参数是要制作的子图网格的尺寸,在本例中为 4 行和 3 列。然后,您将在图形左上角的子图中进行绘图(给出的第二个参数),这留下了很多未使用的空间。

    所以要解决这个问题,请使用以下方法减少子图的数量:

    ax1 = plt.subplot2grid((2,2), (0,0),)
    

    完整示例:

    import numpy as np
    import matplotlib.pyplot as plt
    
    data = np.random.randn(25)
    
    fig = plt.figure(figsize=(7,7))
    
    ax1 = plt.subplot2grid((2,2), (0,0),)
    ax2 = plt.subplot2grid((2,2), (1,0),)
    ax3 = plt.subplot2grid((2,2), (0,1),)
    ax4 = plt.subplot2grid((2,2), (1,1),)
    
    ax1.plot(data)
    ax2.plot(data)
    ax3.plot(data)
    ax4.plot(data)
    
    plt.show()
    

    给予:

    【讨论】:

    • 谢谢你的帮助@DavidG,地块填满了所有的空白点,但是,现在图片太大了,有没有其他方法可以保持原来的尺寸并切掉空白点?
    • 缩小图形大小?
    • 我该怎么做?,我将使用这个绘图将保存的图片(绘图)插入到使用 tkinter 的小部件中,我试图减小图片保存的大小,但是,图片不是很在那里可见,这就是为什么我要削减空白点。
    • 所以你已经删除了空地块。但是,图形大小没有改变,这意味着现有的 4 个地块将自动缩放以填充空间。要减小图形的整体大小,只需执行fig = plt.figure(figsize=(5,5))
    • 我已经尝试了所有 figsize, (2,2); (3x3)、(5x5) 等,但大体尺寸还是一样
    【解决方案2】:

    你可以使用 plt.subplots_adjust(left=0.09, bottom=0.07, right=0.98, top=0.97, wspace=0.2 , hspace=0.17 ) 调整窗口。 但问题是你的情节中有很多空间是空的 也许你应该改变 plt.subplot2grid((4,3)...转plt.subplot2grid((2,2)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-04
      • 2015-04-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      • 2015-06-08
      相关资源
      最近更新 更多