Matplotlibight_layout——删除多余的白色/空白区域

2024-04-23

我想尽量减少人物周围的空白,但不确定如何 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: enter image description here

I am aware that this comes from the axis object (which I turned off) enter image description here

但是,我不确定在这种情况下如何消除空白。 我认为可以指定所讨论的边界框Matplotlib strict_layout() 不考虑图副标题 https://stackoverflow.com/questions/8248467/matplotlib-tight-layout-doesnt-take-into-account-figure-suptitle但插入

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

this only gives me more whitespace: 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])

您可以删除 x 和 y 轴,然后使用 savefig 与bbox_inches='tight' and 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). 

这将导致

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Matplotlibight_layout——删除多余的白色/空白区域 的相关文章

随机推荐