|
1 | 1 | """
|
2 | 2 | Plot demonstrating the integral as the area under a curve.
|
| 3 | +
|
| 4 | +Although this is a simple example, it demonstrates some important tweaks: |
| 5 | +
|
| 6 | + * A simple line plot with custom color and line width. |
| 7 | + * A shaded region created using a Polygon patch. |
| 8 | + * A text label with mathtext rendering. |
| 9 | + * figtext calls to label the x- and y-axes. |
| 10 | + * Use of axis spines to hide the top and right spines. |
| 11 | + * Custom tick placement and labels. |
3 | 12 | """
|
4 | 13 | import numpy as np
|
5 | 14 | import matplotlib.pyplot as plt
|
6 | 15 | from matplotlib.patches import Polygon
|
7 | 16 |
|
| 17 | + |
8 | 18 | def func(x):
|
9 |
| - return (x-3)*(x-5)*(x-7)+85 |
| 19 | + return (x - 3) * (x - 5) * (x - 7) + 85 |
10 | 20 |
|
11 |
| -fig, ax = plt.subplots() |
12 | 21 |
|
13 |
| -a, b = 2, 9 # integral area |
| 22 | +a, b = 2, 9 # integral limits |
14 | 23 | x = np.linspace(0, 10)
|
15 | 24 | y = func(x)
|
| 25 | + |
| 26 | +fig, ax = plt.subplots() |
16 | 27 | plt.plot(x, y, 'r', linewidth=2)
|
| 28 | +plt.ylim(ymin=0) |
17 | 29 |
|
18 |
| -# make the shaded region |
| 30 | +# Make the shaded region |
19 | 31 | ix = np.linspace(a, b)
|
20 | 32 | iy = func(ix)
|
21 |
| -verts = [(a,0)] + list(zip(ix,iy)) + [(b,0)] |
| 33 | +verts = [(a, 0)] + list(zip(ix, iy)) + [(b, 0)] |
22 | 34 | poly = Polygon(verts, facecolor='0.9', edgecolor='0.5')
|
23 | 35 | ax.add_patch(poly)
|
24 | 36 |
|
25 |
| -plt.text(0.5 * (a + b), 30, |
26 |
| - r"$\int_a^b f(x)\mathrm{d}x$", horizontalalignment='center', |
27 |
| - fontsize=20) |
| 37 | +plt.text(0.5 * (a + b), 30, r"$\int_a^b f(x)\mathrm{d}x$", |
| 38 | + horizontalalignment='center', fontsize=20) |
28 | 39 |
|
29 |
| -plt.axis([0,10, 0, 180]) |
30 | 40 | plt.figtext(0.9, 0.05, '$x$')
|
31 | 41 | plt.figtext(0.1, 0.9, '$y$')
|
32 | 42 |
|
33 | 43 | ax.spines['right'].set_visible(False)
|
34 | 44 | ax.spines['top'].set_visible(False)
|
35 |
| -ax.set_xticks((a,b)) |
36 |
| -ax.set_xticklabels(('$a$','$b$')) |
| 45 | +ax.xaxis.set_ticks_position('bottom') |
| 46 | + |
| 47 | +ax.set_xticks((a, b)) |
| 48 | +ax.set_xticklabels(('$a$', '$b$')) |
37 | 49 | ax.set_yticks([])
|
38 | 50 |
|
39 | 51 | plt.show()
|
0 commit comments