如何在matplotlib中循环推进y轴?

问题描述 投票:0回答:1

我有一个csv文件,其中第一列包含x轴,其他所有列是各种y轴,我想对x轴进行绘制.我通过 "DictReader "使用 "fieldnames "来读取这些列.不同的y轴值我使用append方法在循环中读取,但问题是它的值从来没有前进到下一列,然而这些列的图例是正确创建的! 我尝试在plt.plot.plot之后使用y_axe.clear(),但没有任何帮助。我没有找到任何使用append的例子,我怀疑append是这里的问题,但我不知道如何解决。所有的帮助将被高度感激。

import csv
from matplotlib import pyplot as plt


x_axe = []
y_axe = []
with open("file.csv", "r") as csv_file:
    csv_reader = csv.DictReader(csv_file)
    for lines in csv_reader:
        x_axe.append(float(lines[csv_reader.fieldnames[0]]))

with open("file.csv", "r") as csv_file:
    csv_reader = csv.DictReader(csv_file)
    for i in range(1, len(csv_reader.fieldnames)):
        for lines in csv_reader:
            y_axe.append(float(lines[csv_reader.fieldnames[i]]))
        plt.plot(x_axe, y_axe, label=csv_reader.fieldnames[i])
        # y_axe.clear()   this did not help
plt.legend()

plt.show()
python csv matplotlib append
1个回答
0
投票

你的代码有几个问题。

首先,你打开了两次csv文件(第一次是为了获取 "字段名")。xs那么 ys),这是没必要也没效率的。那么,在第二部分中,没有前进的原因是由于你在迭代了 csv_reader 而一旦耗尽,就没有东西可读了,所以你的迭代是不够的。

你可以尝试把 csv_reader 在外 for 循环,但问题是,由于你是逐行读取,你需要先读取整个文件,然后才能绘制任何东西;因此,你不能在循环内绘制,必须使用一个新的 for 来生成图谱。这是一个工作实例,虽然很丑,但很好用。

import csv
from matplotlib import pyplot as plt
import io

dummy_csv_file = '''Y,X1,X2,X3
1,5,10,15
2,6,11,16
3,7,12,17
4,8,13,18
5,9,14,19'''

x_axe = []
y_axe = []
with io.StringIO(dummy_csv_file) as csv_file:
    csv_reader = csv.DictReader(csv_file)
    for lines in csv_reader:
        x_axe.append(float(lines[csv_reader.fieldnames[0]]))


y_axe = []
with io.StringIO(dummy_csv_file) as csv_file:
    csv_reader = csv.DictReader(csv_file)


    for lines in csv_reader:

        for i in range(1, len(csv_reader.fieldnames)):
            y_axe.append(float(lines[csv_reader.fieldnames[i]]))

    # y_axe here contains all the points but are not ordered, a list comprehension will split them into the needed values of each column so we can plot each one
    for y in [y_axe[x::len(csv_reader.fieldnames)-1] for x in range(len(csv_reader.fieldnames)-1)]:
        plt.plot(x_axe, y, label=csv_reader.fieldnames[i])
        # y_axe.clear()   this did not help
plt.legend()

plt.show()

它的输出是:

enter image description here

但是,正如有人在评论中建议的那样,用... ... pandas 而省去了所有的麻烦。

import pandas as pd 
import io

dummy_csv_file = '''Y,X1,X2,X3
1,5,10,15
2,6,11,16
3,7,12,17
4,8,13,18
5,9,14,19'''

df = pd.read_csv(io.StringIO(dummy_csv_file))
df.plot(x="Y", y=["X1", "X2", "X3"])

只需几行代码就能得到和上面一样的结果。

enter image description here

*请注意,其实有一个小的区别,X轴的标签。但也就这样了。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.