如何使用Seaborn Barplot在单个条形内展示多数值(堆叠条形图实现)
当然可以实现!虽然Seaborn本身没有专门的堆叠条形图API,但它基于Matplotlib构建,我们可以结合两者完成你想要的效果;另外,如果你想单独展示三个组成数值对应同一测量项,用Seaborn做分组条形图就很方便,下面一步步说明:
方法1:堆叠条形图(展示总Lead Time + 内部组成)
这种方式能让每个条形的高度对应总Lead Time,同时在条形内部堆叠显示三个组成部分的数值,步骤如下:
- 导入必要库并构造示例数据
import seaborn as sns import matplotlib.pyplot as plt import pandas as pd # 模拟你的数据:5个测量项,每个对应3个组成部分 data = { "Measurement": ["Item1", "Item2", "Item3", "Item4", "Item5"], "Component_A": [12, 18, 9, 15, 10], "Component_B": [6, 8, 7, 5, 9], "Component_C": [4, 5, 3, 6, 4] } df = pd.DataFrame(data)
- 绘制堆叠条形图
# 应用Seaborn的美观样式 sns.set_style("whitegrid") # 创建画布和轴对象 fig, ax = plt.subplots(figsize=(10, 6)) # 定义组成部分和对应的颜色(用Seaborn调色板) components = ["Component_A", "Component_B", "Component_C"] colors = sns.color_palette("Greens", n_colors=3) # 初始化堆叠的底部位置为0 bottom = [0] * len(df) # 循环绘制每个组成部分的条形 for comp, color in zip(components, colors): ax.bar(df["Measurement"], df[comp], bottom=bottom, label=comp, color=color) # 更新底部位置,让下一个条形堆叠在当前条形上方 bottom = [b + val for b, val in zip(bottom, df[comp])] # 可选:为每个总Lead Time添加数值标签 for idx, total in enumerate(df[components].sum(axis=1)): ax.text(idx, total + 0.6, f"{total}", ha="center", fontweight="bold") # 设置图表标签和标题 ax.set_xlabel("Measurement Items", fontsize=12) ax.set_ylabel("Total Lead Time", fontsize=12) ax.set_title("Stacked Lead Time by Measurement Item", fontsize=14) # 添加图例说明组成部分 ax.legend(title="Lead Time Components") # 调整布局防止标签被截断 plt.tight_layout() plt.show()
方法2:单独展示三个组成数值(分组条形图)
如果更想清晰对比每个测量项的三个组成部分的具体数值,分组条形图会更直观,Seaborn的barplot可以直接实现,只需先把数据转为长格式:
- 转换数据格式并绘制分组条形图
# 将宽格式数据转为长格式,方便Seaborn处理 df_long = df.melt( id_vars="Measurement", var_name="Component", value_name="Lead Time" ) # 应用Seaborn样式 sns.set_style("whitegrid") fig, ax = plt.subplots(figsize=(10, 6)) # 绘制分组条形图 sns.barplot( data=df_long, x="Measurement", y="Lead Time", hue="Component", palette="Greens" ) # 可选:为每个条形添加数值标签 for patch in ax.patches: height = patch.get_height() ax.text( patch.get_x() + patch.get_width()/2., height + 0.4, f"{height}", ha="center", fontsize=10 ) # 设置图表标签和标题 ax.set_xlabel("Measurement Items", fontsize=12) ax.set_ylabel("Lead Time", fontsize=12) ax.set_title("Lead Time Components by Measurement Item", fontsize=14) plt.tight_layout() plt.show()
两种方法各有侧重:堆叠图适合展示总和与内部占比关系,分组图适合直接对比各组成部分的数值大小,你可以根据需求选择。
内容的提问来源于stack exchange,提问作者MF1893
相关产品推荐
相关产品推荐

