格式化 x 轴代码以仅显示连续时间序列线图的年份

Formatting x-axis tickers to show only the years for a continuous time series line graph

我可以绘制我想要的图表,但我想更改 x 轴代码以仅显示年份而不是显示每年的相应月份,因为数据范围非常大。有没有一种方法可以在不更改数据集的情况下执行此操作?我目前正在使用 matplotlib.pyplot 绘制此图。

这是我目前拥有的图表,代码是每年的每个月。 Time Series Graph

这是我现在拥有的数据框示例。 Data Table

希望有人能帮我解决这个问题!谢谢!

有很多方法可以解决这个问题:

  1. 添加另一列仅表示几个月,并将该列用作 X,PS:实际情节不会改变。
  2. 使用 fig.autofmt__date() 这会倾斜日期,以便整个日期都可见。Check this documentation for further details.

我要生成一些“随机”数据,您应该从数据框中插入数据。

# generate some data
# dates is a list of strings. For example, the first element
# will be "2005-01".
dates = []
for y in range(2005, 2013):
    dates += [str(y)+"-"+str(m) for m in range(1, 13)]
x = np.arange(len(dates))
y = np.cos(x / 4)

f, ax = plt.subplots()
ax.plot(x, y)

# xticks and labels: select only the first
# unique year
xticks, xlabels = [], []
for t, d in zip(x, dates):
    if (not xlabels) or (d[:4] != xlabels[-1]):
        xticks.append(t)
        # keep only the year
        xlabels.append(d[:4])

ax.set_xticks(xticks)
ax.set_xticklabels(xlabels)
# f.autofmt_xdate(rotation=60, ha="right")

如果您想进一步自定义日期的外观,您可以删除最后一行的注释。