使用带有两个列表的matplotlib绘制图形

时间:2014-03-08 19:54:38

标签: python matplotlib plot

我尝试从CSV文件导入数据并将其存储为两个单独的列表后绘制图表。 matplotlib是否可以使用字符串列表绘制图形,或者列表中是否有必要使用“int”列表? 如果没有,为什么以下代码不起作用?

提示错误:

  

对于基数为10的int()的无效文字:'02_13_2014'

我的代码:

 import csv
    import numpy as np
    from numpy import genfromtxt
    import matplotlib.pyplot as plt
    import matplotlib.dates as mdates

with open('pytdef.csv','r') as f:
    reader = csv.reader(f)
    for row in reader:
        print (row)

first_column= ['Date']
second_column = ['Value']
Date_list = []
Value_list = []

with open('pytdef.csv') as f:
    reader = csv.reader(f)
    for row in reader:
        Date_list.append(row[0])

with open('pytdef.csv') as f:
    reader = csv.reader(f)
    for row in reader:
        Value_list.append(row[1])

    print (Date_list)
    print (Value_list)

Date_list = list(map(int,Date_list))
print (Date_list)
print (Value_list)


fig = plt.figure()
plt.plot_date(x=Date_list, y=Value_list)
plt.show()

1 个答案:

答案 0 :(得分:1)

我认为这里的问题是你的约会对象。如果您只使用pandas

,这里的代码要简单得多
#!/usr/bin/env python

%matplotlib inline

import pandas as pd
import matplotlib.pyplot as plt
from datetime import date

columns = ['dates', 'value']
data = pd.read_csv('/location_of_file/file_name.csv', header=False, names=columns)

我假设您的数据看起来像这样......

enter image description here

然后格式化日期

data['dates'] = [date(int(x.split('_')[2]), int(x.split('_')[0]), 
    int(x.split('_')[1])) for x in data.dates]
plt.plot(data.dates, data.value);

enter image description here