Note

Go to the endto download the full example code.

Plotting masked and NaN values#

Sometimes you need to plot data with missing values.

One possibility is to simply remove undesired data points. The line plottedthrough the remaining data will be continuous, and not indicate where themissing data is located.

If it is useful to have gaps in the line where the data is missing, then theundesired points can be indicated using amasked array or by setting theirvalues to NaN. No marker will be drawn where either x or y are masked and, ifplotting with a line, it will be broken there.

The following example illustrates the three cases:

  1. Removing points.

  2. Masking points.

  3. Setting to NaN.

importmatplotlib.pyplotaspltimportnumpyasnpx=np.linspace(-np.pi/2,np.pi/2,31)y=np.cos(x)**3# 1) remove points where y > 0.7x2=x[y<=0.7]y2=y[y<=0.7]# 2) mask points where y > 0.7y3=np.ma.masked_where(y>0.7,y)# 3) set to NaN where y > 0.7y4=y.copy()y4[y3>0.7]=np.nanplt.plot(x*0.1,y,'o-',color='lightgrey',label='No mask')plt.plot(x2*0.4,y2,'o-',label='Points removed')plt.plot(x*0.7,y3,'o-',label='Masked values')plt.plot(x*1.0,y4,'o-',label='NaN values')plt.legend()plt.title('Masked and NaN data')plt.show()
Masked and NaN data

Tags:plot-type: linelevel: intermediate

Gallery generated by Sphinx-Gallery