Skip to content

Commit df2c889

Browse files
added pie labeling example (rev1)
1 parent b3684ed commit df2c889

File tree

1 file changed

+34
-33
lines changed

1 file changed

+34
-33
lines changed

examples/pie_and_polar_charts/pie_and_donut_labels.py

Lines changed: 34 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,14 @@
66
Welcome to the matplotlib bakery. We will create a pie and a donut
77
chart through the :meth:`pie method <matplotlib.axes.Axes.pie>` and
88
show how to label them with a :meth:`legend <matplotlib.axes.Axes.legend>`
9-
as well as with :meth:`annotations <matplotlib.axes.Axes.annotation>`.
9+
as well as with :meth:`annotations <matplotlib.axes.Axes.annotate>`.
1010
"""
1111

1212
###############################################################################
1313
# As usual we would start by defining the imports and create a figure with
1414
# subplots. To have some space for the big cake, we use
15-
# :meth:`subplots_adjust <matplotlib.figure.subplots_adjust>` to adjust the
16-
# spacings.
15+
# :meth:`subplots_adjust <matplotlib.figure.Figure.subplots_adjust>` to
16+
# adjust the spacings.
1717

1818
import numpy as np
1919
import matplotlib.pyplot as plt
@@ -22,25 +22,24 @@
2222
fig.subplots_adjust(top=0.92, bottom=0.08)
2323
plt.setp((ax, ax2), aspect="equal")
2424

25-
2625
###############################################################################
2726
# Now it's time for the pie. Starting with a pie recipe, we create the data
2827
# and a list of labels from it.
2928
#
30-
# We can `provide a function to the ``autopct`` argument, which will expand
31-
# automatic percentage labeling by the absolute values, which we calculate
32-
# back from realtive data and the known sum of all values.
29+
# We can provide a function to the ``autopct`` argument, which will expand
30+
# automatic percentage labeling by showing absolute values; we calculate
31+
# the latter back from realtive data and the known sum of all values.
3332
#
34-
# We then create the pie and store the tuple of returned objects in a
35-
# variable ``pie``.
36-
# The first returned element of that tuple is a list of the wedges. Those are
33+
# We then create the pie and store the returned objects for later.
34+
# The first returned element of the returned tuple is a list of the wedges.
35+
# Those are
3736
# :class:`matplotlib.patches.Wedge <matplotlib.patches.Wedge>` patches, which
38-
# can directly be used as the handles for a legend. We can use the
37+
# can directly be used as the handles for a legend. We can use the
3938
# legend's ``bbox_to_anchor`` argument to position the legend outside of
40-
# the pie. Here we use the axes coordinates ``(1, 0, 0.5, 1)`` together
39+
# the pie. Here we use the axes coordinates ``(1, 0, 0.5, 1)`` together
4140
# with the location ``"center left"``; i.e.
4241
# the left central point of the legend will be at the left central point of the
43-
# bounding box, spanning from ``(1,0)`` to ``(1.5,1)`` in axes coordinates.
42+
# bounding box, spanning from ``(1,0)`` to ``(1.5,1)`` in axes coordinates.
4443

4544

4645
recipe = ["375 g flour",
@@ -51,44 +50,47 @@
5150
data = [float(x.split()[0]) for x in recipe]
5251
ingredients = [x.split()[-1] for x in recipe]
5352

53+
5454
def func(pct, allvals):
5555
absolute = int(pct/100.*np.sum(allvals))
5656
return "{:.1f}%\n({:d} g)".format(pct, absolute)
5757

58-
pie = ax.pie(data, autopct=lambda pct: func(pct, data),
59-
textprops=dict(color="w"))
6058

61-
ax.legend(pie[0], ingredients,
59+
wedges, texts, autotexts = ax.pie(data, autopct=lambda pct: func(pct, data),
60+
textprops=dict(color="w"))
61+
62+
ax.legend(wedges, ingredients,
6263
title="Ingredients",
6364
loc="center left",
6465
bbox_to_anchor=(1, 0, 0.5, 1))
6566

66-
plt.setp(pie[2], size=8, weight="bold")
67+
plt.setp(autotexts, size=8, weight="bold")
6768

6869
ax.set_title("Matplotlib bakery: A pie")
6970

7071

71-
7272
###############################################################################
7373
# Now it's time for the donut. Starting with a donut recipe, we transcribe
7474
# the data to numbers (converting 1 egg to 50 g), and directly plot the pie.
75-
# The pie? Wait... it's going to be donut, is it not?
75+
# The pie? Wait... it's going to be donut, is it not?
7676
# Well, as we see here, the donut is a pie, having a certain ``width`` set to
7777
# the wedges, which is different from its radius. It's as easy as it gets.
7878
# This is done via the ``wedgeprops`` argument.
7979
#
80-
# Labeling the wedges is done via ``annotate``. We first create some
80+
# We then want to label the wedges via
81+
# :meth:`annotations <matplotlib.axes.Axes.annotate>`. We first create some
8182
# dictionaries of common properties, which we can later pass as keyword
8283
# argument. We then iterate over all wedges and for each
8384
#
84-
# * calcualte the angle of the wedge's center
85-
# * from that obtain the coordinates of the point at that angle on the
86-
# circonference
85+
# * calculate the angle of the wedge's center,
86+
# * from that obtain the coordinates of the point at that angle on the
87+
# circumference,
8788
# * determine the horizontal alignment of the text, depending on which side
88-
# of the circle the point lies.
89+
# of the circle the point lies,
8990
# * update the connection style with the obtained angle to have the annotation
90-
# arrow point outwards from the donut
91-
# * finally create the annotation with all the previously determined parameters
91+
# arrow point outwards from the donut,
92+
# * finally, create the annotation with all the previously
93+
# determined parameters.
9294

9395
recipe = ["225 g flour",
9496
"90 g sugar",
@@ -99,23 +101,22 @@ def func(pct, allvals):
99101

100102
data = [225, 90, 50, 60, 100, 5]
101103

102-
donut = ax2.pie(data, radius=1, wedgeprops=dict(width=0.5), startangle=-40)
104+
wedges, texts = ax2.pie(data, wedgeprops=dict(width=0.5), startangle=-40)
103105

104106
bbox_props = dict(boxstyle="square,pad=0.3", fc="w", ec="k", lw=0.72)
105-
kw = dict(xycoords='data',textcoords='data',arrowprops=dict(arrowstyle="-"),
107+
kw = dict(xycoords='data', textcoords='data', arrowprops=dict(arrowstyle="-"),
106108
bbox=bbox_props, zorder=0, va="center")
107109

108-
for i, p in enumerate(donut[0]):
110+
for i, p in enumerate(wedges):
109111
ang = (p.theta2 - p.theta1)/2. + p.theta1
110112
y = np.sin(np.deg2rad(ang))
111113
x = np.cos(np.deg2rad(ang))
112114
horizontalalignment = ["", "left", "right"][int(np.sign(x))]
113115
connectionstyle = "angle,angleA=0,angleB={}".format(ang)
114-
kw["arrowprops"].update({"connectionstyle" : connectionstyle})
116+
kw["arrowprops"].update({"connectionstyle":connectionstyle})
115117
ax2.annotate(recipe[i], xy=(x, y), xytext=(1.35*np.sign(x), 1.4*y),
116118
horizontalalignment=horizontalalignment, **kw)
117-
118-
ax2.set_title("Matplotlib bakery: A donut")
119119

120-
plt.show()
120+
ax2.set_title("Matplotlib bakery: A donut")
121121

122+
plt.show()

0 commit comments

Comments
 (0)