python - 如何在 Matplotlib 饼图周围绘制箭头以将每个标签指向圆圈中各自的部分?

标签 python matplotlib

我一直在用 Matplotlib 绘制一些图表,我有一个饼图,想要在图表周围绘制箭头,使每个标签都指向图表,我有一个示例:

enter image description here

这是我当前的代码:

import matplotlib.pyplot as plt
plt.rcParams['font.family'] = 'Arial'
labels = ['Section 1', 'Section 2', 'Section 3', 'Section 4', 'Section 5']
sizes = [20, 20, 20, 20, 20]

fig1, ax1 = plt.subplots()
fig1.set_size_inches(3,3)
ax1.pie(sizes, explode=None, labels=labels, autopct='',
        shadow=False, startangle=0)
ax1.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.


plt.savefig('real.png', bbox_inches = 'tight',
    pad_inches = 0)
plt.show()

当前代码生成此图表:

enter image description here

如何实现上述(第一个)图像结果?

最佳答案

您可以使用annotations基于楔子的角度。请参阅tutorial对于许多带有箭头选项和文本周围边框的示例。

import numpy as np
import matplotlib.pyplot as plt

plt.rcParams['font.family'] = 'Arial'
labels = ['Section 1', 'Section 2', 'Section 3', 'Section 4', 'Section 5']
sizes = [20, 20, 20, 20, 20]

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

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

kw = dict(arrowprops=dict(arrowstyle="->"), va="center")
for p, label in zip(wedges, labels):
    ang = np.deg2rad((p.theta1 + p.theta2)/2)
    y = np.sin(ang)
    x = np.cos(ang)
    horizontalalignment = "center" if abs(x) < abs(y) else "right" if x < 0 else "left"
    ax.annotate(label, xy=(0.75*x, 0.75*y), xytext=(1.3*x, 1.3*y),
                horizontalalignment=horizontalalignment, **kw)
plt.tight_layout()
plt.show()

pie plot with arrows

关于python - 如何在 Matplotlib 饼图周围绘制箭头以将每个标签指向圆圈中各自的部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67023749/

相关文章:

python - Python 中的二叉树

python - 在 Pandas 中加入数据框

python - 在 Jupyter 上启动 python 脚本作为后台作业

python - Matplotlib.savefig 忽略轴并在图像周围绘制黑色边框

Python nosetest 不起作用,但直接运行它可以使用 matplotlib 的 @image_comparison

python - 使用循环 Python 绘制重复值

python - 如何从列表中随机调用任何方法

python - Pandas:按日期时间(可能不存在)对数据帧进行切片并返回 View

python - 辅助 y 轴上的 Matplotlib 选择器事件

python - 我需要使用 MatPlotLib 在 PyQt4 GUI 中绘制饼图