0

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)
np.shape(a)
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.

4
  • can you post part of your CSV file or better a link to it or to excel file so we could download it and try to develop a working solution? Commented Apr 16, 2016 at 23:29
  • uploaded it to onedrive, let me know if the link works. Cheers onedrive.live.com/… Commented Apr 16, 2016 at 23:36
  • there are no values in first two rows - is it OK? and how do you want to plot it as a line or as bars? Is it OK for you to use pandas module? - it's going to be much easier Commented Apr 16, 2016 at 23:38
  • yehm theres no data for the first two dates, yeh if it pandas works then thats great Commented Apr 16, 2016 at 23:46

2 Answers 2

2

You can also do this in numpy / matplotlib without needing pandas. Note that np.genfromtxt can cope with blank lines fine (as opposed to np.loadtxt which will break. By default those values get filled with NaNs but you can change this with the filling_values option.

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

date_decode_function = lambda b: mdates.strpdate2num('%d/%m/%Y')(b.decode())

dates, growth_rates = np.genfromtxt('growth_rate.csv',
                                    delimiter = ',',
                                    unpack=True,
                                    converters = {0: date_decode_function})


fig, ax = plt.subplots()
ax.plot_date(dates, growth_rates,'-',lw=2)
plt.xlabel("Date", fontsize=16)
plt.ylabel("Growth rate", fontsize=16)

plt.grid()
plt.show()
Sign up to request clarification or add additional context in comments.

3 Comments

Thats working. Brilliant. Is there any way i can have multiple graphs on the one output? Separate graphs but as if it was for the one print out. The csv file i uploaded is a smaller section of a bigger file
@anthonymccool You need to use the plt.subplot method. The exact invocation will depend on what you're trying to accomplish but the examples here should help.
yeh something similar to that output, ill have a wee tinker and see what i come up with. Thanks everyone, really helped me out there
0

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
df.plot(kind='bar')

# line plot
#df.plot()

plt.show()

enter image description here

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.