【发布时间】:2021-05-31 01:13:46
【问题描述】:
我有一个固定大小 (1000*1000) 的图形,我试图在图下方放置一个图例(即在轴边界框之外)。我使用bbox_to_anchor 参数到plt.legend() 和pad 参数到plt.tight_layout()。问题是,当我尝试将图例进一步向下移动时,通过减小传递给bbox_to_anchor 的第二个值,图形底部边缘和图例之间的填充会增加,即使我在plt.tight_layout() 中设置了pad=0 .我想使用 0.7 的填充,以使绘图与使用该填充的其他绘图一致,并使图例与条形标签充分分开,将绘图的缩小保持在所需的最小值。我已经阅读了matplotlib documentation legend guide 和this excelent answer 到一个相关问题,但我不明白为什么图例底部和图形底部之间的填充会随着我减小 2- 的 y 值而增加元组传递给 bbox_to_anchor 参数。我也试图弄乱loc 参数,但无济于事。
示例
案例一
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.3), fontsize=30, frameon=True, borderaxespad=0)
plt.tight_layout(pad=0)
案例2
试图将图例进一步向下移动:
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.5), fontsize=30, frameon=True, borderaxespad=0)
plt.tight_layout(pad=0)
案例3
将内边距更改为 0.2,这样图形的边缘就不会被剪裁:
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.5), fontsize=30, frameon=True, borderaxespad=0)
plt.tight_layout(pad=0.2)
创建绘图的函数代码(删除了一些不必要的部分):
def example_plot(left_total, right_total, target):
fig, ax = plt.subplots(figsize=(10,10), linewidth=2, edgecolor='#9E9E9E')
names = ['left', 'right']
size_of_groups = [left_total, right_total]
left_bar = ax.bar(names[0], size_of_groups[0], color='#515151', width=0.5)
right_bar = ax.bar(names[1], size_of_groups[1], color='#FFD732', width=0.5)
ax.axhline(y=target, color='#32CDFF', linestyle='solid', lw=3, label='Target')
ymin = min(left_total, right_total, target)
ymin = math.floor(ymin/1000)*1000
ymax = max(left_total, right_total, target)
ymax = math.ceil(ymax/1000)*1000
ax.set_ylim([ymin, ymax])
yticks = list(range(ymin, ymax+1000, 1000))
ax.set_yticks(yticks)
ax.bar_label(left_bar, fontsize=40)
ax.bar_label(right_bar, fontsize=40)
ax.spines[:].set_visible(False)
ax.set_axisbelow(True)
ax.grid(True, axis='y', color='#9E9E9E', clip_on=False)
ax.set_title("Example plot\n", fontsize=50, fontweight = 500)
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.3), fontsize=30, frameon=True, borderaxespad=0)
plt.tight_layout(pad=0)
fig.savefig("plots/example_plot.png")
【问题讨论】:
标签: python matplotlib plot