跟进我之前的问题,我在将图例重新定位到我想要的位置时遇到了一些麻烦。在上述帖子中,我的图例附加到第二个子图上,但我想将其放在两个图的下方。例如这里的左图。
这是我现有的代码:
a_combined_path = 'c:\\mypath'
fig, (ax1, ax2) = plt.subplots(1,2, layout='constrained')
fig.set_size_inches(10,10)
a_2020.plot(ax=ax1, column='Party Vote Share', cmap='Greens', edgecolor='black', linewidth = 0.5, norm=norm)
a_dublin.plot(ax=ax2, column='Party Vote Share', cmap='Greens', edgecolor='black', linewidth = 0.5, norm=norm)
ax1.set_axis_off()
ax2.set_axis_off()
ax1.set_title('Republic of Ireland', size = 16)
ax2.set_title('Dublin', size = 16)
fig.suptitle('Aontú vote share in the 2020 elections\nby constituency (Pct of total vote)', size = 16)
plt.savefig(a_combined_path, dpi=600)
我尝试将
legend=True, legend_kwds={loc: 'lower right'}
放入 a_2020.plot(...)
中,但显然 colorbar
不将 loc
作为参数。我尝试过使用 fig.colorbar
,但我似乎无法让 imshow
使用我的数据框。另外,它甚至不需要严格是一个颜色条,我会对像图例here这样的东西非常满意。我只是想把它放在我身材的中下部,我错误地认为这是一个简单的练习。
任何帮助将不胜感激,因为到目前为止我已经花了一天的时间在这个问题上。
没有任何数据,很难测试这一点,但如果您计划对两个子图仅使用一个图例,您可以使用以下内容,但您可能需要摆弄元组内的数字以获取
bbox_to_anchor
。 bbox_to_anchor
元组内的四个数字表示图例框锚点的坐标。然而,这些数字中只有两个通常用于定位图例。前两个数字表示锚点相对于子图轴的水平和垂直位置。例如。 bboch_to_anchor = (0.5,0.5)
。如果您想指定子图中图例框的确切位置,您可以添加其他参数,例如宽度和高度。例如。 bboch_to_anchor = (0.5,0.5,0.3,0.7)
。这些数字可能大于 1,因此请尝试不同的值。
# Add legends to subplots
ax1.legend(loc='upper left') # For the first subplot
ax2.legend(loc='upper right') # For the second subplot
# Positioning the legend relative to the entire figure
fig.legend(loc='lower center', bbox_to_anchor=(0.5, 0), bbox_transform=fig.transFigure)
如果您想为每个子图都有单独的图例,那么您可以尝试以下操作:
# Add legends to subplots
ax1.legend(loc='upper left', bbox_to_anchor=(0.5, 0.5, 0.5, 0.5))
ax2.legend(loc='upper right', bbox_to_anchor=(0.5, 0.5, 0.5, 0.5))
同样,您可以在元组内使用 2 或 4 个数字。
希望这至少能帮助您找到解决方案。