Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib not continuing lines after NaN's [duplicate]

I have an array slice:

array([1.0, 2.0, 3.0, None, 4.0, None, 5.0, None, 6.0, None], dtype=object)

which when plotted looks like THIS

How do I get the dotted/connecting lines to continue after the None values? I tried changing the data type from objects to floats using astype and the None's are replaced with nan's but it made no difference, I also tried a masked array using np.where(np.isnan()) etc. but it didn't make a difference. My plotting command is very simply:

plt.plot(x, array, 'ro--')

where x is a numpy array.

like image 599
user1654183 Avatar asked Aug 25 '13 16:08

user1654183


1 Answers

This is the correct behavior, mpl tries to connect adjacent points. If you have points with a nan on either side, there is no valid way to connect them to anything.

If you want to just ignore your nans when plotting, then strip them out

ind = ~np.isnan(np.asarray(data.astype(float)))
plt.plot(np.asarray(x)[ind], np.asarray(data)[ind], 'ro--')

All the asarray are just to be sure the example will work, same with the astype

also, it is really bad practice to use variable names that shadow (both in terms of python resolution and in terms of semantic) classes (like array) or common functions.

like image 173
tacaswell Avatar answered Sep 28 '22 05:09

tacaswell