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

修改Pandas绘制的每小时活跃用户统计图的X轴刻度

修改Pandas时间分组直方图的X轴刻度

嘿,我来帮你调整X轴刻度的显示~首先注意下,你代码里用的pd.TimeGrouper在新版Pandas(0.21及以后)已经被弃用了,换成pd.Grouper会更兼容。接下来我们可以自定义X轴的刻度文本,让它更清晰易读,具体修改后的代码如下:

import pandas as pd
import datetime
from matplotlib import pyplot as plt

# 你的时间数据(这里补了几个示例值)
data = [datetime.datetime(2000, 1, 1, 11, 5, 44, 233144), 
        datetime.datetime(2000, 1, 1, 12, 5, 45, 175807),
        datetime.datetime(2000, 1, 1, 11, 15, 30),
        datetime.datetime(2000, 1, 1, 13, 20, 10),
        datetime.datetime(2000, 1, 1, 12, 40, 5)]

df = pd.DataFrame(data, columns=['Users'])
df.index = pd.to_datetime(df['Users'])

# 用新版的pd.Grouper替代TimeGrouper
hourly_counts = df.groupby(pd.Grouper(key='Users', freq='60Min')).count()

# 绘图时获取Axes对象,方便修改刻度
ax = hourly_counts.plot(kind='bar', title='Activity by Hour', figsize=(10,8))

# 自定义X轴刻度:把时间格式化为「小时:分钟」的样式,同时倾斜标签避免重叠
ax.set_xticklabels([dt.strftime('%H:%M') for dt in hourly_counts.index], rotation=45)

plt.xlabel('Time')
plt.ylabel('Number of Users')
plt.tight_layout()  # 自动调整布局,防止标签被截断
plt.show()

几个关键调整点:

  • 替换pd.TimeGrouper为pd.Grouper(key='Users', freq='60Min'),适配新版Pandas的API
  • 将分组结果存入hourly_counts变量,方便直接获取分组后的时间索引
  • 通过ax.set_xticklabels()自定义刻度文本,你可以根据需求修改strftime的格式:
    • 想显示完整日期+时间:用'%Y-%m-%d %H:%M'
    • 只想显示小时:用'%H'
  • 添加rotation=45让刻度标签倾斜,避免横向重叠;plt.tight_layout()确保标签不会被图框截断

如果需要更灵活的刻度控制(比如只显示特定小时的刻度),还可以手动指定刻度位置:

# 示例:只显示偶数小时的刻度
target_ticks = [i for i, dt in enumerate(hourly_counts.index) if dt.hour % 2 == 0]
target_labels = [dt.strftime('%H:%M') for i, dt in enumerate(hourly_counts.index) if dt.hour % 2 == 0]

ax.set_xticks(target_ticks)
ax.set_xticklabels(target_labels, rotation=45)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:35:54