首页 > 解决方案 > 如何在matplotlib中循环推进y轴?

问题描述

我有一个 csv 文件,其中第一列包含 x 轴,所有其他列是我想针对 x 轴绘制的各种 y 轴。我使用“字段名”阅读了“DictReader”的列。我使用 append 方法在循环中读取的不同 y 轴值,但问题是它的值永远不会前进到下一列,但是这些列的图例是正确创建的!我在 plt.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()

标签: pythoncsvmatplotlibappend

解决方案


您的代码存在一些问题。

首先,您打开 csv 文件两次(首先是获取xs,然后是ys),这既没有必要也没有效率。然后,在第二部分中,不前进的原因是因为您正在迭代csv_reader并且一旦耗尽,就没有更多可阅读的内容了,因此您的迭代还不够。

您可以尝试将其csv_reader放在外部for循环中,但问题是由于您是逐行读取,因此您需要先读取整个文件,然后才能绘制任何内容;因此,您不能在循环内绘图,而必须使用 newfor来生成绘图。这是一个工作示例,它很丑,但它有效:

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()

哪个输出:

在此处输入图像描述

但是,正如评论中有人建议的那样,使用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"])

只需几行代码和与上面相同的输出:

在此处输入图像描述

*请注意,实际上有一个小的差异,x 轴上的标签。但仅此而已。


推荐阅读