【问题标题】:xticks values as dataframe column values in matplotlib plot [duplicate]xticks 值作为 matplotlib 图中的数据框列值 [重复]
【发布时间】:2017-09-15 15:29:27
【问题描述】:
下面有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
附上绘制的图像,问题是我希望年份值 '2007-09' 到 'TTM' 作为图中的 xtick 值
【问题讨论】:
标签:
python
pandas
matplotlib
dataframe
【解决方案1】:
一种方法是访问 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)
您还可以将 x 轴设置为显示所有年份,如下所示:
fig, ax = plt.subplots()
df.plot(ax=ax, xticks=df.index, rot=45)
ax.set_xticklabels(df.years)