在matplotlib饼图/圈图中仅在选定位置绘制标签
我有一个半圆饼图,如下所示:
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize=(8,6),dpi=100)
ax = fig.add_subplot(1,1,1)
pie_labels = ["Label 1", "Label 2", "Label 3"]
pie_values = [1,2,3]
pie_labels.append("Label 0")
pie_values.append(sum(pie_values))
colors = ['red', 'blue', 'green', 'white']
wedges, texts = ax.pie(pie_values, wedgeprops=dict(width=0.35), startangle= -90,colors=colors)
for w,lbl in zip(wedges,pie_labels):
angle = w.theta2
r=w.r-w.width/2
x = r*np.cos(np.deg2rad(angle))
y = r*np.sin(np.deg2rad(angle))
ax.scatter(x,y)
ax.annotate(lbl, xy=(x,y), size=12, color='k',
ha='right', va='center', weight='bold')
这个饼图生成了这样的效果:

我想知道,如何从这个饼图的(x,y)坐标中,遍历它,来只绘制第一个和最后一个标签,或者第一个和第三个标签?我不想创建一个新的标签列表,我只是想获取某些标签的位置。谢谢!
1 个回答
1
你可以把标签放在一个字典里。注意,你所说的“标签0”,实际上是一个最后的隐形部分,用来闭合整个圆圈。通过把你的编号减去 1
,那么键 1
就会对应到 wedges[0]
的开始位置,而键 0
则会对应到 wedges[-1]
(也就是最后一个)。给标签加个空格可以让它看起来更宽松一些。
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize=(8, 6), dpi=100)
ax = fig.add_subplot(1, 1, 1)
pie_labels = {0: "Label 0", 1: "Label 1", 3: "Label 3"}
pie_values = [1, 2, 3]
pie_values.append(sum(pie_values))
colors = ['red', 'blue', 'green', 'none']
wedges, texts = ax.pie(pie_values, wedgeprops=dict(width=0.35), startangle=-90, colors=colors)
for key in pie_labels:
w = wedges[key - 1]
angle = w.theta2
r = w.r - w.width / 2
x = r * np.cos(np.deg2rad(angle))
y = r * np.sin(np.deg2rad(angle))
ax.scatter(x, y, facecolor='gold', edgecolor='black', marker='D')
ax.annotate(pie_labels[key] + " ", xy=(x, y), size=12, color='k',
ha='right', va='center', weight='bold')
plt.show()