Matplotlib tight_布局--删除额外的白色/空sp

2024-06-11 12:51:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我想尽量减少数字周围的空白,不确定如何 a) 在我的图像和 b) 为什么“紧密布局”命令在我的工作示例中不起作用。

在我当前的示例中,我紧紧围绕对象/面片设置了一个轴环境(如此紧密,黄色对象和蓝色框几乎分别在左侧和底部被切断)。但是,这仍然给了我左侧和底部的空白: enter image description here

我知道这来自axis对象(我关闭了它) enter image description here

但是,在这种情况下,我不知道如何摆脱空白。 我认为可以指定边界框,如前所述Matplotlib tight_layout() doesn't take into account figure suptitle 但是插入

fig.tight_layout(rect=[0.1,0.1,0.9, 0.95]), 

这只会给我更多的空白: enter image description here

我知道如何通过插入一个填充整个图形的轴对象来绕过这个问题,但这感觉像一个愚蠢的黑客。有简单快捷的方法吗?

我的代码是:

import matplotlib
from matplotlib import pyplot as plt
from matplotlib.path import Path
import matplotlib.patches as patches
from matplotlib.collections import PatchCollection
from matplotlib.patches import FancyBboxPatch


plt.ion()

fig, ax=plt.subplots(1)
ax.set_xlim([-0.38,7.6])
ax.set_ylim([-0.71,3.2])
ax.set_aspect(0.85)
#objects 
circs2=[]
circs2.append( patches.Circle((-0.3, 1.225), 0.1,ec="none"))
circs2.append( patches.RegularPolygon ((-0.3,1.225+1.5),4, 0.1) )
coll2 = PatchCollection (circs2,zorder=10)
coll2.set_facecolor(['yellow', 'gold'])
ax.add_collection(coll2)

#squares
p_fancy=FancyBboxPatch((0.8,1.5),1.35,1.35,boxstyle="round,pad=0.1",fc='red', ec='k',alpha=0.7, zorder=1)
ax.add_patch(p_fancy)
x0=4.9
p_fancy=FancyBboxPatch((1.15+x0,-0.6),0.7*1.15,0.7*1.15,boxstyle="round,pad=0.1", fc='blue', ec='k',alpha=0.7, zorder=1)
ax.add_patch(p_fancy)

plt.axis('off')

fig.tight_layout(rect=[0.1,0.1,0.9, 0.95])

Tags: 对象fromimportmatplotlibfigpltax空白
2条回答

实际上,fig.tight_layout(rect=[0.1,0.1,0.9, 0.95])与你想要的正好相反。它将使放置所有图形内容的区域适合给定的矩形,有效地产生更多的空间。

在理论上,你当然可以在另一个方向上做一些事情,使用一个负坐标的矩形和一个大于1的矩形,fig.tight_layout(rect=[-0.055,0,1.05, 1])。但是没有一个好的策略来找出需要使用的价值观。另外,如果需要使用特定的方面,您仍然需要更改图形的大小。

现在来个解决方案:

我不知道为什么把斧头固定在图形边缘会是一个“愚蠢的黑客”。这正是一个选择,你必须得到周围的子地块没有间距-这是你想要的。

通常情况下

fig.subplots_adjust(0,0,1,1)

就够了。但是,由于在轴上设置了特定的纵横比,因此还需要将图形大小调整为“轴”框。 可以这样做

fig.subplots_adjust(0,0,1,1)
w,h = fig.get_size_inches()
x1,x2 = ax.get_xlim()
y1,y2 = ax.get_ylim()
fig.set_size_inches(w, ax.get_aspect()*(y2-y1)/(x2-x1)*w)

或者,可以使用subplots_adjust而不是tight_layout(pad=0),并且仍然相应地设置图形大小

ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
fig.tight_layout(pad=0)

w,h = fig.get_size_inches()
x1,x2 = ax.get_xlim()
y1,y2 = ax.get_ylim()
fig.set_size_inches(w, ax.get_aspect()*(y2-y1)/(x2-x1)*w)

当然,如果您只关心导出的图,那么使用一些savefig选项是一个更简单的解决方案,other answer已经显示了其中最简单的一个。

您可以删除x轴和y轴,然后使用savefig和bbox_inches='tight'pad_inches = 0来删除空白。请参见下面的代码:

plt.axis('off') # this rows the rectangular frame 
ax.get_xaxis().set_visible(False) # this removes the ticks and numbers for x axis
ax.get_yaxis().set_visible(False) # this removes the ticks and numbers for y axis
plt.savefig('test.png', bbox_inches='tight',pad_inches = 0, dpi = 200). 

这将导致

enter image description here

此外,还可以选择添加plt.margins(0.1),使散射点不接触y轴。

相关问题 更多 >