xticks 值作为 matplotlib 图中的数据框列值

Ash*_*ade 5 python matplotlib dataframe pandas

我下面有 data.frame

      values    years
0    24578.0  2007-09
1    37491.0  2008-09
2    42905.0  2009-09
3    65225.0  2010-09
4   108249.0  2011-09
5   156508.0  2012-09
6   170910.0  2013-09
7   182795.0  2014-09
8   233715.0  2015-09
9   215639.0  2016-09
10  215639.0      TTM
Run Code Online (Sandbox Code Playgroud)

附上绘制的图像,问题是我希望年份值“2007-09”到“TTM”作为xtick图中的值

绘制的图像已附加,问题是我希望将年份值“2007-09”更改为“TTM”作为图中的 xtick 值

Grr*_*Grr 8

一种方法是访问 x 数据中 xticks 的当前 idice。使用该值从中选择值df.year,然后将标签设置为这些值:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
df.plot(ax=ax)
tick_idx = plt.xticks()[0]
year_labels = df.years[tick_idx].values
ax.xaxis.set_ticklabels(year_labels)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

您还可以设置 x 轴来显示所有年份,如下所示:

fig, ax = plt.subplots()
df.plot(ax=ax, xticks=df.index, rot=45)
ax.set_xticklabels(df.years)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述