You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现Matplotlib饼图标签通过箭头指向对应扇区的效果?

在Matplotlib饼图中添加指向扇区的标签箭头

我来帮你搞定这个需求!Matplotlib的pie()函数其实自带了参数可以轻松实现标签带箭头指向对应扇区的效果,主要用到labeldistance、bbox_props和arrowprops这几个参数。下面是修改后的完整代码,直接运行就能得到你想要的效果:

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)

# 关键修改:添加labeldistance、bbox_props和arrowprops参数
wedges, texts, autotexts = ax1.pie(
    sizes,
    explode=None,
    labels=labels,
    autopct='',
    shadow=False,
    startangle=0,
    labeldistance=1.2,  # 让标签远离饼图,留出箭头空间
    bbox_props=dict(boxstyle="square,pad=0.3", fc="white", ec="none"),  # 给标签加白色背景框增强可读性
    arrowprops=dict(arrowstyle="-", color="gray", connectionstyle="angle,angleA=0,angleB=90")  # 设置箭头样式
)

ax1.axis('equal') # 保证饼图绘制为正圆形
plt.savefig('real.png', bbox_inches = 'tight', pad_inches = 0)
plt.show()

关键参数说明:

  • labeldistance=1.2: 控制标签与饼图中心的距离,1.0代表标签刚好在饼图边缘,大于1的数值会将标签移到饼图外部,为箭头留出显示空间。
  • bbox_props: 定义标签的容器样式,这里设置的白色背景框可以让标签文字在任何背景下都更清晰,你可以根据需求调整boxstyle(框体样式)、fc(填充色)和ec(边框色)。
  • arrowprops: 配置箭头的外观,arrowstyle="-"表示使用直线箭头,connectionstyle设置箭头的连接角度,确保箭头精准指向对应扇区的边缘,color则让箭头颜色与饼图线条风格统一。

如果需要调整箭头的长度或角度,你可以修改labeldistance的数值,或者调整connectionstyle中的参数(比如修改angleB的数值)来适配不同的布局需求。

内容的提问来源于stack exchange,提问作者Eissaweb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 13:07:29