2010-08-15 144 views
16

我有一個由日期 - 值對組成的數據集。我想在一個條形圖中用x軸的特定日期繪製它們。如何使用matplotlib繪製x軸上的特定日期的數據

我的問題是matplotlib在整個日期範圍內分配xticks;並繪製數據使用點。

日期均爲datetime對象。這裏的數據集的樣本:

data = [(DT.datetime.strptime('2010-02-05', "%Y-%m-%d"), 123), 
     (DT.datetime.strptime('2010-02-19', "%Y-%m-%d"), 678), 
     (DT.datetime.strptime('2010-03-05', "%Y-%m-%d"), 987), 
     (DT.datetime.strptime('2010-03-19', "%Y-%m-%d"), 345)] 

這裏使用一個可運行的代碼示例pyplot

import datetime as DT 
from matplotlib import pyplot as plt 

data = [(DT.datetime.strptime('2010-02-05', "%Y-%m-%d"), 123), 
     (DT.datetime.strptime('2010-02-19', "%Y-%m-%d"), 678), 
     (DT.datetime.strptime('2010-03-05', "%Y-%m-%d"), 987), 
     (DT.datetime.strptime('2010-03-19', "%Y-%m-%d"), 345)] 

x = [date for (date, value) in data] 
y = [value for (date, value) in data] 

fig = plt.figure() 

graph = fig.add_subplot(111) 
graph.plot_date(x,y) 

plt.show() 

問題摘要:
我的情況更像是我有一個Axes實例,準備(通過引用在上面的代碼),我想要做以下事情:

  1. 使xticks對應於確切的日期值。我聽說過matplotlib.dates.DateLocator,但我不知道如何創建一個,然後將其與特定的Axes對象相關聯。
  2. 克服的圖表類型更嚴格的控制使用(棒,線,點等)
+0

只是一個提示:因爲你的問題確實是純粹的約matplotlib並沒有具體到wxWidgets的東西,它會可能讓你改變的東西更容易你的例子使用'matplotlib.pyplot'中的函數,並將wx的東西離開它。 – 2010-08-15 04:23:26

+0

@大衛:修正。謝謝,我意識到可能有更多的人可以閱讀'matplotlib' +'pyplot'比'matplotlib' +'wx' – Kit 2010-08-15 04:45:08

回答

28

你在做什麼是很簡單的,它是最簡單的只是用情節,而不是plot_date。對於更復雜的情況,plot_date是很好的選擇,但是如果沒有它,設置你所需要的東西就很容易實現。

例如,基於你上面的例子:

import datetime as DT 
from matplotlib import pyplot as plt 
from matplotlib.dates import date2num 

data = [(DT.datetime.strptime('2010-02-05', "%Y-%m-%d"), 123), 
     (DT.datetime.strptime('2010-02-19', "%Y-%m-%d"), 678), 
     (DT.datetime.strptime('2010-03-05', "%Y-%m-%d"), 987), 
     (DT.datetime.strptime('2010-03-19', "%Y-%m-%d"), 345)] 

x = [date2num(date) for (date, value) in data] 
y = [value for (date, value) in data] 

fig = plt.figure() 

graph = fig.add_subplot(111) 

# Plot the data as a red line with round markers 
graph.plot(x,y,'r-o') 

# Set the xtick locations to correspond to just the dates you entered. 
graph.set_xticks(x) 

# Set the xtick labels to correspond to just the dates you entered. 
graph.set_xticklabels(
     [date.strftime("%Y-%m-%d") for (date, value) in data] 
     ) 

plt.show() 

如果你喜歡酒吧的情節,只是使用plt.bar()。要了解如何設置行和標記樣式,看plt.plot() Plot with date labels at marker locations http://www.geology.wisc.edu/~jkington/matplotlib_date_labels.png

+0

+1這很好。謝謝! – Kit 2010-08-17 13:23:46