简体   繁体   English

使用 matplotlib 绘制两个不同大小的数组

[英]Plotting two different sized arrays with matplotlib

I want to use matplotlib to plot my data.我想使用 matplotlib 来绘制我的数据。 I want to have 4 different y values plotted on the same graph so I can compare the 4. Currently, my 'x' data is an array of size 10:我想在同一张图上绘制 4 个不同的 y 值,以便我可以比较这 4 个。目前,我的“x”数据是一个大小为 10 的数组:

x: [1,2,3,4,5,6,7,8]

and my y data, of 3 values, is:我的 y 数据有 3 个值,是:

y: [[0.6, 0.3, 0.4], [0.2, 0.5, 0.4], [0.6, 0.3, 0.4], .... etc.]

each nested array corresponds to that x value.每个嵌套数组对应于该 x 值。 So for x=1, the different y values are 0.6, 0.3, 0.4.因此,对于 x=1,不同的 y 值为 0.6、0.3、0.4。

How can I plot these all together on one graph?我怎样才能把这些都画在一张图上?

Thanks.谢谢。

You can convert your list of lists (y) to a more adequate format before plotting, and use a for loop to plot in the same graph.您可以在绘图前将列表 (y) 列表转换为更合适的格式,并使用 for 循环在同一图形中绘图。

Try this example (is basic):试试这个例子(是基本的):

def plotting(y):
    new_y = [ [sublist[i] for sublist in y] for i in range(len(y[0])) ]

    fig, axes = plt.subplots(1,1)
    for sublist in new_y:
        x = np.arange(0, len(sublist))
        axes.plot(x, sublist)

    return fig, axes

Note that the 1st line into the method creates a new y list.请注意,该方法的第一行创建了一个新的 y 列表。

# use
fig, ax = plotting(y)

Use zip function to transpose your y -list, extracting arrays of size equivalent to x .使用zip函数转置y ,提取大小等于x数组。 For example,例如,

y1,y2,y3=list(zip(*y))

Then plot each of y1,y2, and y3.然后分别绘制 y1、y2 和 y3。

You can just do a for loop:你可以只做一个 for 循环:

for col in np.array(y).T:
    plt.plot(x, col)

Run on sample data:在示例数据上运行:

x = [1,2,3,4,5,6,7,8]
y = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11],
     [12, 13, 14], [15, 16, 17], [18, 19, 20], [21, 22, 23]
    ]

Output:输出:

在此处输入图片说明

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

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