python - Matplotlib donut 标签/注释位置

标签 python matplotlib

我正在尝试重新创建此圆环图的这种确切样式,但我不知道如何将标签/注释调整到同一位置并加下划线。

enter image description here

我在网上找到了一个注释程序示例,但我对它的理解还不够,无法进行必要的调整。

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

labels= 'x', 'y'

data = [1266.97, 746.79 ]  

wedges, texts = ax.pie(data, wedgeprops=dict(width=0.5), startangle=225)

kw = dict(arrowprops=dict(arrowstyle="-"),
           zorder=0, va="center")

for i, p in enumerate(wedges):
    ang = (p.theta2 - p.theta1)/2. + p.theta1
    y = np.sin(np.deg2rad(ang))
    x = np.cos(np.deg2rad(ang))
    horizontalalignment = {-1: "right", 1: "left"}[int(np.sign(x))]
    connectionstyle = "angle,angleA=0,angleB={}".format(ang)
    kw["arrowprops"].update({"connectionstyle": connectionstyle})
    ax.annotate(data[i], xy=(x, y), xytext=(1.35*np.sign(x), 1.4*y),
                horizontalalignment=horizontalalignment,  **kw)

ax.set_title("title")

plt.show()

上面的代码创建了下面的 donut ,但我不知道如何调整我的标签线来匹配上面的例子。

enter image description here

最佳答案

您正在使用这些行确定标签的位置:

y = np.sin(np.deg2rad(ang))
x = np.cos(np.deg2rad(ang))

您可以像这样手动设置文本的位置:

annotation_postions = [(-.5, .5), (.5, .5)]
for i, p in enumerate(wedges):
    ang = (p.theta2 - p.theta1) / 2. + p.theta1
    print(i)
    y = annotation_postions[i][1]
    x = annotation_postions[i][0]
    horizontalalignment = {-1: "right", 1: "left"}[int(np.sign(x))]
    connectionstyle = "angle,angleA=0,angleB={}".format(ang)
    kw["arrowprops"].update({"connectionstyle": connectionstyle})
    ax.annotate(data[i], xy=(x, y), xytext=(3*x, 1 * y),
                horizontalalignment=horizontalalignment, **kw)

xy 是图表上线条的起点。

xytext 是文字所在的地方

下划线只是在文本下方延伸的线。你必须研究如何让它更长并将文本放在上面。

关于python - Matplotlib donut 标签/注释位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57332067/

相关文章:

python - 语法错误 : encoding declaration in Unicode string

python - 无法将标准输出复制到 python 中的文件

python - matplotlib 子图未显示

python - 使用 matplotlib 显示六边形网格

Python:如何将对象从基类提升为派生类?

python - 默认和非默认参数的顺序

蟒轮 : "ModuleNotFoundError" after installing package

python - pyqt4的scrollArea事件和matplotlib的wheelEvent

python-3.x - python 3 散点图给出 "ValueError: Masked arrays must be 1-D"即使我没有使用任何掩码数组

python-2.7 - 绘制大型 NetworkX 图表时返回进度状态