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

如何修复Matplotlib多折线图X轴显示两类值的问题

问题:Matplotlib折线图X轴异常显示type类别,需仅保留年份

我用Matplotlib绘制DataFrame中type列不同类别随年份变化的折线图,折线能正常生成,但X轴同时显示日期和一个type类别,无法去除,希望X轴仅显示年份。

代码

ctdf = df.groupby(["year"])["type"].value_counts().unstack(fill_value=0).stack()
print(ctdf)
from matplotlib import pyplot as plt
fig, ax = plt.subplots()

# key gives the group name (i.e. category), data gives the actual values
for key, data in ctdf.groupby('type'):
    data.plot(x='year', ax=ax, label=key, legend=True)
    plt.xticks(rotation = 45, ha = 'right')
    plt.xlabel('year')

ctdf数据

year        type           
2002-01-01  Robot              0
            Smart Speaker      0
            Virtual Agent      1
            Voice Assistant    0
2003-01-01  Robot              0
                              ..
2019-01-01  Voice Assistant    0
2020-01-01  Robot              6
            Smart Speaker      2
            Virtual Agent      3
            Voice Assistant    1
Length: 68, dtype: int64

当前异常图表

折线图显示多条曲线,但X轴混乱,同时出现日期和type类别


解决方案

问题根源

你的ctdf是**多层索引(MultiIndex)**结构,year和type都属于索引层级,循环绘图时pandas会把整个索引信息带入X轴,导致显示混乱。

修复方案一:重置索引后绘图

  1. 先将多层索引转换为普通列,同时给计数列命名:
    ctdf = df.groupby(["year"])["type"].value_counts().unstack(fill_value=0).stack().reset_index(name='count')
    
  2. 绘图时提取年份设置X轴刻度:
    from matplotlib import pyplot as plt
    import pandas as pd
    
    fig, ax = plt.subplots()
    
    for key, data in ctdf.groupby('type'):
        # 按年份排序保证折线顺序正确
        data_sorted = data.sort_values('year')
        data_sorted.plot(x='year', y='count', ax=ax, label=key, legend=True)
    
    # 替换X轴标签为年份
    ax.set_xticks(ctdf['year'].unique())
    ax.set_xticklabels([pd.to_datetime(y).year for y in ctdf['year'].unique()])
    plt.xticks(rotation=45, ha='right')
    plt.xlabel('Year')
    plt.tight_layout()  # 避免标签被截断
    plt.show()
    

修复方案二:直接用unstack后的DataFrame绘图(更简洁)

无需再stack,直接用宽表格式绘图:

ctdf = df.groupby(["year"])["type"].value_counts().unstack(fill_value=0)

fig, ax = plt.subplots()
ctdf.plot(ax=ax)

# 设置X轴仅显示年份
ax.set_xticks(ctdf.index)
ax.set_xticklabels([pd.to_datetime(y).year for y in ctdf.index])
plt.xticks(rotation=45, ha='right')
plt.xlabel('Year')
plt.tight_layout()
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 07:06:33