Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

matplotlib - How can I plot multiple line in the same graph in python?

I want to create this graph 1 in python using matplotlib. I created a list called generation that is initialized with values from 0 to 200. I created a list variable consisting of 38 lists. Each list consists of 200 float numbers. I tried to plot the data but I have the error:

ValueError: x and y must have same first dimension, but have shapes (200,) and (38,)

My code:

generation = []
for i in range(200):
    generation.append(i)
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("A test graph")
for i in range(len(listt)):
#generation is a list  with 200 values
#listt is a list with 38 lists
#list1 is a list with 200 values
    plt.plot(generation ,[list1[i] for list1 in listt],label = 'id %s'%i)
plt.legend()
plt.show()

The final graph I want to look like the one below:

Graph output

Each line in this graph 1 corresponds to a different input value. For each input, the algorithm runs 100 generations. The graph shows how the results of the algorithm evolve over 100 generations.

question from:https://stackoverflow.com/questions/65886371/how-can-i-plot-multiple-line-in-the-same-graph-in-python

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

1 Answer

0 votes
by (71.8m points)

You're almost there! You only need to use listt[i] instead of [list1[i] for list1 in listt].

So, the code should look like this:

import matplotlib.pyplot as plt

#random listt
listt = [[i for j in range(200)] for i in range(38)]

generation = []
for i in range(200):
    generation.append(i)

plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("A test graph")
for i in range(len(listt)):
    plt.plot(generation ,listt[i],label = 'id %s'%i)  #<--- change here
plt.legend()
plt.show()

And it returns this graph: enter image description here

Of course, it won't be exactly as yours since I randomly generated listt.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...