Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
776 views
in Technique[技术] by (71.8m points)

matplotlib - Plotting list of lists in a same graph in Python

I am trying to plot (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.

I also tried: 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()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.

Edited: Adapt the code if y contains more lists.

Below is the plot I get for this case: Sample plot


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...