Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting lists with different number of elements in matplotlib

I have a list of numpy arrays, each potentially having a different number of elements, such as:

[array([55]),
 array([54]),
 array([], dtype=float64),
 array([48, 55]),]

I would like to plot this, where each array has an abscissa (x value) assigned, such as [1,2,3,4] so that the plot should show the following points: [[1,55], [2, 54], [4, 48], [4, 55]]. Is there a way I can do that with matplotlib? or how can I transform the data with numpy or pandas first so that it is can be plotted?

like image 864
Ramon Crehuet Avatar asked Jun 10 '26 07:06

Ramon Crehuet


1 Answers

What you want to do is chain the original array and generate a new array with "abscissas". There are many way to concatenated, one of the most efficient is using itertools.chain.

import itertools
from numpy import array

x = [array([55]), array([54]), array([]), array([48, 55])]

ys = list(itertools.chain(*x))
# this will be [55, 54, 48, 55]

# generate abscissas
xs = list(itertools.chain(*[[i+1]*len(x1) for i, x1 in enumerate(x)])) 

Now you can just plot easily with matplotlib as below

import matplotlib.pyplot as plt
plt.plot(xs, ys)
like image 179
Alessandro Mariani Avatar answered Jun 12 '26 11:06

Alessandro Mariani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!