2016-03-08 65 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的稍微修改后的版本。希望有帮助。