【问题标题】:How can I plot multiple line in the same graph in python?如何在 python 的同一图中绘制多条线?
【发布时间】:2021-01-25 23:04:55
【问题描述】:

我想使用 matplotlib 在 python 中创建这个图形1。我创建了一个名为 generation 的列表,它使用 0 到 200 的值进行初始化。我创建了一个包含 38 个列表的列表变量。每个列表包含 200 个浮点数。我试图绘制数据,但出现错误:

ValueError: x and y must have same first dimension, but have shapes (200,) and (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)):
#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()

我想要的最终图表如下所示:

此图中1 中的每一行对应一个不同的输入值。对于每个输入,算法运行 100 代。该图显示了算法的结果如何演变超过 100 代。

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    你快到了!您只需要使用listt[i] 而不是[list1[i] for list1 in listt]

    所以,代码应该是这样的:

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

    它会返回这个图表:

    当然,它不会和你的完全一样,因为我随机生成了listt

    【讨论】:

      猜你喜欢
      • 2021-03-26
      • 1970-01-01
      • 2015-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-04
      • 1970-01-01
      相关资源
      最近更新 更多