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

使用Pandas绘图如何显示X轴全部Period类型日期标签(无需fig、ax)

问题:Pandas折线图Period类型X轴显示全部刻度标签

我用Pandas绘图功能创建折线图时,X轴的每个刻度标签没有全部显示。查过一些解决方案,但大多不是用Period类型作为X轴数据的情况。想问能不能不使用fig、ax变量实现显示所有X轴日期标签?

我的代码:

from matplotlib import pyplot as plt 
import numpy as np

fig = tweets_per_month.plot(x = "month_year", legend= False, kind='line', figsize=(25, 8), fontsize = 15, grid = True, rot = 45).get_figure()
plt.xlabel('Date', fontsize=15)
plt.ylabel('Number of tweets', fontsize=15)

fig.savefig('Tweet_count_REL2.png')

相关说明:

  • 数据表示例:month_year列为Period类型(格式如2020-01这类年月周期),对应每条数据的推文数量
  • 当前生成的图表:X轴仅显示部分日期刻度,并非所有Period标签都展示

解决方案:不用fig/ax也能显示全部X轴标签

你可以直接用Matplotlib的全局plt.xticks()方法,手动指定要显示的X轴刻度值,不需要额外定义fig、ax变量。修改后的代码如下:

from matplotlib import pyplot as plt 
import numpy as np

# 直接绘图,无需提前获取fig对象
tweets_per_month.plot(x = "month_year", legend= False, kind='line', figsize=(25, 8), fontsize = 15, grid = True)
plt.xlabel('日期', fontsize=15)
plt.ylabel('推文数量', fontsize=15)

# 关键步骤:强制显示所有Period类型的X轴标签
plt.xticks(
    ticks=tweets_per_month['month_year'],
    labels=tweets_per_month['month_year'].astype(str),
    rotation=45,
    fontsize=15
)

# 保存并关闭图表
plt.savefig('Tweet_count_REL2.png')
plt.close()

代码说明

  • ticks参数传入所有Period类型的X轴数据,确保每个标签都对应一个刻度位置
  • labels把Period转为字符串,避免绘图时出现格式兼容问题
  • 全程依赖Matplotlib的全局plt方法操作,完全不需要用到fig、ax变量

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 23:27:10