Pandas绘图:如何为分组统计的柱状图添加hue参数?
解决pandas柱状图无法使用hue参数的问题
pandas自带的plot.bar()方法本身不支持hue参数,这个参数是seaborn绘图库的专属参数。要实现按Corr列分组展示不同颜色的柱状图,有两种可行方案:
方案一:用pandas调整数据结构后绘图
先通过多层分组+unstack()把Corr的不同取值转为列,再调用plot.bar()就能自动按列区分颜色:
x_var, y_var = 'category', 'instance' # 同时按category和Corr分组,统计instance的唯一值数量 grouped_counts = df.groupby([x_var, 'Corr'])[y_var].nunique().unstack() # 绘制柱状图,每个category下会显示对应不同Corr的柱子 grouped_counts.plot.bar(stacked=False)
方案二:用seaborn直接绘制(推荐)
seaborn的barplot()原生支持hue参数,先整理好统计数据再传入即可:
import seaborn as sns import matplotlib.pyplot as plt # 先统计每个(category, Corr)组合的instance唯一值数量,转为DataFrame stats_df = df.groupby(['category', 'Corr'])['instance'].nunique().reset_index(name='unique_instance_count') # 使用seaborn绘制,hue参数指定Corr列来区分颜色 sns.barplot(data=stats_df, x='category', y='unique_instance_count', hue='Corr') plt.show()
两种方案都能实现你要的效果:在每个category下展示不同Corr对应的instance唯一值数量,且用颜色区分Corr的分组。
内容的提问来源于stack exchange,提问作者Salih
相关产品推荐
相关产品推荐

