在 Python 中的同一图中绘制列表列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40073322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Plotting list of lists in a same graph in Python
提问by sivasudhan
I am trying to plot (x,y)
where as y = [[1,2,3],[4,5,6],[7,8,9]]
.
我试图绘制(x,y)
where as y = [[1,2,3],[4,5,6],[7,8,9]]
。
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
.
说,len(x) = len(y[1]) = len(y[2])
.. y 的长度由用户输入决定。我想在同一个图中绘制 y 的多个图,即(x, y[1],y[2],y[3],...)
. 当我尝试使用循环时,它说dimension error
。
I also tried: plt.plot(x,y[i] for i in range(1,len(y)))
我也试过: plt.plot(x,y[i] for i in range(1,len(y)))
How do I plot ? Please help.
我如何绘制?请帮忙。
for i in range(1,len(y)):
plt.plot(x,y[i],label = 'id %s'%i)
plt.legend()
plt.show()
回答by Sreejith Menon
Assuming some sample values for x, below is the code that could give you the desired output.
假设 x 的一些示例值,下面是可以为您提供所需输出的代码。
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()
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
.
假设:x
和任何元素y
的长度相同。这个想法是逐个读取元素以构造列表(x,y[0]'s)
,(x,y[1]'s)
和(x,y[n]'s
。
Edited: Adapt the code if y
contains more lists.
编辑:如果y
包含更多列表,则调整代码。
回答by Nathan Pyle
Use a for loop to generate the plots and use the .show()
method after the for loop.
使用 for 循环生成图并.show()
在 for 循环之后使用该方法。
import matplotlib.pyplot as plt
for impacts in impactData:
timefilteredForce = plt.plot(impacts)
timefilteredForce = plt.xlabel('points')
timefilteredForce = plt.ylabel('Force')
plt.show()
impactData is a list of lists.
ImpactData 是一个列表列表。