gpt4 book ai didi

python - Matplotlib tight_layout -- 删除多余的白色/空白空间

转载 作者:太空宇宙 更新时间:2023-11-03 13:30:39 25 4
gpt4 key购买 nike

我想尽量减少图形周围的空白,但不确定如何a) 为我的图像周围的 savefig 命令精确指定一个边界框,并且b) 为什么 tight-layout 命令在我的工作示例中不起作用。

在我当前的例子中,我在我的对象/补丁周围设置了一个轴环境(非常紧密以至于黄色对象和蓝色框分别在左侧和底部几乎被切断)。但是,这仍然给我左侧和底部的空白: enter image description here

我知道这来自轴对象(我关闭了它) 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

我知道如何通过插入一个填满整个图形的轴对象等来绕过这个问题,但这感觉像是一个愚蠢的 hack。有没有简单快捷的方法来做到这一点?

我的代码是:

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 轴,然后使用带有 bbox_inches='tight'pad_inches = 0 的 savefig 来删除空白。见下面的代码:

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 轴。

关于python - Matplotlib tight_layout -- 删除多余的白色/空白空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47891830/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com