1

Very new at Python and first time using matplotlib

I'm trying to graph a multiline plot based on the rows of a CSV file.

CSV file looks something like this:

Row1        S1      S2     S3      HWS
Row2        2.45    3.76   2.44    1
Row3        3.59    2.56   9.68    2
Row4        2.54    9.45   6.78    3

I want to graph the HWS values by each row in the csv file.

Ex: For Row2, I want my points to be (1, 2.45), (2, 3.76), and (3, 2.44). For Row3, I want my points to be (1, 3.59), (2, 2.56), and (3, 9.68).

I've already looked at modules like pandas from other stack overflow answers, but I can't find commands to graph by rows. All I found is ways to graph a whole CSV file or ways to isolate columns of a csv file.

Is there a way to graph this way using Python and matplotlib?

2 Answers 2

2

Read in each column in the csv into separate lists.

plotting the data is trivial. Here's a basic example in your code the data sets come from the csv.

import matplotlib.pyplot as plt

s1 = [2,3,2]
s2 = [3,2,9]
s3 = [2,9,6]
hws = [1,2,3]

plt.plot(hws,s1)
plt.plot(hws,s2)
plt.plot(hws,s3)
Sign up to request clarification or add additional context in comments.

2 Comments

I have a huge dataset - is there a way for me to read the specific columns s1, s2, s3... I can't manually type them. Thanks!
yes there most certainly is. At this point in the discussion, referencing the teach a man to fish etc, you'll find it beneficial to try googling "how to read a csv with python". In fact this question could have found a solution using this method as well. Best of luck to you.
1

Try this if you have a huge dataset.!

import csv
import matplotlib.pyplot as plt
import os

os.chdir(r"C:\--")  #path of your csv file

S1=[]
S2=[]
S3=[]
HWS=[]
with open('dataSet.csv','r') as csvFile:
    reader=csv.reader(csvFile,delimiter=';')
    next(reader)
    for row in reader:
        temp=row[0]
        S1.append(temp)
        temp=row[1]
        S2.append(temp)
        temp=row[2]
        S3.append(temp)
        temp=row[3]
        HWS.append(temp)
plt.plot(HWS,S1)
plt.plot(HWS,S2)
plt.plot(HWS,S3)
plt.show()

8 Comments

This solution looks great - but I get an error when I try to run it: IndexError: list index out of range i know it probably doesn't have to do with the code, but if you know, could you shed some light as to why this error is happening?
which version of python you are using.? try changing delimiter to ',', try 'rb' at the place of 'r' in 9th line and keep r before the path of your file in line 4
I'm using python 2.7.10
i am using 3, anyways try 'rb' at the place of 'r'.
still no luck...the error only appears when I add the code past "temp=row[0] S1.append(temp)"
|

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.