[英]Remove labels but keep legend in a pie chart
You can remove the labels
argument from the pie and add it to the legend.您可以从饼图中删除labels
参数并将其添加到图例中。 Instead of而不是
plt.pie(x,labels=labels)
plt.legend()
use使用
plt.pie(x)
plt.legend(labels=labels)
Complete example:完整示例:
import matplotlib.pyplot as plt
x = [15, 30, 55]
labels = [1, 2, 3]
plt.figure(figsize=(3, 3), dpi=72)
plt.pie(x)
plt.legend(labels=labels)
plt.show()
As an alternative to IMCoins' answer , which is the best way to proceed, you could also keep your current code, but delete the labels from the pie chart.作为IMCoins 答案的替代方案,这是进行的最佳方式,您也可以保留当前代码,但从饼图中删除标签。
x = [15, 30, 55]
labels = [1, 2, 3]
plt.figure(figsize=(3, 3), dpi=72)
patches, texts = plt.pie(x, labels=labels)
plt.legend()
for t in texts:
t.remove()
If I were you, I'd create a custom legend, instead of letting matplotlib creating its own automatic one.如果我是你,我会创建一个自定义图例,而不是让 matplotlib 创建自己的自动图例。 You are now asking matplotlib to plot the labels using labels=labels
in plt.pie()
.您现在要求 matplotlib 在plt.pie()
使用labels=labels
绘制标签。
import matplotlib.pyplot as plt
x = [15, 30, 55]
labels = [1, 2, 3]
colors = ['blue', 'red', 'grey']
plt.figure(figsize=(3, 3), dpi=72)
patches, texts = plt.pie(x, colors=colors)
plt.legend(patches, labels)
plt.show()
# plt.savefig('pie_1.png')
A very simple way is to set the label distance to None , as suggested in the matlplotlib.pyplot.pie documentation.一个非常简单的方法是将标签距离设置为None ,如 matlplotlib.pyplot.pie 文档中所建议的。
This worked very well in my case.这在我的情况下非常有效。
import matplotlib.pyplot as plt
x = [15, 30, 55]
labels = [1, 2, 3]
plt.figure(figsize=(3, 3), dpi=72)
plt.pie(x, labels=labels, labeldistance=None)
plt.legend()
plt.savefig('pie_1.png')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.