开发者

Reading values from csv and drawing bar chart with matplotlib in python

I'm trying to read in a delimited csv called 'StabilityResults.csv' and create a bar plot of column 7 with x-labels from column 0. Getting the labels from column 0 is not a problem but reading the values from col7 into a list doesn't seem to work as a valid input in matplotlib. Is there a way to convert my list of values so they are readable in matplotlib??

import matplotlib.pyplot as plt
import csv
import numpy as np

res = csv.reader(open('StabilityResults.csv'), delimiter=',')
res.next() # do not read header

mut = []
tot = [] 
a = 0
width = 0.2

for col in res:
    mut.append(col[0])
    tot.append(col[7])
    a += 1

ind = a开发者_高级运维range(a)

p1 = plt.bar(ind,tot,width,color='r')
labs = plt.xticks(ind+width,mut)

plt.show()

I also reading column7 using numpy's genfromtxt function but this gave an array which also didnt work.

tot2 = np.genfromtxt('StabilityResults.csv', delimiter=',', dtype=None, names=True, deletechars=',', usecols=[7])


You should convert the data to integer type (or float)

tot.append(int(col[7]))


Ahh, should've spent more time. Similar to Manuel's answer, I just added a temporary holder to convert to a float in the for loop:

for col in res:
    tmp_tot = float(col[7])
    tot.append(tmp_tot)

Both ways work!

Cheers


mut.append(col[0])
tot.append(col[7])

You append the content of col list, which is text. You will have to convert it to int or float:

mut.append(float(col[0]))
tot.append(float(col[7]))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜