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

如何用Python绘制按元素分组同色、不同条件值并排的柱状图

解决方案

不需要重构现有DataFrame,直接基于matplotlib按元素分组绘制即可满足需求,核心逻辑为:

  • 为每个元素分配X轴基准位置
  • 根据单个元素对应的条件数量计算每个柱子的偏移量,实现多柱并排、单柱自动居中,不会为缺失条件预留空白
  • 直接使用数据中预定义的颜色为对应元素的所有柱子赋值

完整可运行代码

import matplotlib.pyplot as plt
import pandas as pd

col1 = ["A","B","C","D","A","E","B","F","C","A", "G"]
col2 = [5,3.5,4,7,3.7,2.5,4,6,5.5,3,4.5]
col3 = ["Cond1","Cond1","Cond1","Cond1","Cond2","Cond1","Cond2","Cond1","Cond2","Cond3","Cond1"]
col4 = ["green","red","blue","yellow","green","purple","red","brown","blue","green","black"]

data = pd.DataFrame(col1,columns=["Names"])
data["Values"] = col2
data["Condition"] = col3
data["Color"] = col4

# 基础参数配置
single_bar_width = 0.25  # 单根柱子的宽度
all_names = data["Names"].unique()  # 所有元素名称列表
x_base_pos = range(len(all_names))  # 每个元素对应的X轴基准位置

fig, ax = plt.subplots(figsize=(8, 4))

# 按元素分组遍历绘制
for name_idx, name in enumerate(all_names):
    current_group = data[data["Names"] == name].reset_index(drop=True)
    bar_count = len(current_group)  # 当前元素的柱子总数
    # 计算每个柱子的X偏移量,保证多柱并排、单柱居中
    x_offsets = [i * single_bar_width - (bar_count -1)*single_bar_width/2 for i in range(bar_count)]
    # 逐根绘制当前元素的所有柱子
    for bar_idx in range(bar_count):
        x = x_base_pos[name_idx] + x_offsets[bar_idx]
        ax.bar(x, current_group.loc[bar_idx, "Values"], 
               width=single_bar_width, 
               color=current_group.loc[bar_idx, "Color"],
               label=name if bar_idx == 0 else "")  # 避免图例重复生成

# 配置X轴刻度
ax.set_xticks(x_base_pos)
ax.set_xticklabels(all_names)
# 配置坐标轴与图例
ax.set_xlabel("元素名称")
ax.set_ylabel("对应数值")
ax.legend(title="元素")

plt.tight_layout()
plt.show()

效果说明

  • 同一元素的所有柱子颜色完全相同,不同元素颜色区分
  • 仅存在1个条件的元素(D、E、F、G)的柱子自动居中显示,不会为缺失条件预留空白位置
  • 存在多个条件的元素(A对应3个条件、B和C对应2个条件)的柱子自动并排排列

内容的提问来源于stack exchange,提问作者G. Cuticchia

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 03:24:04