Python使用matplotlib绘制日期

时间:2012-04-17 21:33:29

标签: python csv matplotlib wxpython

我是Python和matplotlib的初学者,但我正在努力学习!我想使用matplotlib从包含频率日期的CSV中绘制一些简单数据。 X轴包含日期,Y包含频率。来自CSV的示例数据:

2011/12/15,5
2011/12/11,4
2011/12/19,2

我检查了“matplotlib.sf.net/examples”,但显示所有测试数据都是从http get下载的。如果有人可以通过一些示例代码来指导我(大概使用CSV阅读器)并在图表中显示数据,我将非常感激。

谢谢!

2 个答案:

答案 0 :(得分:2)

也许你会找到类似的东西:

import csv
import datetime as dt
import matplotlib.pyplot as plt

arch = 'C:\\Python26\\programas\\test.csv'
data = csv.reader(open(arch))

data = [(dt.datetime.strptime(item, "%Y/%m/%d"), float(value)) for item, value in data]
data.sort()
[x, y] = zip(*data)

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y)

ax.grid(True)
fig.autofmt_xdate()

plt.show()

enter image description here

答案 1 :(得分:1)

我试图让我的代码尽可能简单,这绝不是优雅的,但是你走了:

import csv
import matplotlib.pyplot as plt

### Making test CSV file ###
data = [['2011/12/15,5'],['2011/12/11,4'],['2011/12/19,2'],['2011/12/16,3'],['2011/12/20,8'],['2011/12/14,4'],['2011/12/10,10'],['2011/12/9,7']]
with open('test.csv', 'wb') as f:
    writer = csv.writer(f)
    for i in data:
        writer.writerow(i)


### Extract data from CSV ###
with open('test.csv', 'rb') as n:
    reader = csv.reader(n)
    dates = []
    freq = []
    for row in reader:
        values = row[0].split(',')
        dates.append(values[0])
        freq.append(values[1])          


### Do plot ###
false_x = [x for x in range(len(dates))]
plt.plot(false_x,freq, 'o-')
plt.xticks(range(len(dates)), (dates), rotation=45)
# plt.axis([xmin, xmax, ymin, ymax]) - sets axes limits on graph
plt.axis([-1, 8, 0, 11])
plt.show()

这样做:

enter image description here