matplotlib分组柱状图如何添加各指标全球均值参考线
实现方案
你之前hlines错位的核心原因是没搞懂pandas分组柱状图的x轴坐标规则:4个指标作为x轴分类,实际对应的坐标是整数0、1、2、3,每个分类下的5根国家柱子围绕对应整数中心均匀排布,整组柱子的总宽度就等于你传入plot()的width参数值。参考线只需要以对应整数为中心,左右各取总宽度的1/2作为xmin/xmax,就能和分组柱完美对齐。
完整可运行代码如下:
import matplotlib.pyplot as plt import pandas as pd plt.rcParams.update({'font.size': 22}) df = pd.read_html( "https://worldpopulationreview.com/country-rankings/gender-equality-by-country", index_col=0)[1] for x in list(df): df[x] = df[x].str.rstrip('%').astype('float') / 100.0 df = df.rename(columns={'Economic Opp.': 'Economic Opportunity'}) # 固定国家和指标顺序,避免集合索引导致的柱子顺序随机问题 target_countries = ["China", "India", "United States", "Indonesia", "Pakistan"] target_cols = ["Economic Opportunity", "Educational Attainment", "Health and Survival", "Political Power"] plot_df = df.loc[target_countries, target_cols].transpose() # 自动计算4个指标的全球均值,无需手动硬编码 global_avg = df[target_cols].mean() with plt.style.context('dark_background'): ax = plot_df.plot(kind="bar", figsize=(20, 10), width=0.5, align='center', linewidth=8, edgecolor='black') group_width = 0.5 # 和plot传入的width参数保持一致 # 逐组绘制均值参考线 for idx, col in enumerate(target_cols): avg = global_avg[col] ax.hlines( y=avg, xmin=idx - group_width/2, xmax=idx + group_width/2, color='orange', linestyle='dashed', linewidth=5, label=f'Global Average: {col}' ) plt.xticks(rotation=0) plt.title("The 4 Gender Equality parameters in the 5 most populated countries on Earth") plt.legend() plt.tight_layout() plt.show()
关键修改说明
- 把原来的集合选数改成固定列表,解决国家柱子顺序随机的问题
- 直接从原始数据计算全球均值,不用手动抄数值,数据源更新后代码自动适配
- 基于分类轴的整数坐标计算参考线范围,和分组柱完全对齐,不会错位
- 参考线长度和每组柱子总宽度一致,和你给出的预期效果匹配
- 增加自动图例和布局收紧,避免标签截断
内容的提问来源于stack exchange,提问作者Leonardo Boscolo
相关产品推荐
相关产品推荐

