如何在图表右侧预留空白放置图例?(Matplotlib/Pandas)
柱状图右侧预留空白放置图例的问题
我正在学习数据可视化,希望在柱状图右侧预留空白区域,以便将图例移入其中,避免与图表数据重叠。尝试过调整图例位置、更改柱状图尺寸,但效果不佳;也尝试过添加空白区域但未成功,现寻求可行解决方案。
当前图表效果

预期图表效果

使用代码
bins = [float('-inf'), 1960, 1970, 1980, 1990, float('inf')] labels = ['1960 and Older', '1970s', '1980s', '1990s', '2000 and Younger'] df['AgeGroup'] = pd.cut(df['Year'], bins=bins, labels=labels) fam_map = {3: 'Low', 4: 'Medium', 5: 'High'} df['FamLabel'] = df['Familiar_with_capsicum'].map(fam_map) ax = avg_df.plot(kind='bar', color=['#00dd00','#dd0000','#0000bb' ], figsize=(8, 4), ) ax.set_xlabel('Age Groups') ax.set_ylabel('Average Familiarity with Capsicum') ax.set_title('Average Familiarity Level of Capsicum by Age Groups', fontsize=15, fontweight='bold') ax.legend(title='Familiarity Level', title_fontsize=12, loc='center left', bbox_to_anchor=(1.03,.5)) plt.show()
已尝试操作
- 调整图例位置、更改柱状图尺寸,无合理效果
- 尝试添加空白区域未成功
可行解决方案
方法1:手动调整子图右侧边距
通过subplots_adjust设置右侧边距,专门给图例预留空间,不影响柱状图的显示范围:
import matplotlib.pyplot as plt import pandas as pd # 数据处理代码不变 bins = [float('-inf'), 1960, 1970, 1980, 1990, float('inf')] labels = ['1960 and Older', '1970s', '1980s', '1990s', '2000 and Younger'] df['AgeGroup'] = pd.cut(df['Year'], bins=bins, labels=labels) fam_map = {3: 'Low', 4: 'Medium', 5: 'High'} df['FamLabel'] = df['Familiar_with_capsicum'].map(fam_map) # 创建子图并绘图 fig, ax = plt.subplots(figsize=(8, 4)) avg_df.plot(kind='bar', color=['#00dd00','#dd0000','#0000bb' ], ax=ax) # 图表标签设置不变 ax.set_xlabel('Age Groups') ax.set_ylabel('Average Familiarity with Capsicum') ax.set_title('Average Familiarity Level of Capsicum by Age Groups', fontsize=15, fontweight='bold') # 调整右侧边距,给图例留出空间 plt.subplots_adjust(right=0.8) # 设置图例位置 ax.legend(title='Familiarity Level', title_fontsize=12, loc='center left', bbox_to_anchor=(1.03,.5)) plt.show()
方法2:配合布局自动调整+加宽图表
增大图表宽度,再用tight_layout()自动适配元素位置,避免手动计算边距:
import matplotlib.pyplot as plt import pandas as pd # 数据处理代码不变 # 加宽图表尺寸 fig, ax = plt.subplots(figsize=(10, 4)) avg_df.plot(kind='bar', color=['#00dd00','#dd0000','#0000bb' ], ax=ax) # 图表标签设置不变 ax.set_xlabel('Age Groups') ax.set_ylabel('Average Familiarity with Capsicum') ax.set_title('Average Familiarity Level of Capsicum by Age Groups', fontsize=15, fontweight='bold') # 设置图例位置 ax.legend(title='Familiarity Level', title_fontsize=12, loc='center left', bbox_to_anchor=(1.03,.5)) # 自动调整布局,确保所有元素不重叠 plt.tight_layout() plt.show()
方法3:导出图片时避免图例裁剪
如果需要保存图表,可通过bbox_extra_artists指定图例为额外元素,防止导出时被裁剪:
# 前面代码不变 # 单独获取图例对象 leg = ax.legend(title='Familiarity Level', title_fontsize=12, loc='center left', bbox_to_anchor=(1.03,.5)) # 保存图片时包含图例 plt.savefig('capsicum_familiarity_chart.png', bbox_extra_artists=(leg,), bbox_inches='tight') plt.show()
内容的提问来源于stack exchange,提问作者Aldo
相关产品推荐
相关产品推荐

