python扇形图标签太密集_Matplotlib饼图标签的中心对齐

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.

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.

Here is my code:

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()

Any ideas?

解决方案

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'})

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.

Back to your question

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.

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值