简体   繁体   English

Matplotlib tight_layout - 删除额外的白色/空白空间

[英]Matplotlib tight_layout — remove extra white/empty space

I want to minimise whitespace around my figures and am unsure how to a) precisely specify a bounding box for the savefig command around my image and b) why the tight-layout command does not work in my working example. 我想尽量减少我的数字周围的空白,并且不确定如何a)为我的图像周围的savefig命令精确指定一个边界框,以及b)为什么紧张布局命令在我的工作示例中不起作用。

In my current example, I set up an axis environment tightly around my objects/patches (so tightly that the yellow objects and blue box are almost cut off on the left and bottom, respectively). 在我当前的例子中,我在我的对象/补丁周围紧紧地设置了一个轴环境(非常紧密,黄色物体和蓝色框几乎分别在左侧和底部被切断)。 However, this still gives me white space both to the left and bottom: 但是,这仍然给我左边和底部的空白区域: 在此输入图像描述

I am aware that this comes from the axis object (which I turned off) 我知道这来自轴对象(我关掉了) 在此输入图像描述

However, I'm not sure how to get rid off the white space in this case. 但是,在这种情况下,我不确定如何摆脱空白区域。 I thought that one could specify the bounding box as discussed Matplotlib tight_layout() doesn't take into account figure suptitle but inserting 我认为可以指定边界框,如讨论Matplotlib tight_layout()没有考虑数字suptitle但插入

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

this only gives me more whitespace: 这只给了我更多的空白: 在此输入图像描述

I know how to sneak my way round this by inserting an axis object that fills the full figure etc but this feels like a silly hack. 我知道如何通过插入一个充满整个人物的轴对象来绕过这个方向,但这感觉就像一个愚蠢的黑客。 Is there an easy and fast way to do this? 有一种简单快捷的方法吗?

My code is: 我的代码是:

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

You can remove the x and y axis and then use savefig with bbox_inches='tight' and pad_inches = 0 to remove the white space. 您可以删除x轴和y轴,然后使用savefig和bbox_inches='tight'pad_inches = 0来删除空白区域。 See code below: 见下面的代码:

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

This will result in 这将导致

在此输入图像描述

In addition, you can optionally add plt.margins(0.1) to make the scatter points not touch the y axis. 此外,您可以选择添加plt.margins(0.1)以使散点不接触y轴。

Actually fig.tight_layout(rect=[0.1,0.1,0.9, 0.95]) does kind of the inverse of what you want. 实际上, fig.tight_layout(rect=[0.1,0.1,0.9, 0.95])确实与你想要的相反。 It will make the region where all the figure's content is placed fit into the rectangle given, effectively producing even more space. 它将使所有图形内容放置的区域适合给定的矩形,从而有效地产生更多空间。

In theory you could of course do something in the other direction, using a rectangle with negative coordinates and ones bigger than 1, fig.tight_layout(rect=[-0.055,0,1.05, 1]) . 从理论上讲,你当然可以在另一个方向上做一些事情,使用带负坐标的矩形和大​​于1的fig.tight_layout(rect=[-0.055,0,1.05, 1])fig.tight_layout(rect=[-0.055,0,1.05, 1]) But there is no good strategy to find out the values that need to be used. 但是没有好的策略来找出需要使用的值。 Plus (what will become apparent later in this text) you would still need to change the size of the figure if a specific aspect needs to be used. 另外(如果需要使用特定方面),您仍需要更改图形的大小。

Now to a solution: 现在来一个解决方案:

I don't know why setting the axes tight to the figure edge would be a "silly hack". 我不知道为什么将轴紧固到图形边缘会是一个“愚蠢的黑客”。 It is precisely one option you have to get no spacings around the subplot - which is what you want. 正是一个选项,你必须在子情节周围没有间距 - 这就是你想要的。

In the usual case, 在通常的情况下,

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

would be enough to do that. 就足够了。 However, since here you have a specific aspect ratio set on the axes, you would also need to adjust the figure size to the axes box. 但是,由于此处您在轴上设置了特定的纵横比,因此您还需要将数字大小调整为轴框。 This could be done as 这可以做到

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)

Alternatively, instead of subplots_adjust one may use tight_layout(pad=0) and still set the figure size accordingly, 或者,代替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)

Of course if you only care about the exported figure, using some of the savefig options is an easier solution, the other answer already shows the easiest one of them. 当然,如果你只关心导出的数字,使用一些savefig选项是一个更容易的解决方案, 另一个答案已经显示了最简单的一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM