Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 60f9af8

Browse files
story645oscargussledziu32
committed
added hatch kwarg arg + tests + what's new
expanded basic pie example to include small examples of labels, autopct, colors, hatch, and distance reworded pctdistance and labeldistance b/c of #24789 Co-authored-by: Oscar Gustafsson <[email protected]> Co-authored-by: sledziu32 <[email protected]>
1 parent 5093150 commit 60f9af8

File tree

5 files changed

+156
-48
lines changed

5 files changed

+156
-48
lines changed
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
``hatch`` *kwarg* for pie
2+
-------------------------------------------
3+
4+
`~matplotlib.axes.Axes.pie` now accepts a *hatch* keyword that takes as input
5+
a hatch or list of hatches:
6+
7+
.. plot::
8+
:include-source: true
9+
10+
fig, (ax1, ax2) = plt.subplots(ncols=2)
11+
w1,_ = ax1.pie([1,1,1,1], hatch='\/|-', colors=['whitesmoke','silver'],
12+
wedgeprops={'edgecolor':'dimgray'})
13+
w2,_ = ax2.pie([1,1,1,1], hatch=[ '-O', '-', '-.O', '-.'],
14+
colors=['thistle'], wedgeprops={'edgecolor':'darkmagenta'})

examples/pie_and_polar_charts/pie_features.py

Lines changed: 86 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -3,39 +3,102 @@
33
Basic pie chart
44
===============
55
6-
Demo of a basic pie chart plus a few additional features.
7-
8-
In addition to the basic pie chart, this demo shows a few optional features:
9-
10-
* slice labels
11-
* auto-labeling the percentage
12-
* offsetting a slice with "explode"
13-
* drop-shadow
14-
* custom start angle
6+
Demo of plotting a `~matplotlib.axes.Axes.pie` chart
7+
"""
158

16-
Note about the custom start angle:
9+
# %%
10+
# Label slices
11+
# ----------------
12+
#
13+
# Plot a pie chart of animals and label the slices. To add
14+
# labels, pass a list of labels to the *labels* keyword argument
1715

18-
The default ``startangle`` is 0, which would start the "Frogs" slice on the
19-
positive x-axis. This example sets ``startangle = 90`` such that everything is
20-
rotated counter-clockwise by 90 degrees, and the frog slice starts on the
21-
positive y-axis.
22-
"""
2316
import matplotlib.pyplot as plt
24-
25-
# Pie chart, where the slices will be ordered and plotted counter-clockwise:
2617
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
2718
sizes = [15, 30, 45, 10]
28-
explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. 'Hogs')
2919

30-
fig1, ax1 = plt.subplots()
31-
ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
32-
shadow=True, startangle=90)
33-
ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
20+
fig, ax = plt.subplots()
21+
ax.pie(sizes, labels=labels)
3422

35-
plt.show()
23+
###############################################################################
24+
# Each slice of the pie chart is a `.patches.Wedge` object; therefore in
25+
# addition to the customizations shown here, each wedge can be customized as
26+
# demoed in :doc:`/gallery/pie_and_polar_charts/nested_pie`.
27+
28+
# %%
29+
# Auto-label slices
30+
# ---------------------------
31+
#
32+
# The pie function can use a format string or function passed to *autopct* to
33+
# label slices.
34+
35+
fig, ax = plt.subplots()
36+
ax.pie(sizes, labels=labels, autopct='%1.1f%%')
37+
38+
#################################################################
39+
# By default, the label values are obtained from the percent size of the slice.
40+
41+
# %%
42+
# Color slices
43+
# ----------------
44+
#
45+
# Pass a list of colors to *colors* to set the color of each slice.
46+
47+
fig, ax = plt.subplots()
48+
ax.pie(sizes, labels=labels,
49+
colors=['olivedrab', 'rosybrown', 'gray', 'saddlebrown'])
50+
51+
# %%
52+
# Hatch slices
53+
# ----------------
54+
#
55+
# Pass a list of hatch patterns to *hatch* to set the pattern of each slice.
56+
57+
fig, ax = plt.subplots()
58+
ax.pie(sizes, labels=labels, hatch=['**O', 'oO', 'O.O', '.||.'])
59+
60+
# %%
61+
# Swap label and autopct text positions
62+
# -------------------------------------
63+
# Use the *labeldistance* and *pctdistance* keywords to position the *labels*
64+
# and *autopct* text respectively.
65+
66+
fig, ax = plt.subplots()
67+
ax.pie(sizes, labels=labels, autopct='%1.1f%%',
68+
pctdistance=1.25, labeldistance=.6)
3669

3770
#############################################################################
71+
# *labeldistance* and *pctdistance* are ratios computed relative to the
72+
# distance of the radius, meaning that a distance of ``0`` places the text
73+
# at the center of the pie while ``1`` places the text at the edge of the pie.
74+
75+
# %%
76+
# Explode, shade, and rotate slices
77+
# ---------------------------------
78+
#
79+
# In addition to the basic pie chart, this demo shows a few optional features:
80+
#
81+
# * offsetting a slice using *explode*
82+
# * add a drop-shadow using *shadow*
83+
# * custom start angle using *startangle*
3884
#
85+
# This example orders the slices, separates (explodes) them, and plots them
86+
# counter-clockwise:
87+
88+
explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. 'Hogs')
89+
90+
fig, ax = plt.subplots()
91+
ax.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
92+
shadow=True, startangle=90)
93+
plt.show()
94+
95+
##############################################################################
96+
# The default *startangle* is 0, which would start the "Frogs" slice on the
97+
# positive x-axis. This example sets ``startangle = 90`` such that everything
98+
# is rotated counter-clockwise by 90 degrees, and the frog slice starts on the
99+
# positive y-axis.
100+
101+
##############################################################################
39102
# .. admonition:: References
40103
#
41104
# The use of the following functions, methods, classes and modules is shown

lib/matplotlib/axes/_axes.py

Lines changed: 36 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -3078,7 +3078,7 @@ def pie(self, x, explode=None, labels=None, colors=None,
30783078
autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1,
30793079
startangle=0, radius=1, counterclock=True,
30803080
wedgeprops=None, textprops=None, center=(0, 0),
3081-
frame=False, rotatelabels=False, *, normalize=True):
3081+
frame=False, rotatelabels=False, *, normalize=True, hatch=None):
30823082
"""
30833083
Plot a pie chart.
30843084
@@ -3104,29 +3104,34 @@ def pie(self, x, explode=None, labels=None, colors=None,
31043104
A sequence of colors through which the pie chart will cycle. If
31053105
*None*, will use the colors in the currently active cycle.
31063106
3107+
hatch : str or list, default: None
3108+
Hatching pattern applied to all pie wedges or sequence of patterns
3109+
through which the chart will cycle. For a list of valid patterns,
3110+
see :doc:`/gallery/shapes_and_collections/hatch_style_reference`
3111+
3112+
.. versionadded:: 3.7
3113+
31073114
autopct : None or str or callable, default: None
3108-
If not *None*, is a string or function used to label the wedges
3109-
with their numeric value. The label will be placed inside the
3110-
wedge. If it is a format string, the label will be ``fmt % pct``.
3111-
If it is a function, it will be called.
3115+
If not *None*, *autopct* a string or function used to label the
3116+
wedges with their numeric value. The label will be placed inside
3117+
the wedge. If it is a format string, the label will be
3118+
``fmt % pct``. If it is a function, it will be called.
31123119
31133120
pctdistance : float, default: 0.6
3114-
The ratio between the center of each pie slice and the start of
3115-
the text generated by *autopct*. Ignored if *autopct* is *None*.
3121+
The relative distance along the radius at which the the text
3122+
generated by *autopct* is drawn. To draw the text outside the pie,
3123+
set *pctdistance* > 1. This parameter is ignored if *autopct* is
3124+
``None``.
3125+
3126+
labeldistance : float or None, default: 1.1
3127+
The relative distance along the radius at which the labels are
3128+
drawn. To draw the labels inside the pie, set *labeldistance* < 1.
3129+
If set to ``None``, labels are not drawn but are still stored for
3130+
use in `.legend`.
31163131
31173132
shadow : bool, default: False
31183133
Draw a shadow beneath the pie.
31193134
3120-
normalize : bool, default: True
3121-
When *True*, always make a full pie by normalizing x so that
3122-
``sum(x) == 1``. *False* makes a partial pie if ``sum(x) <= 1``
3123-
and raises a `ValueError` for ``sum(x) > 1``.
3124-
3125-
labeldistance : float or None, default: 1.1
3126-
The radial distance at which the pie labels are drawn.
3127-
If set to ``None``, label are not drawn, but are stored for use in
3128-
``legend()``
3129-
31303135
startangle : float, default: 0 degrees
31313136
The angle by which the start of the pie is rotated,
31323137
counterclockwise from the x-axis.
@@ -3138,11 +3143,11 @@ def pie(self, x, explode=None, labels=None, colors=None,
31383143
Specify fractions direction, clockwise or counterclockwise.
31393144
31403145
wedgeprops : dict, default: None
3141-
Dict of arguments passed to the wedge objects making the pie.
3142-
For example, you can pass in ``wedgeprops = {'linewidth': 3}``
3143-
to set the width of the wedge border lines equal to 3.
3144-
For more details, look at the doc/arguments of the wedge object.
3145-
By default, ``clip_on=False``.
3146+
Dict of arguments passed to each `.patches.Wedge` of the pie.
3147+
For example, ``wedgeprops = {'linewidth': 3}`` sets the width of
3148+
the wedge border lines equal to 3. By default, ``clip_on=False``.
3149+
When there is a conflict between these properties and other
3150+
keywords, properties passed to *wedgeprops* take precedence.
31463151
31473152
textprops : dict, default: None
31483153
Dict of arguments to pass to the text objects.
@@ -3156,6 +3161,11 @@ def pie(self, x, explode=None, labels=None, colors=None,
31563161
rotatelabels : bool, default: False
31573162
Rotate each label to the angle of the corresponding slice if true.
31583163
3164+
normalize : bool, default: True
3165+
When *True*, always make a full pie by normalizing x so that
3166+
``sum(x) == 1``. *False* makes a partial pie if ``sum(x) <= 1``
3167+
and raises a `ValueError` for ``sum(x) > 1``.
3168+
31593169
data : indexable object, optional
31603170
DATA_PARAMETER_PLACEHOLDER
31613171
@@ -3226,7 +3236,9 @@ def get_next_color():
32263236
slices = []
32273237
autotexts = []
32283238

3229-
for frac, label, expl in zip(x, labels, explode):
3239+
hatch = itertools.cycle(np.atleast_1d(hatch))
3240+
3241+
for frac, label, expl, htch in zip(x, labels, explode, hatch):
32303242
x, y = center
32313243
theta2 = (theta1 + frac) if counterclock else (theta1 - frac)
32323244
thetam = 2 * np.pi * 0.5 * (theta1 + theta2)
@@ -3236,6 +3248,7 @@ def get_next_color():
32363248
w = mpatches.Wedge((x, y), radius, 360. * min(theta1, theta2),
32373249
360. * max(theta1, theta2),
32383250
facecolor=get_next_color(),
3251+
hatch=htch,
32393252
clip_on=False,
32403253
label=label)
32413254
w.set(**wedgeprops)

lib/matplotlib/pyplot.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2755,15 +2755,15 @@ def pie(
27552755
pctdistance=0.6, shadow=False, labeldistance=1.1,
27562756
startangle=0, radius=1, counterclock=True, wedgeprops=None,
27572757
textprops=None, center=(0, 0), frame=False,
2758-
rotatelabels=False, *, normalize=True, data=None):
2758+
rotatelabels=False, *, normalize=True, hatch=None, data=None):
27592759
return gca().pie(
27602760
x, explode=explode, labels=labels, colors=colors,
27612761
autopct=autopct, pctdistance=pctdistance, shadow=shadow,
27622762
labeldistance=labeldistance, startangle=startangle,
27632763
radius=radius, counterclock=counterclock,
27642764
wedgeprops=wedgeprops, textprops=textprops, center=center,
27652765
frame=frame, rotatelabels=rotatelabels, normalize=normalize,
2766-
**({"data": data} if data is not None else {}))
2766+
hatch=hatch, **({"data": data} if data is not None else {}))
27672767

27682768

27692769
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.

lib/matplotlib/tests/test_axes.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5740,6 +5740,24 @@ def test_normalize_kwarg_pie():
57405740
assert abs(t2[0][-1].theta2 - 360.) > 1e-3
57415741

57425742

5743+
@check_figures_equal()
5744+
def test_pie_hatch_single(fig_test, fig_ref):
5745+
x = [0.3, 0.3, 0.1]
5746+
hatch = '+'
5747+
fig_test.subplots().pie(x, hatch=hatch)
5748+
wedges, _ = fig_ref.subplots().pie(x)
5749+
[w.set_hatch(hatch) for w in wedges]
5750+
5751+
5752+
@check_figures_equal()
5753+
def test_pie_hatch_multi(fig_test, fig_ref):
5754+
x = [0.3, 0.3, 0.1]
5755+
hatch = ['/', '+', '.']
5756+
fig_test.subplots().pie(x, hatch=hatch)
5757+
wedges, _ = fig_ref.subplots().pie(x)
5758+
[w.set_hatch(hp) for w, hp in zip(wedges, hatch)]
5759+
5760+
57435761
@image_comparison(['set_get_ticklabels.png'])
57445762
def test_set_get_ticklabels():
57455763
# test issue 2246

0 commit comments

Comments
 (0)