python-2.7 - Python PieChart(是否可以做CallOut标签)

标签 python-2.7 matplotlib

有没有用 Python、Matplotlib 等做 CallOut Labels 的例子

enter image description here
Image source

上面有一条线,标签从饼图外部指向……看不到任何可能的例子,它用 Mathplotlib 完成……这可以用 Python 完成吗??

最佳答案

您可以使用 matplotlib annotations 创建文本标签和注释线。
手动贴标
这是一个示例,其中标签在数据坐标中手动定位,即饼图的中心是 (0,0) 坐标。

import matplotlib.pyplot as plt 

fig, ax= plt.subplots(figsize=(4,4))
plt.subplots_adjust(bottom=0.3)
total = [13,87]
plt.title('How to spot intellectuals on TV')
plt.gca().axis("equal")
pie = plt.pie(total, startangle=93)
labels = ["1. They say sophisticated things", "2. They sit in front of a bookshelf"]

bbox_props = dict(boxstyle="square,pad=0.3", fc="w", ec="k", lw=0.72)
arrowprops=dict(arrowstyle="-",connectionstyle="angle,angleA=0,angleB=90")
kw = dict(xycoords='data',textcoords='data',
          arrowprops=arrowprops, bbox=bbox_props, zorder=0)
plt.gca().annotate("2", xy=(0, 0), xytext=( 1.1, -0.8), **kw )
plt.gca().annotate("1", xy=(0, 0), xytext=(-1.1,  0.8), **kw )

plt.legend(pie[0],labels, loc="center", bbox_to_anchor=(0.5,-0.1))
plt.show()
enter image description here
自动贴标:
我们可以使用楔子的角度在合适的位置自动创建标签。
import matplotlib.pyplot as plt
import numpy as np 

fig, ax= plt.subplots(figsize=(4,4))
plt.subplots_adjust(bottom=0.3)
total = [12,15,12,13,16]
plt.title('My repair strategies')
plt.gca().axis("equal")
patches, texts = pie = plt.pie(total, startangle=5)
labels = ["1. roaring at it", 
          "2. hitting it",
          "3. using superglue",
          "4. using duct tape",
          "5. dismantling it, then ditch it"]

bbox_props = dict(boxstyle="square,pad=0.3", fc="w", ec="k", lw=0.72)
arrowprops=dict(arrowstyle="-",connectionstyle="angle,angleA=0,angleB=90")
kw = dict(xycoords='data',textcoords='data',arrowprops=arrowprops, 
          bbox=bbox_props, zorder=0, va="center")

for i, p in enumerate(patches):
    ang = (p.theta2 - p.theta1)/2.+p.theta1
    y = np.sin(ang/180.*np.pi)
    x = 1.35*np.sign(np.cos(ang/180.*np.pi))
    plt.gca().annotate(str(1+i), xy=(0, 0), xytext=( x, y), **kw )

plt.legend(pie[0],labels, loc="center", bbox_to_anchor=(0.5,-0.2))
plt.show()
enter image description here

关于python-2.7 - Python PieChart(是否可以做CallOut标签),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43349004/

相关文章:

python - 如何在同一绘图上对多个字典进行箱线图

python - xticks 的 matplotlib 自定义顺序

python - 如何使用文件中的随机代理/UA 制作 annonimizer?

python - numpy 取很多样本而不按行替换

python - Matplotlib:通过乘以常数来缩放轴

python - 迭代图中的标记

python - 列表理解在 Python2 : how making it be compatible with Python3 中泄漏了它们的循环变量

python - 如何使用 scikit-learn 加载文件并处理 .txt 文件?

python - 旋转图像后获取(x,y)点(python,openCV)

python - ipywidgets:使用交互时避免闪烁