【发布时间】:2020-12-09 19:46:48
【问题描述】:
在生成要保存到 pdf 文件的图形时,我想调整图形相对于页面边缘的位置,例如在所有边上添加英寸边距。据我所知,执行此操作的解决方案(例如,this question):
- 不要使用
constrained_layout模式——在创建图形之后但在fig.savefig()之前应用plt.subplots_adjust()会破坏受约束的布局 - 实际上不要对图的位置进行量化调整——添加
bbox_inches="tight"或pad=-1似乎没有任何意义
有没有一种直接的方法来调整受约束的布局图形的外部边距?
例如:
fig = plt.figure(constrained_layout=True, figsize=(11, 8.5))
page_grid = gridspec.GridSpec(nrows=2, ncols=1, figure=fig)
# this doesn't appear to do anything with constrained_layout=True
page_grid.update(left=0.2, right=0.8, bottom=0.2, top=0.8)
top_row_grid = gridspec.GridSpecFromSubplotSpec(1, 3, subplot_spec=page_grid[0])
for i in range(3):
ax = fig.add_subplot(top_row_grid[:, i], aspect="equal")
n_bottom_row_plots = 10
qc_grid = gridspec.GridSpecFromSubplotSpec(1, n_bottom_row_plots, subplot_spec=page_grid[1])
for i, metric in enumerate(range(n_bottom_row_plots)):
ax = fig.add_subplot(qc_grid[:, i])
plt.plot(np.arange(5), np.arange(5))
fig.suptitle("my big label", fontweight="bold", fontsize="x-large", y=0.9)
# this ruins the constrained layout
# plt.subplots_adjust(left=0.2,right=0.8, bottom=0.2, top=0.8)
fig.savefig("temp.png", facecolor="coral")
产生以下效果(我希望在边缘看到更多珊瑚!):
【问题讨论】:
-
从 matpotlib 3.3.1 开始,使用
constrained_layout=False保存的图像正确显示右边距。你用的是什么版本? -
@r-beginners 我正在运行 3.2.2,但我有
constrained_layout=True... 你是什么意思右边距显示正确? -
与左边距相同的宽度在右边距中
标签: python matplotlib