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

Power BI:如何实现带分组状态标签的柱形图?

实现带分组标签的交易状态柱状图

要做出你需要的分组样式图表,核心是给同组状态统一视觉样式,再在X轴区域添加分组标题。下面用Python的matplotlib和pandas给出可复用的实现方案:

1. 准备数据

假设你的数据集已经处理好,包含status(具体交易状态)、count(交易数量)、group(分组类别)三列,先模拟一份数据(替换成你的真实数据即可):

import pandas as pd
import matplotlib.pyplot as plt

# 模拟你的数据结构
data = {
    'status': ['completed', 'start', 'InProgress', 'wait', 'failed', 'stopped'],
    'count': [150, 80, 60, 40, 30, 20],
    'group': ['completed', 'ongoing', 'ongoing', 'ongoing', 'interrupted', 'interrupted']
}
df = pd.DataFrame(data)

2. 规划X轴布局

先固定状态的显示顺序,再给每个状态分配X轴坐标,同时计算每组的中心位置,用来放分组标签:

# 按需求指定状态显示顺序
status_order = ['completed', 'start', 'InProgress', 'wait', 'failed', 'stopped']
df = df.set_index('status').loc[status_order].reset_index()

# 给每个状态分配X轴位置
x_coords = range(len(df))

# 计算每个分组的中心坐标
group_centers = {}
for group_name in df['group'].unique():
    # 找出当前组所有状态的X坐标
    group_x = [i for i, g in enumerate(df['group']) if g == group_name]
    # 计算中心位置
    group_centers[group_name] = sum(group_x) / len(group_x)

3. 绘制图表并添加分组标签

plt.figure(figsize=(10, 6))

# 给不同分组设置统一颜色
color_map = {
    'completed': '#27ae60',
    'ongoing': '#3498db',
    'interrupted': '#e74c3c'
}
bar_colors = [color_map[g] for g in df['group']]

# 绘制柱状图
plt.bar(x_coords, df['count'], color=bar_colors)

# 设置X轴刻度为具体状态
plt.xticks(x_coords, df['status'], rotation=45)

# 在X轴下方添加分组标签
for group_name, center_pos in group_centers.items():
    plt.text(center_pos, -max(df['count']) * 0.06, group_name, 
             ha='center', fontweight='bold', fontsize=12)

# 设置图表标签和标题
plt.ylabel('transaction count')
plt.title('Transaction Status Distribution')

# 调整底部边距,避免分组标签被截断
plt.subplots_adjust(bottom=0.2)

plt.show()

效果说明

  • 同组状态使用相同颜色,一眼就能区分组别
  • 分组标签放在X轴下方的中心位置,和对应组的状态对齐
  • 可根据需求调整颜色、图表尺寸、标签位置等参数

内容的提问来源于stack exchange,提问作者priya

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 15:57:20