You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现:在类别计数柱状图上叠加中位数折线图

如何在类别计数柱状图上叠加中位数折线图?

嘿,我来帮你搞定这个需求!要在每个类别的计数柱状图上叠加对应类别的数值特征中位数折线图,咱们需要对原代码做这几个关键修改:

  • 计算每个类别的目标数值中位数:原代码只统计了类别计数,现在需要新增分组计算逻辑,用groupby按类别分组后提取目标数值特征的中位数(这里假设你的数值特征是log_rental,和标题里的描述对应,记得替换成你实际的列名)。
  • 添加双Y轴:因为计数和中位数的数值量级差异很大,单Y轴会导致折线图被柱状图覆盖,所以要创建右侧的第二个坐标轴来单独展示中位数。
  • 绘制中位数折线图:在新的坐标轴上用折线+标记点的形式画出中位数趋势,让可视化更清晰。
  • 优化图表标签与图例:给双轴分别设置明确的标签,同时添加图例区分柱状图和折线图,避免读者混淆。

修改后的完整代码

import matplotlib.pyplot as plt

def plot_bars_with_median(xy_merge, cols, target_num_col='log_rental'):
    for col in cols:
        fig = plt.figure(figsize=(8,6)) # 稍微调宽一点,给双轴标签留空间
        ax = fig.gca() # 主坐标轴(计数柱状图)
        
        # 1. 计算类别计数和目标数值的中位数,保证索引顺序一致
        counts = xy_merge[col].value_counts()
        medians = xy_merge.groupby(col)[target_num_col].median().reindex(counts.index)
        
        # 2. 绘制计数柱状图
        counts.plot.bar(ax=ax, color='blue', alpha=0.7, label='Category Count')
        ax.set_title(f'Category Counts & Median {target_num_col}: {col}')
        ax.set_xlabel(col)
        ax.set_ylabel('Count')
        ax.legend(loc='upper left')
        
        # 3. 创建双Y轴并绘制中位数折线图
        ax2 = ax.twinx()
        medians.plot(kind='line', ax=ax2, color='red', marker='o', linewidth=2, label=f'Median {target_num_col}')
        ax2.set_ylabel(f'Median {target_num_col}')
        ax2.legend(loc='upper right')
        
        plt.tight_layout() # 自动调整布局,避免标签被截断
        plt.show()

# 调用函数,传入你的类别列和目标数值列(如果不是log_rental就修改)
plot_cols = ['state', 'rucc', 'urban_influence']
plot_bars_with_median(xy_merge, plot_cols, target_num_col='log_rental')

额外说明

  • 我加了reindex(counts.index)来保证中位数的顺序和计数柱状图的类别顺序完全一致,避免折线和柱子错位。
  • 给柱状图加了alpha=0.7让半透明效果更柔和,折线用了marker='o'和加粗线条,让中位数点更突出。
  • 用plt.tight_layout()避免标签被截断,提升图表美观度。

内容的提问来源于stack exchange,提问作者docproc85

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:50:44