2016-03-08 39 views
0

我有一個數組,其時間戳爲ts_array,格式爲dd-mm-yyyy,如03-08-2012。現在我想用matplotlib 1.5.1繪製直方圖和Python 2.7如下:使用Python生成直方圖

import matplotlib.pyplot as plt 

timestamps = dict((x, ts_array.count(x)) for x in ts_array) 

plt.hist(timestamps) 
plt.title("Timestamp Histogram") 
plt.xlabel("Value") 
plt.ylabel("Frequency") 
plt.show() 

例如在哪裏timestamps = {'03-08-2012': 108, '15-08-2012': 16}

當我嘗試運行它時,它會拋出TypeError: len() of unsized object。我如何繪製一個直方圖,其中x軸上的日期(鍵)和y軸上的計數(值)?

回答

1

這個問題我認爲你有,但我不確定,因爲我不知道ts_array是什麼樣子,hist試圖創建一個柱狀圖,然後在條形圖中繪製它。你想要的只是繪製一張條形圖:從你的聲明看起來,timestamps是生成該條形圖所需的數據?

所以,你可以舉例來說做到這一點:

timestamps = {'03-08-2012': 108, '15-08-2012': 16} # Sample data 

# Get the heights and labels from the dictionary 
heights, labels = [], [] 
for key, val in timestamps.iteritems(): 
    labels.append(key) 
    heights.append(val) 

# Create a set of fake indexes at which to place the bars 
indexes = np.arange(len(timestamps)) 
width = 0.4 

# Generate a matplotlib figure and plot the bar chart 
fig, ax = plt.subplots() 
ax.bar(indexes, heights) 

# Overwrite the axis labels 
ax.set_xticks(indexes + width) 
ax.set_xticklabels(labels) 

這是example in the docs的稍微修改後的版本。希望有幫助。