使用matplotlib问题将CSV转换为PNG

时间:2016-07-13 14:15:15

标签: python csv matplotlib

我正在尝试使用一些CSV数据创建PNG图像,但我收到与日期列相关的错误(同时转换为列表)。错误是:

Traceback (most recent call last):
File "C:/Users/user1/Desktop/Py/AgentsStatus/testGraph.py", line 57, in <module>
    plt.plot(dateCol,okCol,linewidth=5)
File "C:\Python34\lib\site-packages\matplotlib\pyplot.py", line 3154, in plot
    ret = ax.plot(*args, **kwargs)
File "C:\Python34\lib\site-packages\matplotlib\__init__.py", line 1812, in inner
    return func(ax, *args, **kwargs)
File "C:\Python34\lib\site-packages\matplotlib\axes\_axes.py", line 1425, in plot
    self.add_line(line)
File "C:\Python34\lib\site-packages\matplotlib\axes\_base.py", line 1708, in add_line
    self._update_line_limits(line)
File "C:\Python34\lib\site-packages\matplotlib\axes\_base.py", line 1730, in _update_line_limits
    path = line.get_path()
File "C:\Python34\lib\site-packages\matplotlib\lines.py", line 925, in get_path
    self.recache()
File "C:\Python34\lib\site-packages\matplotlib\lines.py", line 612, in recache
    x = np.asarray(xconv, np.float_)
File "C:\Python34\lib\site-packages\numpy\core\numeric.py", line 482, in asarray
    return array(a, dtype, copy=False, order=order)
ValueError: could not convert string to float: '11-04-2016'

CSV包含:

11-04-2016;37180;6;23852
18-04-2016;37341;9;24105
25-04-2016;37075;18;23788

我的代码是:

import csv
import matplotlib.pyplot as plt
import os

path = 'C:\\Users\\user1\\Desktop\\Py\\AgentsStatus\\data.csv'

with open (path) as csvfile:
    readCSV = csv.reader(csvfile, delimiter=';')

    dateCol = [] # date list

    for row in readCSV:
        if row:
            date0 = row[0]
            dateCol.append(date0)

with open (path) as csvfile:
    readCSV = csv.reader(csvfile, delimiter=';')

    okCol = [] # all agents list

    for row in readCSV:
        if row:
            ok0 = row[1]
            okCol.append(ok0)


with open (path) as csvfile:
    readCSV = csv.reader(csvfile, delimiter=';')

    heaCol = [] # healthy list




from matplotlib import pyplot as plt
from matplotlib import style

style.use('ggplot')


# can plot specifically, after just showing the defaults:
plt.plot(dateCol,okCol,linewidth=5)
plt.plot(dateCol,heaCol,linewidth=5)

plt.title('Epic Info')
plt.ylabel('Y axis')
plt.xlabel('X axis')

plt.show()

我的目标是创建如下内容:

enter image description here

你能不能给我一些关于我做错什么的提示?我认为我的问题是我没有将List dateCol设置为图表的索引(不绘制它)。你能帮帮我吗?

非常感谢。

1 个答案:

答案 0 :(得分:1)

对于像这样的东西,熊猫是无与伦比的:

import pandas
import matplotlib.pyplot as plt

df = pandas.read_csv('sampledata.csv', delimiter=';', 
                     index_col=0, 
                     parse_dates=[0], dayfirst=True, 
                     names=['date','a','b','c'])
df.plot()

plt.savefig('sampledata.png')

结果

enter image description here