.. only:: html .. note:: :class: sphx-glr-download-link-note Click :ref:`here ` to download the full example code .. rst-class:: sphx-glr-example-title .. _sphx_glr_gallery_lines_bars_and_markers_masked_demo.py: ============================== 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 plotted through the remaining data will be continuous, and not indicate where the missing data is located. If it is useful to have gaps in the line where the data is missing, then the undesired points can be indicated using a `masked array`_ or by setting their values to NaN. No marker will be drawn where either x or y are masked and, if plotting with a line, it will be broken there. .. _masked array: https://docs.scipy.org/doc/numpy/reference/maskedarray.generic.html The following example illustrates the three cases: 1) Removing points. 2) Masking points. 3) Setting to NaN. .. image:: /gallery/lines_bars_and_markers/images/sphx_glr_masked_demo_001.png :alt: Masked and NaN data :class: sphx-glr-single-img .. code-block:: default import matplotlib.pyplot as plt import numpy as np x = np.linspace(-np.pi/2, np.pi/2, 31) y = np.cos(x)**3 # 1) remove points where y > 0.7 x2 = x[y <= 0.7] y2 = y[y <= 0.7] # 2) mask points where y > 0.7 y3 = np.ma.masked_where(y > 0.7, y) # 3) set to NaN where y > 0.7 y4 = y.copy() y4[y3 > 0.7] = np.nan plt.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() .. _sphx_glr_download_gallery_lines_bars_and_markers_masked_demo.py: .. only :: html .. container:: sphx-glr-footer :class: sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: masked_demo.py ` .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: masked_demo.ipynb ` .. only:: html .. rst-class:: sphx-glr-signature Keywords: matplotlib code example, codex, python plot, pyplot `Gallery generated by Sphinx-Gallery `_