6
6
Welcome to the matplotlib bakery. We will create a pie and a donut
7
7
chart through the :meth:`pie method <matplotlib.axes.Axes.pie>` and
8
8
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 >`.
10
10
"""
11
11
12
12
###############################################################################
13
13
# As usual we would start by defining the imports and create a figure with
14
14
# 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.
17
17
18
18
import numpy as np
19
19
import matplotlib .pyplot as plt
22
22
fig .subplots_adjust (top = 0.92 , bottom = 0.08 )
23
23
plt .setp ((ax , ax2 ), aspect = "equal" )
24
24
25
-
26
25
###############################################################################
27
26
# Now it's time for the pie. Starting with a pie recipe, we create the data
28
27
# and a list of labels from it.
29
28
#
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.
33
32
#
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
37
36
# :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
39
38
# 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
41
40
# with the location ``"center left"``; i.e.
42
41
# 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.
44
43
45
44
46
45
recipe = ["375 g flour" ,
51
50
data = [float (x .split ()[0 ]) for x in recipe ]
52
51
ingredients = [x .split ()[- 1 ] for x in recipe ]
53
52
53
+
54
54
def func (pct , allvals ):
55
55
absolute = int (pct / 100. * np .sum (allvals ))
56
56
return "{:.1f}%\n ({:d} g)" .format (pct , absolute )
57
57
58
- pie = ax .pie (data , autopct = lambda pct : func (pct , data ),
59
- textprops = dict (color = "w" ))
60
58
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 ,
62
63
title = "Ingredients" ,
63
64
loc = "center left" ,
64
65
bbox_to_anchor = (1 , 0 , 0.5 , 1 ))
65
66
66
- plt .setp (pie [ 2 ] , size = 8 , weight = "bold" )
67
+ plt .setp (autotexts , size = 8 , weight = "bold" )
67
68
68
69
ax .set_title ("Matplotlib bakery: A pie" )
69
70
70
71
71
-
72
72
###############################################################################
73
73
# Now it's time for the donut. Starting with a donut recipe, we transcribe
74
74
# 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?
76
76
# Well, as we see here, the donut is a pie, having a certain ``width`` set to
77
77
# the wedges, which is different from its radius. It's as easy as it gets.
78
78
# This is done via the ``wedgeprops`` argument.
79
79
#
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
81
82
# dictionaries of common properties, which we can later pass as keyword
82
83
# argument. We then iterate over all wedges and for each
83
84
#
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,
87
88
# * 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,
89
90
# * 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.
92
94
93
95
recipe = ["225 g flour" ,
94
96
"90 g sugar" ,
@@ -99,23 +101,22 @@ def func(pct, allvals):
99
101
100
102
data = [225 , 90 , 50 , 60 , 100 , 5 ]
101
103
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 )
103
105
104
106
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 = "-" ),
106
108
bbox = bbox_props , zorder = 0 , va = "center" )
107
109
108
- for i , p in enumerate (donut [ 0 ] ):
110
+ for i , p in enumerate (wedges ):
109
111
ang = (p .theta2 - p .theta1 )/ 2. + p .theta1
110
112
y = np .sin (np .deg2rad (ang ))
111
113
x = np .cos (np .deg2rad (ang ))
112
114
horizontalalignment = ["" , "left" , "right" ][int (np .sign (x ))]
113
115
connectionstyle = "angle,angleA=0,angleB={}" .format (ang )
114
- kw ["arrowprops" ].update ({"connectionstyle" : connectionstyle })
116
+ kw ["arrowprops" ].update ({"connectionstyle" : connectionstyle })
115
117
ax2 .annotate (recipe [i ], xy = (x , y ), xytext = (1.35 * np .sign (x ), 1.4 * y ),
116
118
horizontalalignment = horizontalalignment , ** kw )
117
-
118
- ax2 .set_title ("Matplotlib bakery: A donut" )
119
119
120
- plt . show ( )
120
+ ax2 . set_title ( "Matplotlib bakery: A donut" )
121
121
122
+ plt .show ()
0 commit comments