【问题标题】:How to plot list of lists against list?如何根据列表绘制列表列表?
【发布时间】:2020-12-25 10:16:33
【问题描述】:
x = [2000,2001,2002,2003]
y = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
for i in range(len(y[0])):
    plt.plot(x,[pt[i] for pt in y])
plt.show()

我收到了ValueError4, 3。我知道xy 必须相等。我认为len(y[0]) 会起作用。

对于y 中的每个子列表,我想生成一行,其x 值对应于2000, 2001, 2002, 2003

【问题讨论】:

标签: python matplotlib valueerror


【解决方案1】:

另一种解决方案是通过以下方式使用pandas 包:

import pandas as pd
import matplotlib.pyplot as plt
x = [2000,2001,2002,2003]
y = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
df = pd.DataFrame(y).transpose()
df.index=x
df.plot()
plt.show()

结果是:

输出DataFrame 为:

In [30]: df
Out[30]: 
      0  1   2
2000  1  5   9
2001  2  6  10
2002  3  7  11
2003  4  8  12

【讨论】:

  • 简洁的方法。我喜欢它。
【解决方案2】:

对于简单的 Pythonic 解决方案,请执行以下操作:

for y_values in y:
    plt.plot(x, y_values)

plt.xticks(x)  # add this or the plot api will add extra ticks
plt.show()

y 嵌套列表中的每个项目都是您要针对 x 绘制的列表,因此这种方法在这里非常有效。

【讨论】:

  • 这个解决方案是完美的。但我认为在这方面使用pandas 方法很好,因此我添加了另一个解决方案。
【解决方案3】:

[pt[i] for pt in y] 上的i = 0 会给你[1,5,9]

我认为你需要[1,2,3,4],所以使用y[i] 而不是[pt[i] for pt in y]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-30
    • 1970-01-01
    • 2015-10-01
    • 1970-01-01
    • 2021-07-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多