Python matplotlib 绘制所有列的 csv 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17084851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:23:38  来源:igfitidea点击:

matplotlib plot csv file of all columns

pythonnumpymatplotlib

提问by user2095624

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.

我有一个包含 20 列的 csv 文件。现在我可以使用此代码进行绘图,将第一列作为 x 轴,其余作为 y 轴。

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]

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.

此代码一一显示所有列。我实际上想要有一些方法,以便它可以绘制所有 19 列,将第一列作为 x 轴常量并将它们绘制在单个窗口中。请任何帮助。

采纳答案by atomh33ls

How about this:

这个怎么样:

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

回答by Matti John

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

您可以尝试使用pandas,它使用 matplotlib 进行绘图。例如,如果您有这样的 CSV:

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

You can plot columns b& clike this:

您可以绘制列b&c像这样:

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 documentationfor more details.

第一列默认用作索引和 x 轴。有关更多详细信息,请参阅绘图文档

回答by Jonny Brooks

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:

正如 Matti John 所说,Pandas 是前进的方向,您可以更轻松地完成您的要求。假设您的 CSV 格式与他发布的格式相似,您可以针对第一列绘制所有列(第一列除外),如下所示:

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

使用 Matti John 提供的 CSV,即

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

This is the output from the code above

这是上面代码的输出