|
| 1 | +""" |
| 2 | +Illustrate different ways of using the various fill functions. |
| 3 | +""" |
| 4 | +import numpy as np |
| 5 | +import matplotlib.pyplot as plt |
| 6 | + |
| 7 | +import example_utils |
| 8 | + |
| 9 | +def main(): |
| 10 | + fig, axes = example_utils.setup_axes() |
| 11 | + |
| 12 | + fill_example(axes[0]) |
| 13 | + fill_between_example(axes[1]) |
| 14 | + stackplot_example(axes[2]) |
| 15 | + |
| 16 | + example_utils.title(fig, 'fill/fill_between/stackplot: Filled polygons', |
| 17 | + y=0.95) |
| 18 | + fig.savefig('fill_example.png', facecolor='none') |
| 19 | + plt.show() |
| 20 | + |
| 21 | +def fill_example(ax): |
| 22 | + # Use fill when you want a simple filled polygon between vertices |
| 23 | + x, y = fill_data() |
| 24 | + ax.fill(x, y, color='lightblue') |
| 25 | + ax.margins(0.1) |
| 26 | + example_utils.label(ax, 'fill') |
| 27 | + |
| 28 | +def fill_between_example(ax): |
| 29 | + # Fill between fills between two curves or a curve and a constant value |
| 30 | + # It can be used in several ways. We'll illustrate a few below. |
| 31 | + x, y1, y2 = sin_data() |
| 32 | + |
| 33 | + # The most basic (and common) use of fill_between |
| 34 | + err = np.random.rand(x.size)**2 + 0.1 |
| 35 | + y = 0.7 * x + 2 |
| 36 | + ax.fill_between(x, y + err, y - err, color='orange') |
| 37 | + |
| 38 | + # Filling between two curves with different colors when they cross in |
| 39 | + # different directions |
| 40 | + ax.fill_between(x, y1, y2, where=y1>y2, color='lightblue') |
| 41 | + ax.fill_between(x, y1, y2, where=y1<y2, color='forestgreen') |
| 42 | + |
| 43 | + # Note that this is fillbetween*x*! |
| 44 | + ax.fill_betweenx(x, -y1, where=y1>0, color='red', alpha=0.5) |
| 45 | + ax.fill_betweenx(x, -y1, where=y1<0, color='blue', alpha=0.5) |
| 46 | + |
| 47 | + ax.margins(0.15) |
| 48 | + example_utils.label(ax, 'fill_between/x') |
| 49 | + |
| 50 | +def stackplot_example(ax): |
| 51 | + # Stackplot is equivalent to a series of ax.fill_between calls |
| 52 | + x, y = stackplot_data() |
| 53 | + ax.stackplot(x, y.cumsum(axis=0), alpha=0.5) |
| 54 | + example_utils.label(ax, 'stackplot') |
| 55 | + |
| 56 | +#-- Data generation ---------------------- |
| 57 | + |
| 58 | +def stackplot_data(): |
| 59 | + x = np.linspace(0, 10, 100) |
| 60 | + y = np.random.normal(0, 1, (5, 100)) |
| 61 | + y = y.cumsum(axis=1) |
| 62 | + y -= y.min(axis=0, keepdims=True) |
| 63 | + return x, y |
| 64 | + |
| 65 | +def sin_data(): |
| 66 | + x = np.linspace(0, 10, 100) |
| 67 | + y = np.sin(x) |
| 68 | + y2 = np.cos(x) |
| 69 | + return x, y, y2 |
| 70 | + |
| 71 | +def fill_data(): |
| 72 | + t = np.linspace(0, 2*np.pi, 100) |
| 73 | + r = np.random.normal(0, 1, 100).cumsum() |
| 74 | + r -= r.min() |
| 75 | + return r * np.cos(t), r * np.sin(t) |
| 76 | + |
| 77 | +main() |
0 commit comments