【问题标题】:plot a nested list as multiple trendlines in python在python中将嵌套列表绘制为多条趋势线
【发布时间】:2017-02-03 01:00:57
【问题描述】:

我有一个嵌套列表:

nested=[[35,36,37],[34,35,36,37,38],[22,23,23,24]]

我需要创建一个图表,其中每个子列表都是同一图中的趋势线。例如,在 (x,y) 格式中:趋势线 1 有点 (1,35),(2,36),(3, 37)。趋势线 2 有点 (1,34),(2,35)...(5,38) 和第三条趋势线相同,我不知道该怎么做。我是python初学者,非常感谢您的建议!

我尝试过的编辑:

import matplotlib.pyplot as plt
for list in nested:
      x=range(1, len(list)+1)
      y=list
      plt.plot(x,y)
      plt.show()

这可行,但提供了许多情节。我需要把它全部放在一个情节中

【问题讨论】:

  • 你试过[plt.plot(x) for x in nested]; plt.show()吗?
  • 如果你想让x轴的值从1开始,那么你可以试试[plt.plot(*m) for m in [list(zip(*[(ix+1,y) for ix,y in enumerate(x)])) for x in nested]]; plt.show()

标签: python matplotlib plot graphing trendline


【解决方案1】:

您可以尝试通过遍历每个子列表并使用enumerate 来添加 x 值,如下所示:

import matplotlib.pyplot as plt

nested = [[35,36,37],[34,35,36,37,38],[22,23,23,24]]
fully_nested = [list(zip(*[(ix+1,y) for ix,y in enumerate(x)])) for x in nested]
names = ['sublist%d'%(i+1) for i in range(len(fully_nested))]

for l in fully_nested:
    plt.plot(*l)
plt.xlim(0,5)
plt.xlabel("Indices")
plt.ylim(0,40)
plt.xlabel("Values")
plt.legend(names, fontsize=7, loc = 'upper left')
plt.show()

这会产生:

我希望这证明有用。

【讨论】:

    【解决方案2】:

    你需要在循环外调用plt.show(),否则每次迭代都会显示一个图。

    import matplotlib.pyplot as plt
    nested=[[35,36,37],[34,35,36,37,38],[22,23,23,24]]
    for y in nested:
          x=range(1, len(y)+1)
          plt.plot(x,y)
    plt.show()
    

    (另外,不要在python中使用list作为变量名,因为它是一种数据类型。虽然在这里这不会造成伤害,但在其他情况下可能会产生完全的混乱。)

    【讨论】:

      猜你喜欢
      • 2021-08-28
      • 1970-01-01
      • 2021-08-10
      • 1970-01-01
      • 2020-11-28
      • 1970-01-01
      • 2021-10-03
      • 1970-01-01
      • 2021-02-18
      相关资源
      最近更新 更多