我正在尝试重新创建此圆环图的这种确切样式,但我不知道如何将标签/注释调整到同一位置并加下划线。
我在网上找到了一个注释程序示例,但我对它的理解还不够,无法进行必要的调整。
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 ,但我不知道如何调整我的标签线来匹配上面的例子。
最佳答案
您正在使用这些行确定标签的位置:
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/