|
| 1 | +''' |
| 2 | +Demonstrate how to create semi-transparent polygons which fill the space |
| 3 | +under a line graph, creating a sort of 'jagged stained glass' effect. |
| 4 | +''' |
| 5 | + |
1 | 6 | from mpl_toolkits.mplot3d import Axes3D
|
2 | 7 | from matplotlib.collections import PolyCollection
|
3 | 8 | from matplotlib.colors import colorConverter
|
4 | 9 | import matplotlib.pyplot as plt
|
5 | 10 | import numpy as np
|
6 | 11 |
|
7 | 12 |
|
| 13 | +def cc(arg): |
| 14 | + ''' |
| 15 | + Shorthand to convert 'named' colors to rgba format at 60% opacity. |
| 16 | + ''' |
| 17 | + return colorConverter.to_rgba(arg, alpha=0.6) |
| 18 | + |
| 19 | + |
| 20 | +def polygon_under_graph(xlist, ylist): |
| 21 | + ''' |
| 22 | + Construct the vertex list which defines the polygon filling the space under |
| 23 | + the (xlist, ylist) line graph. Assumes the xs are in ascending order. |
| 24 | + ''' |
| 25 | + return [(xlist[0], 0.)] + list(zip(xlist, ylist)) + [(xlist[-1], 0.)] |
| 26 | + |
| 27 | + |
8 | 28 | fig = plt.figure()
|
9 | 29 | ax = fig.gca(projection='3d')
|
10 | 30 |
|
| 31 | +# Make verts a list, verts[i] will be a list of (x,y) pairs defining polygon i |
| 32 | +verts = [] |
11 | 33 |
|
12 |
| -def cc(arg): |
13 |
| - return colorConverter.to_rgba(arg, alpha=0.6) |
| 34 | +# Set up the x sequence |
| 35 | +xs = np.linspace(0., 10., 26) |
14 | 36 |
|
15 |
| -xs = np.arange(0, 10, 0.4) |
16 |
| -verts = [] |
17 |
| -zs = [0.0, 1.0, 2.0, 3.0] |
18 |
| -for z in zs: |
| 37 | +# The ith polygon will appear on the plane y = zs[i] |
| 38 | +zs = range(4) |
| 39 | + |
| 40 | +for i in zs: |
19 | 41 | ys = np.random.rand(len(xs))
|
20 |
| - ys[0], ys[-1] = 0, 0 |
21 |
| - verts.append(list(zip(xs, ys))) |
| 42 | + verts.append(polygon_under_graph(xs, ys)) |
22 | 43 |
|
23 |
| -poly = PolyCollection(verts, facecolors=[cc('r'), cc('g'), cc('b'), |
24 |
| - cc('y')]) |
25 |
| -poly.set_alpha(0.7) |
| 44 | +poly = PolyCollection(verts, facecolors=[cc('r'), cc('g'), cc('b'), cc('y')]) |
26 | 45 | ax.add_collection3d(poly, zs=zs, zdir='y')
|
27 | 46 |
|
28 | 47 | ax.set_xlabel('X')
|
29 |
| -ax.set_xlim3d(0, 10) |
30 | 48 | ax.set_ylabel('Y')
|
31 |
| -ax.set_ylim3d(-1, 4) |
32 | 49 | ax.set_zlabel('Z')
|
33 |
| -ax.set_zlim3d(0, 1) |
| 50 | +ax.set_xlim(0, 10) |
| 51 | +ax.set_ylim(-1, 4) |
| 52 | +ax.set_zlim(0, 1) |
34 | 53 |
|
35 | 54 | plt.show()
|
0 commit comments