anthony mccool anthony mccool - 10 months ago 139
Python Question

Plotting graph from CSV

Im looking for a bit of help, Im really new to Python and dont know if it just making thngs harder for myslef or what. Im trying to plot a simple line graph from a csv file.
Ive tried a number of approaches but all return the error :
ValueError: could not convert string to float:

This is the code if seeming to get the best with

import csv`
import pylab as pl
import numpy as np
matplotlib.dates as mdates
with open('D:/growth_rate.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')

for row in readCSV:
print (row)
a= (row)
x,y = np.loadtxt('D:/growth_rate.csv', delimiter = ',', unpack=True,
converters = {0: mdates.strpdate2num('%d/%m/%Y')})

Ive also tried the csv reader approach, but similar problem

a = zip(*csv.reader(open('D:/growth_rate.csv', 'rb')))
csv.writer(open('D:/growth_rate.csv', "wb")).writerows(a)

print a

I dont know if its a problem with the csv file, it originally was a xls file, with a company headers and other nonsense, so i put it into a csv and also tried a txt file. Either that or im missing something really obvious,

Any help, greatly appreciated.


pandas approach:

import pandas as pd
import matplotlib as plt

fn = r'D:\temp\.data\growth_rate.csv'
#df = pd.read_csv(fn, parse_dates=[0], names=['date','val']).set_index('date')
df = pd.read_csv(fn, names=['date','val']).set_index('date')

# bar plot

# line plot

enter image description here

enter image description here