python饼状图添加引导线
时间: 2023-07-05 12:35:41 浏览: 587
要在Python中的饼图中添加引导线,可以使用matplotlib库中的annotate()函数。下面是一个简单的例子:
```python
import matplotlib.pyplot as plt
# 数据
labels = ['A', 'B', 'C', 'D']
sizes = [20, 30, 25, 25]
colors = ['red', 'green', 'blue', 'yellow']
# 绘制饼图
plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%')
# 添加引导线
for i, label in enumerate(labels):
angle = sum(sizes[:i+1]) * 360.0 / sum(sizes)
if angle > 180:
angle = angle - 360
x = 1.1 * plt.pie([1], colors=[colors[i]], radius=1.0, startangle=angle, autopct='%1.1f%%')[0].center[0]
y = 1.1 * plt.pie([1], colors=[colors[i]], radius=1.0, startangle=angle, autopct='%1.1f%%')[0].center[1]
plt.annotate(label, xy=(x, y), xytext=(1.2 * x, 1.2 * y),
arrowprops=dict(facecolor='black', shrink=0.05))
# 显示图形
plt.show()
```
这个代码可以绘制一个简单的饼图,并在每个扇形上添加引导线和标签。注意,这里的引导线是通过matplotlib的annotate()函数绘制的,箭头和标签可以根据需要进行调整。
阅读全文
相关推荐











