matplotlib plot csv file of all columns

耗尽温柔 提交于 2021-02-18 08:45:28

问题


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.


回答1:


How about this:

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



回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/17084851/matplotlib-plot-csv-file-of-all-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!