python - 如何在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()
解决方案
您的代码存在一些问题。
首先,您打开 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 轴上的标签。但仅此而已。
推荐阅读
- r - 在R中的目录中读取多个Excel文件(带有多个工作表)
- c++ - 运算符'<'和具有get函数的多个值,不返回
- spring - Spring服务自动调用Oauth2保护的服务
- c++ - 我可以使用命名空间中的一些但不是全部名称,而不必为所有名称重复完整范围吗?
- json - Jolttransformjson 无法从多记录 json 文件中工作
- python - 如何在烧瓶表中制作具有相同文本的按钮?
- python - 为我的 shell 中的每个项目获取多个图像 url,但只为我的 csv 中的每个项目导入一个 url
- javascript - Upload a CSV file using AJAX in Django
- planning - PDDL2.1:“总体”的目的
- python - Plotly Sankey:如何避免将所有节点自动放置到右侧?