绘制Pandas DataFrame时X轴刻度显示Jan-Jan,如何改为仅显示Jan-Dec?
解决X轴多余Jan刻度的问题
问题原因
你处理后的DataFrame索引是%m-%d格式的字符串,而非datetime对象,导致mdates.MonthLocator()和mdates.DateFormatter()无法正确识别月份位置——matplotlib的日期工具只对datetime类型索引生效。此时X轴刻度是matplotlib自动根据字符串索引生成的,因此出现了多余的Jan刻度。
解决方案
下面提供两种可行的修改方案:
方案一:修复索引类型,利用日期工具处理
将字符串索引转换为datetime类型(用固定年份做基准,不影响月份显示),再通过日期工具设置刻度,最后移除多余的刻度:
import matplotlib.pyplot as plt import matplotlib.dates as mdates import numpy as np import pandas as pd # 生成原始数据 ts = pd.Series(np.random.randn(365*4), index=pd.date_range("1/1/2000", periods=365*4)) df = pd.DataFrame(np.random.randn(365*4, 1), index=ts.index, columns=["A"]) df['year'] = df.index.year # 将date列转换为datetime(基准年选任意年份即可) df['date'] = pd.to_datetime('2000-' + df.index.strftime('%m-%d')) df = df.set_index(['year', 'date'])['A'].unstack(-2) fig, axs = plt.subplots(figsize=(14, 5)) df.plot(ax=axs) # 设置月份刻度和格式 axs.xaxis.set_major_locator(mdates.MonthLocator()) axs.xaxis.set_major_formatter(mdates.DateFormatter('%b')) # 移除最后一个多余的Jan刻度 ticks = axs.get_xticks() axs.set_xticks(ticks[:-1]) plt.tight_layout() plt.show()
方案二:手动指定刻度位置和标签
直接根据每个月第一天在字符串索引中的位置,手动设置12个月份的刻度:
import matplotlib.pyplot as plt import numpy as np import pandas as pd # 生成原始数据 ts = pd.Series(np.random.randn(365*4), index=pd.date_range("1/1/2000", periods=365*4)) df = pd.DataFrame(np.random.randn(365*4, 1), index=ts.index, columns=["A"]) df['year'] = df.index.year df['date'] = df.index.strftime('%m-%d') df = df.set_index(['year', 'date'])['A'].unstack(-2) fig, axs = plt.subplots(figsize=(14, 5)) df.plot(ax=axs) # 找到每个月第一天在索引中的位置 month_positions = [df.index.get_loc(f'{month:02d}-01') for month in range(1, 13)] # 设置刻度位置和对应月份标签 axs.set_xticks(month_positions) axs.set_xticklabels(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']) plt.tight_layout() plt.show()
说明
两种方案都能解决多余Jan刻度的问题:方案一更贴合matplotlib的日期处理逻辑,方案二则更直接,无需转换索引类型。
内容的提问来源于stack exchange,提问作者thowild
相关产品推荐
相关产品推荐

