简体   繁体   English

如何在 python 的同一图中 plot 多条线?

[英]How can I plot multiple line in the same graph in python?

I want to create this graph 1 in python using matplotlib.我想使用 matplotlib 在 python 中创建此图1 I created a list called generation that is initialized with values from 0 to 200. I created a list variable consisting of 38 lists.我创建了一个名为 generation 的列表,该列表使用 0 到 200 的值进行初始化。我创建了一个包含 38 个列表的列表变量。 Each list consists of 200 float numbers.每个列表包含 200 个浮点数。 I tried to plot the data but I have the error:我试图 plot 数据,但我有错误:

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:我想要的最终图表如下所示:

图表输出

Each line in this graph 1 corresponds to a different input value.1中的每一行对应一个不同的输入值。 For each input, the algorithm runs 100 generations.对于每个输入,算法运行 100 代。 The graph shows how the results of the algorithm evolve over 100 generations.该图显示了算法的结果如何演变超过 100 代。

You're almost there!您快到了! You only need to use listt[i] instead of [list1[i] for list1 in listt] .您只需要使用listt[i]而不是[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:它返回此图: 在此处输入图像描述

Of course, it won't be exactly as yours since I randomly generated listt .当然,它不会和你的完全一样,因为我是随机生成listt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM