如何基于pandas DataFrame绘制分品牌占比柱状图子图
分品牌独立子图百分比柱状图实现方案
补全依赖导入、子图创建、数据筛选和属性配置逻辑后,即可实现需求效果,完整可运行代码如下:
import pandas as pd import numpy as np import matplotlib.pyplot as plt # 示例数据集 df = pd.DataFrame({ 'brand':['A','A', 'A', 'B','B', 'B' ,'C','C', 'C'], 'plants':[0, 1, 2, 0,1,2,0,1,2], '% of total':[80, 12, 8, 67, 18, 5,35, 40,25], }) # 创建3行1列的子图布局,可根据需要调整行列参数改变排列方式 fig, axes = plt.subplots(nrows=3, ncols=1, figsize=(8, 12)) brand_list = ['A', 'B', 'C'] for i, brand in enumerate(brand_list): ax = axes[i] # 筛选当前品牌对应的数据 brand_data = df[df['brand'] == brand].copy() # 若数据总和不为100%,取消下方注释即可自动归一化计算百分比 # brand_data['% of total'] = brand_data['% of total'] / brand_data['% of total'].sum() * 100 # 绘制柱状图 bars = ax.bar(brand_data['plants'], brand_data['% of total'], width=0.6) # 配置子图属性 ax.set_title(f'Brand {brand}', fontweight='bold') ax.set_xlabel('plants') ax.set_ylabel('% of total') ax.set_xticks(brand_data['plants']) ax.set_ylim(0, 100) # 为柱子添加顶部数值标签 for bar in bars: height = bar.get_height() ax.text(bar.get_x() + bar.get_width()/2., height, f'{height}%', ha='center', va='bottom') # 自动调整子图间距,避免标签、标题遮挡 plt.tight_layout() plt.show()
关键逻辑说明
- 原有代码卡点:仅创建了空白画布,没有生成对应3个品牌的独立子图轴,所有绘图操作会默认叠加在同一个坐标系下,无法生成独立分图
- 归一化计算:如果原始数据各plant的数值总和不是100%,取消代码中归一化行的注释即可自动计算各plant占比,保证单品牌下总和为100%
- 布局调整:如需横向排列3张图表,将
plt.subplots参数改为nrows=1, ncols=3, figsize=(15,4)即可 - 样式调整:柱子宽度、填充色、标签字体大小均可通过修改对应绘图参数自定义,匹配参考效果
参考效果:
内容的提问来源于stack exchange,提问作者SeanjeeWatara
相关产品推荐
相关产品推荐

