【问题标题】:Formatting of DateTimeIndex in plot pandas绘图熊猫中 DateTimeIndex 的格式
【发布时间】:2016-03-16 09:56:34
【问题描述】:

我无法破译使用 pandas 更改滴答频率和日期格式的文档。

例如:

import numpy as np
import pandas as pd
import pandas.io.data as web
import matplotlib as mpl
%matplotlib inline

mpl.style.use('ggplot')
mpl.rcParams['figure.figsize'] = (8,6)

# grab some price data
px = web.DataReader('AAPL', "yahoo", '2010-12-01')['Adj Close']
px_m = px.asfreq('M', method='ffill')
rets_m = px_m.pct_change()

rets_m.plot(kind='bar')

生成此图:

哎呀。我怎样才能让蜱每个月或每个季度或一些明智的?以及如何更改日期格式以摆脱时间?

我用ax.set_xticks()ax.xaxis.set_major_formatter 尝试了各种不同的方法,但还是没搞清楚。

【问题讨论】:

标签: date numpy pandas matplotlib format


【解决方案1】:

如果使用pandas中的plot方法,matplotlibset_major_locatorset_major_formatter方法很可能是fail。如果您想继续使用 pandas``plot 方法,手动调整刻度可能会更容易。

#True if it is the first month of a quarter, False otherwise
xtick_idx = np.hstack((True, 
                       np.diff(rets_m.index.quarter)!=0))

#Year-Quarter string for the tick labels.
xtick     = ['{0:d} quarter {1:d}'.format(*item) 
             for item in zip(rets_m.index.year, rets_m.index.quarter)]
ax        =rets_m.plot(kind='bar')

#Only put ticks on the 1st months of each quarter
ax.xaxis.set_ticks(np.arange(len(xtick))[xtick_idx])

#Adjust the ticklabels
ax.xaxis.set_ticklabels(np.array(xtick)[xtick_idx])

【讨论】:

  • 谢谢!源自这个答案,我写了following example
  • @Dror 您应该将此添加为正确答案,因为它包含其他信息。
猜你喜欢
  • 1970-01-01
  • 2020-12-27
  • 1970-01-01
  • 1970-01-01
  • 2013-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-08
相关资源
最近更新 更多