如何在Seaborn柱状图中显示相对百分比标签?
解决方案:将柱状图标签改为相对百分比
你可以通过计算每个日期销量相对于最高销量的占比,生成自定义标签来实现需求。修改后的完整代码如下:
plt.figure(figsize=(10,5)) graph = df.groupby("Day")["Barcode"].count().sort_values(ascending=False).reset_index() graph_sells_day = sns.barplot(data=graph, x='Day', y='Barcode', palette='viridis') # 替换原bar_label行的代码 max_sales = graph['Barcode'].max() # 计算相对百分比并格式化标签,保留1位小数 labels = [f'{(val / max_sales) * 100:.1f}%' for val in graph['Barcode']] graph_sells_day.bar_label(graph_sells_day.containers[0], labels=labels, fontsize=7) plt.title('SELLS BY DAY') plt.ylabel('Sells', fontsize=12) plt.xlabel('Day', fontsize=12) plt.show()
关键说明:
- 通过
graph['Barcode'].max()获取销量最高的数值作为基准(对应100%) - 用列表推导式遍历每个日期的销量,计算占比后格式化为带百分号的字符串;
:.1f控制保留1位小数,可根据需求调整为:.2f保留两位小数 - 调用
bar_label时传入自定义的labels参数,替代原有的fmt参数,直接使用预格式化好的百分比标签
内容的提问来源于stack exchange,提问作者Tabare De Los Santos
相关产品推荐
相关产品推荐

