Matplotlib将标签移到饼图中间

2024-10-01 09:20:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经让我的饼图工作,但我注意到实际图表的文本框似乎不能正常工作。他们只是聚集在一起,所以我想知道有没有办法让我把标签移到中间的白色圆圈,并在旁边有匹配的颜色吗?在

crimeTypes = dict(crimeData["Crime type"].value_counts())

crimeType = []
totalAmount = []
numberOfCrimes = 14

for key in sorted(crimeTypes, key=crimeTypes.get, reverse=True):
    crimeType.append(key)
    totalAmount.append(crimeTypes.get(key))

crimeType_sample = crimeType[0:numberOfCrimes]
totalAmount_sample = totalAmount[0:numberOfCrimes]

fig1, ax1 = plt.subplots()
ax1.pie(totalAmount_sample, labels=crimeType_sample, autopct='%1.1f%%', shadow=False, startangle=90)
ax1.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.
fig1 = plt.gcf()
fig1.set_size_inches(10,10)
circle = plt.Circle(xy=(0,0), radius=0.75, facecolor='white')
plt.gca().add_artist(circle)
plt.show();

enter image description here


Tags: samplekeyget图表plt文本框piecircle
1条回答
网友
1楼 · 发布于 2024-10-01 09:20:52

下面是一些示例数据以重现您的问题:

样本数据:

import pandas as pd

data = (['Burglary']*50 + ['Arson', 'Theft', 'Violence'] + ['Drugs']*10 + ['Other'] + 
        ['Shoplifting']*4 + ['Harassment']*17 + ['Murder', 'Vehicle Crime']*3 + 
        ['Some other Crimes']*12 + ['Even More Crime', 'And Crime', 'And More Crime']*10)
crimeData = pd.DataFrame(data, columns=['Crime type'])

这将导致以下情节:

enter image description here


使用图例

打印时不要打印百分比或标签,然后创建一个放在旁边的图例:

^{pr2}$

enter image description here

旋转标签:

创建标签并使用rotatelabels=True。尽管在很多情况下,这可能仍然显得局促。在

^{3}$

enter image description here

相关问题 更多 >