2014-04-29 16 views
2

說我有一個數據幀和我的箱線圖:控制表示

df.boxplot(column='value', by='date') 

其中date是D型細胞datetime64[ns]的列。當我運行上述繪圖時,x軸顯示滴答標籤,如下所示:

2014-02-24 00:00:00 

哪個非常羅嗦。我想只顯示類似2014-02-24(甚至更好,必須控制日期的格式(例如,「月 - 日」)

有沒有辦法在大熊貓做到這一點的能力嗎?

對於參考,我使用:

  • matplotlib:1.3.1
  • 大熊貓:0.13.1
  • numpy的:1.8.1

,這裏是我的日期:

In <88>: df['date'].head() 
Out<88>: 
0 2014-02-24 
1 2014-02-24 
2 2014-02-24 
3 2014-02-24 
4 2014-02-24 
Name: date, dtype: datetime64[ns] 

回答

2

如果你有ax對象(從ax = plt.add_subplot(1,1,1)ax = plt.gca()例如),那麼你可以使用一個DateFormatter對象如下面的代碼來設置你想要的任何字符串格式。

字符串選項由strftime()給出。

import matplotlib.dates as mdate 

df.boxplot(...) 

ax = plt.gca() # Gets the current axes 

# String giving your date format as "MM-DD" e.g. "04-29" 
date_fmt = '%m-%d' 

date_formatter = mdate.DateFormatter(date_fmt) 
ax.xaxis.set_major_formatter(date_formatter) 

fig.autofmt_xdate() # Sets your dates slightly diagonal to fit better. 
+0

感謝。我無法正常工作。自動旋轉效果很好,但日期仍然格式化爲「2014-02-24 00:00:00」..嗯。而且我一定要用'add_subplot'返回的軸來調用'boxplot',我確信所有的東西都是 –

+0

。謝謝 –

+0

此外,它並沒有聽到我想對軸進行的其他更改(例如'ax.set_title(「Foo」)') –

2

也許你可以創建一個新的字符串列的值你想:

df['date1']=df.date.apply(lambda x: x.strftime('%m-%y')) 
ax=df.boxplot(column='value', by='date1') 

enter image description here

+0

儘管我得到了:'numpy.datetime64'對象沒有屬性'strftime' –

+0

這是令人驚訝的。你可以添加一行'df ['date'] = pd.to_datetime(df.date)',看看是否有幫助。我懷疑問題源於你構造數據框和它的'dtypes'的方式。 –