如何更改图表标签的日期类型

时间:2016-02-03 06:52:05

标签: python date pandas matplotlib label

enter image description here

您可以看到return - >日期类型out[7] 但 你可以看到o 2015.01.02 - >图表上的ut[17]仅显示x-axis

如何更改0, 50, 100

之类的x-axis

对此有任何建议吗?

1 个答案:

答案 0 :(得分:1)

您可以先尝试转换date to_datetime列,然后set_index,并将axis x的最后更改日期时间格式改为strftime和{ {3}}:

import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

df['date'] = pd.to_datetime(df['date'] )
print df
        date   a   b  c
0 2015-01-02  10  20  3
1 2015-01-05  40  50  6
2 2015-01-06  70  80  8
3 2015-01-07  80  50  9
4 2015-01-08  90  50  3
5 2015-01-09  10  20  3
6 2015-01-10  40  50  6
7 2015-01-11  70  80  8
8 2015-01-12  80  50  9
9 2015-01-13  90  50  3

a = df['a'].pct_change()
b = df['b'].pct_change()
c = df['c'].pct_change()
df['corr'] = pd.rolling_corr(a,b,3)
df = df.set_index('date')
print df
             a   b  c      corr
date                           
2015-01-02  10  20  3       NaN
2015-01-05  40  50  6       NaN
2015-01-06  70  80  8       NaN
2015-01-07  80  50  9  0.941542
2015-01-08  90  50  3  0.914615
2015-01-09  10  20  3  0.776273
2015-01-10  40  50  6  0.999635
2015-01-11  70  80  8  0.985112
2015-01-12  80  50  9  0.941542
2015-01-13  90  50  3  0.914615
ax = df['corr'].plot()

ticklabels = df.index.strftime('%Y.%m.%d')
ax.xaxis.set_major_formatter(ticker.FixedFormatter(ticklabels))
plt.show()

set_major_formatter

通过评论编辑:
这似乎是错误,但您可以更改index,然后轮换labels

df['date'] = pd.to_datetime(df['date'] )
#print df


a = df['a'].pct_change()
b = df['b'].pct_change()
c = df['c'].pct_change()
df['corr'] = pd.rolling_corr(a,b,3)

df = df.set_index('date')
print df
             a   b  c      corr
date                           
2015-01-02  10  20  3       NaN
2015-01-05  40  50  6       NaN
2015-01-06  70  80  8       NaN
2015-01-07  80  50  9  0.941542
2015-01-08  90  50  3  0.914615
2015-01-09  10  20  3  0.776273
2015-01-10  40  50  6  0.999635
2015-01-11  70  80  8  0.985112
2015-01-12  80  50  9  0.941542
2015-01-13  90  50  3  0.914615
df.index = df.index.strftime('%Y.%m.%d')
print df
             a   b  c      corr
2015.01.02  10  20  3       NaN
2015.01.05  40  50  6       NaN
2015.01.06  70  80  8       NaN
2015.01.07  80  50  9  0.941542
2015.01.08  90  50  3  0.914615
2015.01.09  10  20  3  0.776273
2015.01.10  40  50  6  0.999635
2015.01.11  70  80  8  0.985112
2015.01.12  80  50  9  0.941542
2015.01.13  90  50  3  0.914615

ax = df['corr'].plot()

plt.xticks(rotation=90)
plt.show()

graph_corr