python - 更改 Matplotlib 饼图标签的位置
问题描述
我有一个简单的饼图,其中显示了每个切片的百分比和标签。百分比标记和标签位于每个饼图的中间,但我希望将这两个移动到切片的不同部分,如下图所示,这样所有标签都在左侧图。
有没有办法做到这一点?
import matplotlib.pyplot as plt
plt.rcParams.update({'font.size': 12})
labels = 'A', 'B', 'C'
sizes = [5, 20, 75]
explode = (0.1, 0, 0)
fig1, ax1 = plt.subplots()
ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True, startangle=90)
ax1.axis('equal')
plt.tight_layout()
plt.savefig('test.png')
plt.show()
解决方案
这实际上很容易。按着这些次序:
1 - 从 ax1.pie 中删除标签参数。就这样吧:ax1.pie(sizes, explode=explode autopct='%1.1f%%', shadow=True, startangle=90)
2 - 在 ax1.axis("equal") 行之后添加 plt.legend()。
3 - 将您的标签作为参数传递给 plt.legend(),即 plt.legend(labels)。
4 - 如果您仍然对图例的位置不满意,您可以再操作一个参数,即 bbox_to_anchor。
5 - 将 bbox_to_anchor 作为第二个参数传递给 plt.legend() 并以元组的形式给它两个数字,例如:bbox_to_anchor = (2, 3)。玩弄它,直到它出现在您想要的位置。