在Python中绘制同一图表中的列表列表

问题描述 投票:5回答:2

我试图绘制(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

我也尝试过: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()
python matplotlib nested-lists
2个回答
7
投票

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

假设:xy中的任何元素具有相同的长度。这个想法是逐个元素地阅读,以便构建列表(x,y[0]'s)(x,y[1]'s)(x,y[n]'s

编辑:如果y包含更多列表,请调整代码。

下面是我为这个案例得到的情节:Sample plot


1
投票

使用for循环生成绘图并在for循环后使用.show()方法。

 import matplotlib.pyplot as plt
 for impacts in impactData:
     timefilteredForce = plt.plot(impacts)
     timefilteredForce = plt.xlabel('points')
     timefilteredForce = plt.ylabel('Force')

 plt.show()

impactData是一个列表列表。

Here's the plot this code generated.

© www.soinside.com 2019 - 2024. All rights reserved.