|
1 |
| -''' |
2 |
| -=========== |
3 |
| -Masked Demo |
4 |
| -=========== |
| 1 | +""" |
| 2 | +============================== |
| 3 | +Plotting masked and NaN values |
| 4 | +============================== |
5 | 5 |
|
6 |
| -Plot lines with points masked out. |
| 6 | +Sometimes you need to plot data with missing values. |
7 | 7 |
|
8 |
| -This would typically be used with gappy data, to |
9 |
| -break the line at the data gaps. |
10 |
| -''' |
| 8 | +One possibility is to simply remove undesired data points. The line plotted |
| 9 | +through the remaining data will be continuous, and not indicate where the |
| 10 | +missing data is located. |
| 11 | +
|
| 12 | +If it is useful to have gaps in the line where the data is missing, then the |
| 13 | +undesired points can be indicated using a `masked array`_ or by setting their |
| 14 | +values to NaN. No marker will be drawn where either x or y are masked and, if |
| 15 | +plotting with a line, it will be broken there. |
| 16 | +
|
| 17 | +.. _masked array: |
| 18 | + https://docs.scipy.org/doc/numpy/reference/maskedarray.generic.html |
| 19 | +
|
| 20 | +The following example illustrates the three cases: |
| 21 | +
|
| 22 | +1) Removing points. |
| 23 | +2) Masking points. |
| 24 | +3) Setting to NaN. |
| 25 | +""" |
11 | 26 |
|
12 | 27 | import matplotlib.pyplot as plt
|
13 | 28 | import numpy as np
|
14 | 29 |
|
15 |
| -x = np.arange(0, 2*np.pi, 0.02) |
16 |
| -y = np.sin(x) |
17 |
| -y1 = np.sin(2*x) |
18 |
| -y2 = np.sin(3*x) |
19 |
| -ym1 = np.ma.masked_where(y1 > 0.5, y1) |
20 |
| -ym2 = np.ma.masked_where(y2 < -0.5, y2) |
21 |
| - |
22 |
| -lines = plt.plot(x, y, x, ym1, x, ym2, 'o') |
23 |
| -plt.setp(lines[0], linewidth=4) |
24 |
| -plt.setp(lines[1], linewidth=2) |
25 |
| -plt.setp(lines[2], markersize=10) |
26 |
| - |
27 |
| -plt.legend(('No mask', 'Masked if > 0.5', 'Masked if < -0.5'), |
28 |
| - loc='upper right') |
29 |
| -plt.title('Masked line demo') |
| 30 | + |
| 31 | +x = np.linspace(-np.pi/2, np.pi/2, 31) |
| 32 | +y = np.cos(x)**3 |
| 33 | + |
| 34 | +# 1) remove points where y > 0.7 |
| 35 | +x2 = x[y <= 0.7] |
| 36 | +y2 = y[y <= 0.7] |
| 37 | + |
| 38 | +# 2) mask points where y > 0.7 |
| 39 | +y3 = np.ma.masked_where(y > 0.7, y) |
| 40 | + |
| 41 | +# 3) set to NaN where y > 0.7 |
| 42 | +y4 = y.copy() |
| 43 | +y4[y3 > 0.7] = np.nan |
| 44 | + |
| 45 | +plt.plot(x*0.1, y, 'o-', color='lightgrey', label='No mask') |
| 46 | +plt.plot(x2*0.4, y2, 'o-', label='Points removed') |
| 47 | +plt.plot(x*0.7, y3, 'o-', label='Masked values') |
| 48 | +plt.plot(x*1.0, y4, 'o-', label='NaN values') |
| 49 | +plt.legend() |
| 50 | +plt.title('Masked and NaN data') |
30 | 51 | plt.show()
|
0 commit comments