Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

ENH: introduce PieContainer and pie_label method#30733

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Open
rcomer wants to merge1 commit intomatplotlib:main
base:main
Choose a base branch
Loading
fromrcomer:pie_label
Open
Show file tree
Hide file tree
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletionsdoc/api/axes_api.rst
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -73,6 +73,7 @@ Basic
Axes.eventplot

Axes.pie
Axes.pie_label

Axes.stackplot

Expand Down
1 change: 1 addition & 0 deletionsdoc/api/pyplot_summary.rst
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -64,6 +64,7 @@ Basic
stem
eventplot
pie
pie_label
stackplot
broken_barh
vlines
Expand Down
28 changes: 28 additions & 0 deletionsdoc/release/next_whats_new/pie_label.rst
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
Adding labels to pie chart wedges
---------------------------------

The new `~.Axes.pie_label` method adds a label to each wedge in a pie chart created with
`~.Axes.pie`. It can take

* a list of strings, similar to the existing *labels* parameter of `~.Axes.pie`
* a format string in analogy to the existing *autopct* parameter of `~.Axes.pie` except
that it uses the `str.format` method, and it can handle absolute values as well as
fractions/percentages

For more examples, see:doc:`/gallery/pie_and_polar_charts/pie_label`.

..plot::
:include-source: true
:alt: A pie chart with three labels on each wedge, showing a food type, number and fraction associated with the wedge.

import matplotlib.pyplot as plt

data = [36, 24, 8, 12]
labels = ['spam', 'eggs', 'bacon', 'sausage']

fig, ax = plt.subplots()
pie = ax.pie(data)

ax.pie_label(pie, labels, distance=1.1)
ax.pie_label(pie, '{frac:.1%}', distance=0.7)
ax.pie_label(pie, '{absval:d}', distance=0.4)
6 changes: 3 additions & 3 deletionsgalleries/examples/misc/svg_filter_pie.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,16 +28,16 @@

# We want to draw the shadow for each pie, but we will not use "shadow"
# option as it doesn't save the references to the shadow patches.
pies = ax.pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%')
pie = ax.pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%')

for w inpies[0]:
for w inpie.wedges:
# set the id with the label.
w.set_gid(w.get_label())

# we don't want to draw the edge of the pie
w.set_edgecolor("none")

for w inpies[0]:
for w inpie.wedges:
# create shadow patch
s = Shadow(w, -0.01, -0.01)
s.set_gid(w.get_gid() + "_shadow")
Expand Down
38 changes: 18 additions & 20 deletionsgalleries/examples/pie_and_polar_charts/pie_and_donut_labels.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,7 +6,8 @@
Welcome to the Matplotlib bakery. We will create a pie and a donut
chart through the `pie method <matplotlib.axes.Axes.pie>` and
show how to label them with a `legend <matplotlib.axes.Axes.legend>`
as well as with `annotations <matplotlib.axes.Axes.annotate>`.
as well as with the `pie_label method <matplotlib.axes.Axes.pie>` and
`annotations <matplotlib.axes.Axes.annotate>`.
"""

# %%
Expand All@@ -15,12 +16,14 @@
# Now it's time for the pie. Starting with a pie recipe, we create the data
# and a list of labels from it.
#
# We can provide a function to the ``autopct`` argument, which will expand
# automatic percentage labeling by showing absolute values; we calculate
# the latter back from relative data and the known sum of all values.
# We then create the pie and store the returned `~matplotlib.container.PieContainer`
# object for later.
#
# We then create the pie and store the returned objects for later. The first
# returned element of the returned tuple is a list of the wedges. Those are
# We can provide the `~matplotlib.container.PieContainer` and a format string to
# the `~matplotlib.axes.Axes.pie_label` method to automatically label each
# ingredient's wedge with its weight in grams and percentages.
#
# The `~.PieContainer` has a list of patches as one of its attributes. Those are
# `matplotlib.patches.Wedge` patches, which can directly be used as the handles
# for a legend. We can use the legend's ``bbox_to_anchor`` argument to position
# the legend outside of the pie. Here we use the axes coordinates ``(1, 0, 0.5,
Expand All@@ -31,32 +34,26 @@
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(figsize=(6, 3), subplot_kw=dict(aspect="equal"))
fig, ax = plt.subplots(figsize=(6, 3))

recipe = ["375 g flour",
"75 g sugar",
"250 g butter",
"300 g berries"]

data = [float(x.split()[0]) for x in recipe]
data = [int(x.split()[0]) for x in recipe]
ingredients = [x.split()[-1] for x in recipe]

pie = ax.pie(data)

def func(pct, allvals):
absolute = int(np.round(pct/100.*np.sum(allvals)))
return f"{pct:.1f}%\n({absolute:d} g)"

ax.pie_label(pie, '{frac:.1%}\n({absval:d}g)',
textprops=dict(color="w", size=8, weight="bold"))

wedges, texts, autotexts = ax.pie(data, autopct=lambda pct: func(pct, data),
textprops=dict(color="w"))

ax.legend(wedges, ingredients,
ax.legend(pie.wedges, ingredients,
title="Ingredients",
loc="center left",
bbox_to_anchor=(1, 0, 0.5, 1))

plt.setp(autotexts, size=8, weight="bold")

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

plt.show()
Expand DownExpand Up@@ -97,13 +94,13 @@ def func(pct, allvals):

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

wedges, texts = ax.pie(data, wedgeprops=dict(width=0.5), startangle=-40)
pie = ax.pie(data, wedgeprops=dict(width=0.5), startangle=-40)

bbox_props = dict(boxstyle="square,pad=0.3", fc="w", ec="k", lw=0.72)
kw = dict(arrowprops=dict(arrowstyle="-"),
bbox=bbox_props, zorder=0, va="center")

for i, p in enumerate(wedges):
for i, p in enumerate(pie.wedges):
ang = (p.theta2 - p.theta1)/2. + p.theta1
y = np.sin(np.deg2rad(ang))
x = np.cos(np.deg2rad(ang))
Expand DownExpand Up@@ -131,6 +128,7 @@ def func(pct, allvals):
# in this example:
#
# - `matplotlib.axes.Axes.pie` / `matplotlib.pyplot.pie`
# - `matplotlib.axes.Axes.pie_label` / `matplotlib.pyplot.pie_label`
# - `matplotlib.axes.Axes.legend` / `matplotlib.pyplot.legend`
#
# .. tags::
Expand Down
100 changes: 100 additions & 0 deletionsgalleries/examples/pie_and_polar_charts/pie_label.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
"""
===================
Labeling pie charts
===================

This example illustrates some features of the `~matplotlib.axes.Axes.pie_label`
method, which adds labels to an existing pie chart created with
`~matplotlib.axes.Axes.pie`.
"""

# %%
# The simplest option is to provide a list of strings to label each slice of the pie.

import matplotlib.pyplot as plt

data = [36, 24, 8, 12]
labels = ['spam', 'eggs', 'bacon', 'sausage']

fig, ax = plt.subplots()
pie = ax.pie(data)
ax.pie_label(pie, labels)

# %%
#
# If you want the labels outside the pie, set a *distance* greater than 1.
# This is the distance from the center of the pie as a fraction of its radius.

fig, ax = plt.subplots()
pie = ax.pie(data)
ax.pie_label(pie, labels, distance=1.1)

# %%
#
# You can also rotate the labels so they are oriented away from the pie center.

fig, ax = plt.subplots()
pie = ax.pie(data)
ax.pie_label(pie, labels, rotate=True)

# %%
#
# Instead of explicit labels, pass a format string to label slices with their values...

fig, ax = plt.subplots()
pie = ax.pie(data)
ax.pie_label(pie, '{absval:.1f}')

# %%
#
# ...or with their percentages...

fig, ax = plt.subplots()
pie = ax.pie(data)
ax.pie_label(pie, '{frac:.1%}')

# %%
#
# ...or both.

fig, ax = plt.subplots()
pie = ax.pie(data)
ax.pie_label(pie, '{absval:d}\n{frac:.1%}')

# %%
#
# Font styling can be configured by passing a dictionary to the *textprops* parameter.

fig, ax = plt.subplots()
pie = ax.pie(data)
ax.pie_label(pie, labels, textprops={'fontsize': 'large', 'color': 'white'})

# %%
#
# `~matplotlib.axes.Axes.pie_label` can be called repeatedly to add multiple sets
# of labels.

# sphinx_gallery_thumbnail_number = -1

fig, ax = plt.subplots()
pie = ax.pie(data)

ax.pie_label(pie, labels, distance=1.1)
ax.pie_label(pie, '{frac:.1%}', distance=0.7)
ax.pie_label(pie, '{absval:d}', distance=0.4)

plt.show()

# %%
# .. admonition:: References
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
#
# - `matplotlib.axes.Axes.pie` / `matplotlib.pyplot.pie`
# - `matplotlib.axes.Axes.pie_label` / `matplotlib.pyplot.pie_label`
#
# .. tags::
#
# plot-type: pie
# level: beginner
Loading
Loading

[8]ページ先頭

©2009-2025 Movatter.jp