[英]How to advance the y-axis in a loop in matplotlib?
我有一个 csv 文件,其中第一列包含 x 轴,所有其他列是我想要 plot 对 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()
您的代码存在一些问题。
首先,您打开 csv 文件两次(首先获取xs
,然后获取ys
),这既没有必要也没有效率。 然后,在第二部分中,没有推进的原因是因为您正在迭代csv_reader
并且一旦耗尽,就没有更多可读取的内容,因此您的迭代还不够。
您可以尝试将csv_reader
放在外部for
循环中,但问题是由于您正在逐行读取,因此您需要先读取整个文件,然后才能使用 plot 任何内容; 因此,您不能在循环内使用 plot 并且必须使用新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()
哪个输出:
但是,正如评论中有人建议的那样,使用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"])
只需几行代码和与上面相同的 output :
*注意实际上有一个小的区别,X轴上的label。 但仅此而已。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.