python - 使用 matplotlib 和两个列表绘制图形

标签 python matplotlib plot

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

错误提示:

invalid literal for int() with base 10: '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()

最佳答案

我认为问题出在你的约会上。如果只使用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

关于python - 使用 matplotlib 和两个列表绘制图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22274268/

相关文章:

python - reStructuredText:README.rst 不适用于 PyPI

python - 如何使用 pysnmp 避免高 CPU 使用率

python - Django forloop索引操作

python - 如何在seaborn lineplot上显示置信区间(误差带)

r - R中互相关的方法

matlab - 多轴断裂

python 'static core class'

python - autofmt_xdate 删除所有子图的 x 轴标签

python - 在一个图中绘制一些东西,稍后再用于另一个图中

graphics - 如何使用 GNUPlot 根据列中的值绘制单/多行