Matplotlib饼图标签的中心对齐 [英] Matplotlib center alignment for pie chart labels

查看:537
本文介绍了Matplotlib饼图标签的中心对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Matplotlib在Python中制作了一个非常简单的饼图,我想编辑标签的对齐方式.我在标签中使用了\n来分隔行,因为标签对于一行来说太长了.但是,正如您从名为饼图图像"的图片中所看到的那样,此刻混合了各种奇怪的对齐方式.我真的很想让它居中对齐.

I have produced a very simple pie chart in Python using Matplotlib and I am wanting to edit the alignment of my labels. I have used \n within my labels to split the line as the labels are too long for one line. But as you can see from the picture called 'pie chart image', it's a mix of weird alignments at the moment. I would really like to have it center alignment.

对于Matplotlib中的其他图表/图形类型,有一个名为align的参数,您可以在其中将其设置为center,但是,plt.pie(...)似乎没有此属性.

For other chart/graph types in Matplotlib there is an argument called align where you can set it to center, however, plt.pie(...) does not seem to have this attribute.

这是我的代码:

import matplotlib.pyplot as plt
k = [7,15]
labels = 'Strongly and Mostly \n Agree', 'Strongly/Mostly Disagree \n  and In the Middle'
plt.pie(k, labels= labels)
plt.show()

有什么想法吗?

推荐答案

您可以通过textprops参数将文本属性的字典传递给plt.pie.例如:

You can pass a dictionary of text properties to plt.pie via the textprops argument. For example:

plt.pie(k, labels=labels, textprops={'weight': 'bold'})

但是,如果尝试指定horizontalalignment属性,则会收到一条错误消息,提示您两次提供了该参数.显然,没有,但是matplotlib将它的硬编码值和您的值都传递给了一些内部函数.

However, if you try to specify the horizontalalignment property, you'll get an error saying that you provided that parameter twice. Obviously you didn't, but matplotlib passed both it's hard-coded value and your value to some internal function.

但这可能是一件好事.从我的角度来看,没有太多的对齐方式,而是文本与饼图的一致对齐方式.

But that's probably a good thing. The way I see it, there's not so much a mix of alignments, but a consistent alignment of the text against the pie.

pie返回每个楔形的色标和标签.因此,您可以在初次调用pie后修改标签的对齐方式,从而遍历标签.看起来像这样:

pie returns both the patches and the labels for each wedge. So you can loop through the labels after your initial call to pie to modify their alignment. That looks like this:

k = [7, 15]
labels = 'Strongly and Mostly\nAgree', 'Strongly/Mostly Disagree\nand In the Middle'
fig, ax = plt.subplots()
ax.set_aspect('equal')
wedges, labels = ax.pie(k, labels=labels, textprops={'weight': 'bold'})
for label in labels:
    label.set_horizontalalignment('center')

如您所见,标签现在与楔形重叠,从而降低了清晰度.

As you can see, the labels now overlap with the wedges, diminishing legibility.

标签还具有set_position方法(即label.set_position((x, y))),但是重新计算饼图中 N 标签的位置听起来对我来说就像是一段糟糕的时光.

The labels also have a set_position method (i.e., label.set_position((x, y))), but recomputing the positions for N labels in a pie chart sounds like a Bad Time to me.

这篇关于Matplotlib饼图标签的中心对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆