Sierpiński Triangle With Recursive Views

Matplotview’s views support recursive drawing of other views and themselves to a configurable depth. This feature allows matplotview to be used to generate fractals, such as a sierpiński triangle as shown in the following example.

plot 04 sierpinski triangle
10 import matplotlib.pyplot as plt
11 import matplotview as mpv
12 from matplotlib.patches import PathPatch
13 from matplotlib.path import Path
14 from matplotlib.transforms import Affine2D
15
16 # We'll plot a white upside down triangle inside of black one, and then use
17 # 3 views to draw all the rest of the recursions of the sierpiński triangle.
18 outside_color = "black"
19 inner_color = "white"
20
21 t = Affine2D().scale(-0.5)
22
23 outer_triangle = Path.unit_regular_polygon(3)
24 inner_triangle = t.transform_path(outer_triangle)
25 b = outer_triangle.get_extents()
26
27 fig, ax = plt.subplots(1)
28 ax.set_aspect(1)
29
30 ax.add_patch(PathPatch(outer_triangle, fc=outside_color, ec=[0] * 4))
31 ax.add_patch(PathPatch(inner_triangle, fc=inner_color, ec=[0] * 4))
32 ax.set_xlim(b.x0, b.x1)
33 ax.set_ylim(b.y0, b.y1)
34
35 ax_locs = [
36     [0, 0, 0.5, 0.5],
37     [0.5, 0, 0.5, 0.5],
38     [0.25, 0.5, 0.5, 0.5]
39 ]
40
41 for loc in ax_locs:
42     # Here we limit the render depth to 6 levels in total for each zoom view....
43     inax = mpv.inset_zoom_axes(ax, loc, render_depth=6)
44     inax.set_xlim(b.x0, b.x1)
45     inax.set_ylim(b.y0, b.y1)
46     inax.axis("off")
47     inax.patch.set_visible(False)
48
49 fig.show()

Total running time of the script: (0 minutes 4.346 seconds)

Gallery generated by Sphinx-Gallery