在Python中绘制同一图中的列表列表 [英] Plotting list of lists in a same graph in Python
问题描述
我试图将(x,y)
绘制为y = [[1,2,3],[4,5,6],[7,8,9]]
.
说,len(x) = len(y[1]) = len(y[2])
..
y的长度由用户输入决定.我想在同一张图中绘制y的多个图,即(x, y[1],y[2],y[3],...)
.当我尝试使用循环时,它说dimension error
.
Say, len(x) = len(y[1]) = len(y[2])
..
The length of the y is decided by the User input. I want to plot multiple plots of y in the same graph i.e, (x, y[1],y[2],y[3],...)
. When I tried using loop it says dimension error
.
我也尝试过:plt.plot(x,y[i] for i in range(1,len(y)))
如何绘制?请帮忙.
for i in range(1,len(y)):
plt.plot(x,y[i],label = 'id %s'%i)
plt.legend()
plt.show()
推荐答案
假定x的一些示例值,下面的代码可以为您提供所需的输出.
Assuming some sample values for x, below is the code that could give you the desired output.
import matplotlib.pyplot as plt
x = [1,2,3]
y = [[1,2,3],[4,5,6],[7,8,9]]
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("A test graph")
for i in range(len(y[0])):
plt.plot(x,[pt[i] for pt in y],label = 'id %s'%i)
plt.legend()
plt.show()
假设:x
和y
中的任何元素都具有相同的长度.
想法是逐个元素地读取,以便构造列表(x,y[0]'s)
,(x,y[1]'s)
和(x,y[n]'s
.
Assumptions: x
and any element in y
are of the same length.
The idea is reading element by element so as to construct the list (x,y[0]'s)
, (x,y[1]'s)
and (x,y[n]'s
.
已如果y
包含更多列表,请修改代码.
Edited: Adapt the code if y
contains more lists.
以下是我在这种情况下得到的情节:
Below is the plot I get for this case:
这篇关于在Python中绘制同一图中的列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!