|
| 1 | +""" |
| 2 | +============== |
| 3 | +Fill rule demo |
| 4 | +============== |
| 5 | +
|
| 6 | +By default, patches such as `~.patches.Polygon` are filled according to the |
| 7 | +`non-zero winding fill rule <https://en.wikipedia.org/wiki/Nonzero-rule>`__. |
| 8 | +Any given point has a winding number, which is the number of times the path |
| 9 | +wraps around the point in the clockwise direction. For this fill rule, the |
| 10 | +filled regions are where the winding number is non-zero. See |
| 11 | +:doc:`/gallery/shapes_and_collections/donut` for an example of how to leverage |
| 12 | +the winding directions in multiple segments of a path under this fill rule. |
| 13 | +
|
| 14 | +The other option for fill rule is the |
| 15 | +`even-odd fill rule <https://en.wikipedia.org/wiki/Even%E2%80%93odd_rule>`__, |
| 16 | +which is specified by setting the patch's ``fill_rule`` property to "evenodd". |
| 17 | +For this fill rule, the filled regions are where the winding number is an odd |
| 18 | +number. This fill rule allows for the construction of patterns of fill |
| 19 | +regions that would otherwise take many more vertices to construct under the |
| 20 | +non-zero winding fill rule. |
| 21 | +
|
| 22 | +This example demonstrates the difference between the two fill rules for a single |
| 23 | +`~.patches.Polygon` that intersects itself multiple times. The winding number |
| 24 | +for each closed region is labeled. |
| 25 | +
|
| 26 | +""" |
| 27 | + |
| 28 | +import matplotlib.pyplot as plt |
| 29 | +import numpy as np |
| 30 | + |
| 31 | +from matplotlib.patches import Polygon |
| 32 | + |
| 33 | +fig, axs = plt.subplots(1, 2) |
| 34 | + |
| 35 | +vertices = np.array([[0, 0, 6, 6, 1, 1, 5, 5, 2, 2, 4, 4, 3, 3, 5, 5], |
| 36 | + [2, 5, 5, 0, 0, 7, 7, 3, 3, 4, 4, 6, 6, 1, 1, 2]]).T |
| 37 | + |
| 38 | +labels = ['1', '0', '1', '2', '3', '2', '1', '1', '0'] |
| 39 | +label_xys = np.array([[2.0, 4.0, 0.5, 1.5, 2.5, 4.0, 3.5, 2.0, 3.5], |
| 40 | + [1.5, 1.5, 3.5, 3.5, 3.5, 3.5, 4.5, 5.5, 5.5]]).T |
| 41 | + |
| 42 | +for ax, fill_rule in zip(axs, ['nonzero', 'evenodd']): |
| 43 | + polygon = Polygon(vertices, facecolor='green', edgecolor='red', |
| 44 | + fill_rule=fill_rule) |
| 45 | + ax.add_patch(polygon) |
| 46 | + |
| 47 | + ax.plot(*vertices.T, '.', markersize=10, color='red') |
| 48 | + |
| 49 | + for label, label_xy in zip(labels, label_xys): |
| 50 | + ax.text(*label_xy, label, ha='center', va='center') |
| 51 | + |
| 52 | + ax.set_axis_off() |
| 53 | + ax.set_title(f'fill_rule={fill_rule}') |
| 54 | + |
| 55 | +plt.show() |
| 56 | + |
| 57 | +# %% |
| 58 | +# |
| 59 | +# .. admonition:: References |
| 60 | +# |
| 61 | +# The use of the following functions, methods, classes and modules is shown |
| 62 | +# in this example: |
| 63 | +# |
| 64 | +# - `matplotlib.patches` |
| 65 | +# - `matplotlib.patches.Polygon` |
| 66 | +# - `matplotlib.axes.Axes.add_patch` |
| 67 | +# - `matplotlib.patches.Patch.set_fill_rule` |
0 commit comments