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

如何绘制指定样式柱状图?含ClaimID等字段的时间维度数据绘图指导

实现目标柱状图的分步方案

一、先搞定数据预处理

首先得把日期字段转成标准格式,再按时间维度(日/月/年)和Agent分组统计Claim数量——核心是拿到每个时间点下各Agent的订单数。

用Pandas处理的话,代码参考:

import pandas as pd

# 读入数据(假设是CSV格式,其他格式对应调整)
df = pd.read_csv("your_data_file.csv")

# 把字符串日期转成datetime格式,确保时间维度能正确分组
df['Creation_date'] = pd.to_datetime(df['Creation_date'])

# 按月份+Agent分组统计Claim数,按日就把freq='M'改成'D',按年用'Y'
# unstack是把Agent转成列,方便后续画并列柱子
df_grouped = df.groupby([pd.Grouper(key='Creation_date', freq='M'), 'Agent'])['ClaimID'].count().unstack(fill_value=0)

这里fill_value=0很关键,能补全某个时间点没有订单的Agent数据,避免绘图时柱子缺失。

二、绘制基础柱状图

用Matplotlib就能实现常规并列柱状图,代码如下:

import matplotlib.pyplot as plt

# 设定画布大小,避免内容挤在一起
fig, ax = plt.subplots(figsize=(12, 6))

bar_width = 0.25  # 柱子宽度,按需调整
positions = range(len(df_grouped.index))  # 每个时间点的基准位置

# 遍历每个Agent,绘制对应的柱子
for idx, agent in enumerate(df_grouped.columns):
    ax.bar([p + bar_width*idx for p in positions], df_grouped[agent], width=bar_width, label=agent)

# 调整x轴标签,让日期显示居中且不重叠
ax.set_xticks([p + bar_width*(len(df_grouped.columns)-1)/2 for p in positions])
ax.set_xticklabels(df_grouped.index.strftime('%Y-%m'), rotation=45)

# 添加标题和轴标签
ax.set_title('各Agent订单量时间统计')
ax.set_xlabel('日期')
ax.set_ylabel('Claim数量')
ax.legend(title='Agent')

# 自动调整布局,防止标签被截断
plt.tight_layout()
plt.show()

三、匹配目标图的样式优化

如果目标图有特定样式,直接加对应代码即可:

  • 自定义颜色:在bar函数里加color参数,比如color=['#2E86AB', '#F24C4E', '#F7D060']
  • 柱子上方显示数值:在遍历Agent的循环里补充这段:
for p, val in zip([pos + bar_width*idx for pos in positions], df_grouped[agent]):
    ax.text(p, val + 0.3, str(val), ha='center', va='bottom')
  • 添加网格线:ax.grid(axis='y', linestyle='--', alpha=0.7)
  • 调整背景色:ax.set_facecolor('#f8f9fa')

嫌Matplotlib写起来麻烦的话,用Seaborn更简洁,直接用hue参数区分Agent:

import seaborn as sns

# 把分组后的数据转成长格式
df_long = df_grouped.reset_index().melt(id_vars='Creation_date', var_name='Agent', value_name='ClaimCount')

sns.barplot(data=df_long, x='Creation_date', y='ClaimCount', hue='Agent', palette='Set2')
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

四、常见问题排查

  • 柱子重叠/错位:调整bar_width的大小,或检查positions的计算逻辑
  • 时间轴显示混乱:确认Creation_date已转成datetime类型,用strftime格式化显示的日期字符串
  • 部分Agent数据不显示:分组时务必加fill_value=0,补全缺失的Agent数据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 21:00:19