简体   繁体   中英

Plotting two different sized arrays with matplotlib

I want to use matplotlib to plot my data. 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:

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

and my y data, of 3 values, is:

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. So for x=1, the different y values are 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.

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.

# use
fig, ax = plotting(y)

Use zip function to transpose your y -list, extracting arrays of size equivalent to x . For example,

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

Then plot each of y1,y2, and y3.

You can just do a for loop:

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:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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