我一直在用 Matplotlib 绘制一些图表,我有一个饼图,想要在图表周围绘制箭头,使每个标签都指向图表,我有一个示例:
这是我当前的代码:
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()
当前代码生成此图表:
如何实现上述(第一个)图像结果?
最佳答案
您可以使用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()
关于python - 如何在 Matplotlib 饼图周围绘制箭头以将每个标签指向圆圈中各自的部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67023749/