Python: Reading CSV file and plotting a scatter


Question

I've written a script to compute large csv files in dimensions: 27000 rows x 22 column. How can I read in the CSV file in order to use it in matplotlib in a scattered plot like the one in this thread?

axis range in scatter graphs

The concept of generating a scatter plot is understood. Attempts have been made to parse csv file by e.g.:

data=csv.reader(open('some_file.csv, 'rb'), delimiter='|', quotechar='"')

but without success.

1
3
5/23/2017 11:53:06 AM

Accepted Answer

Here is a quick solution

def getColumn(filename, column):
    results = csv.reader(open(filename), delimiter="\t")
    return [result[column] for result in results]

and then you can use it like this

time = getColumn("filename",0)
volt = getColumn("filaname",1)

plt.figure("Time/Volt")
plt.xlabel("Time(ms)")
plt.ylabel("Volt(mV)")
plt.plot(time,volt)
9
2/27/2012 10:39:30 PM

As a general alternative, you might be interested in the pandas python package by Wes McKinney: http://pandas.pydata.org/

It has literally changed my life for data analysis with python. It provides python with a data structure that is like R's data.frame, but even more powerful. And it's build on top of numpy.

And it will read csv files very easily, loading the data into a DataFrame (numpy array subclass) that can be easily sliced and manipulated.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon