3

I am trying to plot a graph after having imported data from a CSV file and stored it as two separate lists. Is it possible for matplotlib to plot a graph using a list of strings, or is it necessary for the lists two be lists of "int" ? If not, why is the following code not working?

Error prompted:

invalid literal for int() with base 10: '02_13_2014'

My code:

 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()
0

1 Answer 1

3

I think the problem here is your date. The code here is a lot simpler if you just use 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)

I'm assuming your data looks something like this...

enter image description here

then format the date

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.