|
| 1 | +""" |
| 2 | +================= |
| 3 | +Nested pie charts |
| 4 | +================= |
| 5 | +
|
| 6 | +The following examples show two ways to build a nested pie chart |
| 7 | +in Matplotlib. |
| 8 | +
|
| 9 | +""" |
| 10 | + |
| 11 | +from matplotlib import pyplot as plt |
| 12 | +import numpy as np |
| 13 | + |
| 14 | +############################################################################### |
| 15 | +# The most straightforward way to build a pie chart is to use the |
| 16 | +# :meth:`pie method <matplotlib.axes.Axes.pie>` |
| 17 | +# |
| 18 | +# In this case, pie takes values corresponding to counts in a group. |
| 19 | +# We'll first generate some fake data, corresponding to three groups. |
| 20 | +# In the outer circle, we'll treat each number as belonging to its |
| 21 | +# own group. In the inner circle, we'll plot them as members of their |
| 22 | +# original 3 groups. |
| 23 | + |
| 24 | +vals = np.array([[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]]) |
| 25 | +fig, ax = plt.subplots() |
| 26 | +ax.pie(vals.flatten(), radius=1.2, |
| 27 | + colors=plt.rcParams["axes.prop_cycle"].by_key()["color"][:vals.shape[1]]) |
| 28 | +ax.pie(vals.sum(axis=1), radius=1) |
| 29 | +ax.set(aspect="equal", title='Pie plot with `ax.pie`') |
| 30 | + |
| 31 | +plt.show() |
| 32 | + |
| 33 | +############################################################################### |
| 34 | +# However, you can accomplish the same output by using a bar plot on |
| 35 | +# axes with a polar coordinate system. This may give more flexibility on |
| 36 | +# the exact design of the plot. |
| 37 | +# |
| 38 | +# In this case, we need to map x-values of the bar chart onto radians of |
| 39 | +# a circle. |
| 40 | + |
| 41 | +fig, ax = plt.subplots(subplot_kw=dict(polar=True)) |
| 42 | + |
| 43 | +left_inner = np.arange(0.0, 2 * np.pi, 2 * np.pi / 6) |
| 44 | +left_middle = np.arange(0.0, 2 * np.pi, 2 * np.pi / 12) |
| 45 | +left_outer = np.arange(0.0, 2 * np.pi, 2 * np.pi / 9) |
| 46 | + |
| 47 | +ax.bar(left=left_inner, |
| 48 | + width=2 * np.pi / 6, bottom=0, color='C0', |
| 49 | + linewidth=2, edgecolor='w', |
| 50 | + height=np.zeros_like(left_inner) + 5) |
| 51 | + |
| 52 | +ax.bar(left=left_middle, |
| 53 | + width=2 * np.pi / 12, bottom=5, color='C1', |
| 54 | + linewidth=2, edgecolor='w', |
| 55 | + height=np.zeros_like(left_middle) + 2) |
| 56 | + |
| 57 | +ax.bar(left=left_outer, |
| 58 | + width=2 * np.pi / 9, bottom=7, color='C2', |
| 59 | + linewidth=2, edgecolor='w', |
| 60 | + height=np.zeros_like(left_outer) + 3) |
| 61 | + |
| 62 | +ax.set(title="Pie plot with `ax.bar` and polar coordinates") |
| 63 | +ax.set_axis_off() |
| 64 | +plt.show() |
0 commit comments