3

I have a csv file which contains 20 columns. Right now I can plot using this code taking first column as x axis and rest of them as y axis.

import numpy as np
import matplotlib.pyplot as plt
data = np.genfromtxt('cs.csv',delimiter=',', dtype = float)

a = [row[0] for row in data]
b = [row[1] for row in data]
c = [row[2] for row in data]

fig = plt.figure()
ax = fig.add_subplot(111, axisbg = 'w')
ax.plot(a,b,'g',lw=1.3)
ax.plot(a,c,'r',lw=1.3)
plt.show()

The problem is here I have to define all the columns by using

a = [row[0] for row in data]

this code for all columns one by one. What I want actually to have some method so that it can plot all 19 columns taking first column as x axis constant and plot them in a single window. Any help please.

3 Answers 3

4

You could try using pandas, which uses matplotlib for plotting. For example, if you have a CSV like this:

a,b,c
20,2,5
40,6,8
60,4,9

You can plot columns b & c like this:

import pandas as pd

df = pd.DataFrame.from_csv('test.csv', parse_dates=False)
df.b.plot(color='g',lw=1.3)
df.c.plot(color='r',lw=1.3)

The first column, is used as the index & x-axis by default. See the plotting documentation for more details.

Sign up to request clarification or add additional context in comments.

2 Comments

i am having a problem with panda. AttributeError: 'module' object has no attribute 'DataFrame'. is it due to the installation or different version. any idea please.
DataFrame has always been part of pandas as far as I am aware. Did you install it with pip?
1

How about this:

[plt.plot(data[0],data[x]) for x in range(1,len(data[:,0]))]

2 Comments

hi, could you pls tell what is a stands for in range(1,len(a[:,0]))]
Hi, typo on my part. It should have been data. Now updated.
0

As Matti John said, Pandas is the way forward and you can do what you asked even easier. Assuming your CSV is a similar form to the one he posted, you can plot all columns (except the first) against the first column like this:

import pandas as pd
df = pd.read_csv('name_of_file.csv', index_col=0)
df.plot(x=df.index, y=df.columns)

Using the CSV that Matti John gave, Namely

a,b,c
20,2,5
40,6,8
60,4,9

This is the output from the code above

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.