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

在Matplotlib中绘制Pandas数据时如何显示次要刻度标签?

问题

我尝试绘制一个Pandas DataFrame,但无法显示次要刻度上的标签。该DataFrame结构如下:

day_of_week   hour   count
0             0      150
0             1      673
...
1             0      734
1             1      35
...

其中day_of_week代表星期几(周一、周二等),hour为一天中的0-23时。我希望将其绘制成时间序列,主刻度设为午夜(次日切换点),次要刻度每6小时一个。我对DataFrame做了修改并尝试绘图,代码如下:

days = {0: "Mon", 1: "Tue", 2: "Wed", 3: "Thu", 4: "Fri", 5: "Sat", 6: "Sun"}

df["dow"] = df["day_of_week"].apply(lambda x: days.get(x))
df["axis"] = (df["dow"] + " " + df["hour"].astype(str))

fig, ax = plt.subplots()

ax.plot(time_tweets["axis"], time_tweets["count"])

ax.grid(which="major", axis="x", linestyle="-", linewidth=2)

ax.xaxis.set_major_locator(MultipleLocator(24))
ax.xaxis.set_minor_locator(MultipleLocator(6))

plt.xticks(rotation=45, minor=True, ha="right")
plt.xticks(rotation=45, minor=False, ha="right")

目前主刻度及其标签、次要刻度线、仅主刻度的网格均正常,但次要刻度标签不显示。尝试添加plt.minorticks_on()或plt.setp(ax.get_xticklabels(minor=True), visible=True),仍无法显示次要刻度标签。


解决方案

问题核心在于用字符串作为x轴刻度值时,Matplotlib的MultipleLocator仅对数值型坐标生效,无法自动生成次要刻度标签。以下是修复方案:

  1. 转换为数值型连续x轴
    放弃字符串拼接的axis列,改用累计小时数作为数值坐标,比如周一0点为0,周二0点为24,以此类推:

    df["total_hours"] = df["day_of_week"] * 24 + df["hour"]
    
  2. 基于数值坐标绘图
    使用total_hours作为x轴参数,让刻度定位器正常工作:

    fig, ax = plt.subplots()
    ax.plot(df["total_hours"], df["count"])
    
  3. 手动设置主/次要刻度与标签

    • 主刻度(午夜):筛选hour=0的行,提取对应total_hours作为刻度位置,星期缩写作为标签
    • 次要刻度(每6小时):筛选小时为0、6、12、18的行,提取对应total_hours作为刻度位置,小时数作为标签
    # 配置主刻度
    major_ticks = df[df["hour"] == 0]["total_hours"].tolist()
    major_labels = df[df["hour"] == 0]["dow"].tolist()
    ax.set_xticks(major_ticks)
    ax.set_xticklabels(major_labels)
    
    # 配置次要刻度
    minor_ticks = df[df["hour"].isin([0,6,12,18])]["total_hours"].tolist()
    minor_labels = df[df["hour"].isin([0,6,12,18])]["hour"].astype(str).tolist()
    ax.set_xticks(minor_ticks, minor=True)
    ax.set_xticklabels(minor_labels, minor=True)
    
  4. 调整样式并显示
    添加网格、调整刻度标签旋转角度:

    ax.grid(which="major", axis="x", linestyle="-", linewidth=2)
    plt.xticks(rotation=45, ha="right")
    plt.setp(ax.get_xticklabels(minor=True), rotation=45, ha="right")
    plt.show()
    

完成以上步骤后,主刻度的星期标签和次要刻度的小时标签就能正常显示了。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 15:20:56