python中的饼图

问题描述 投票:1回答:2

我想用python做一个饼图,但是所有的标签都是重叠的。有什么办法可以保证它们在饼图中但不重叠?

下面是我的代码

import matplotlib.pyplot as plt

labels = ['Cropland', 'Forest', 'Cloud', 'Shadow', 'Water', 'Grassland', 'Bare ground']
sizes = [1737019, 105209472, 5210012, 4638330, 148082,1276550, 2340935]
colors = ['tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple', 'tab:brown', 'tab:pink']
patches, texts = plt.pie(sizes, colors=colors, shadow=False, startangle=90)
plt.pie(sizes, labels=labels, autopct='%1.0f%%', pctdistance=1.4, labeldistance=1.8)
plt.legend(patches, labels, loc="lower left")
plt.axis('equal')
plt.tight_layout()
plt.savefig('LULC_20200425.png', bbox_inches='tight', dpi=600)
plt.show()

enter image description here

python matplotlib pie-chart
2个回答
1
投票

减少和旋转标签。

import matplotlib.pyplot as plt

plt.figure(dpi=150)
labels = ['Cropland', 'Forest', 'Cloud', 'Shadow', 'Water', 'Grassland', 'Bare ground']
sizes = [1737019, 105209472, 5210012, 4638330, 148082,1276550, 2340935]

colors = ['tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple', 'tab:brown', 'tab:pink']

patches, texts = plt.pie(sizes, colors=colors, shadow=False, startangle=90,textprops={'fontsize': 8})
plt.pie(sizes, labels=labels, autopct='%1.0f%%', pctdistance=1.15, labeldistance=0.50,rotatelabels = True, textprops = dict(rotation_mode = 'anchor', va='center', ha='left', fontsize=8))

plt.legend(patches, labels, loc="lower left")
plt.axis('equal')
plt.tight_layout()
plt.show()

enter image description here


2
投票

你可以旋转标签,以减少重叠,也可以使用更大的数字。

fig = plt.figure(figsize=(6,6))

labels = ['Cropland', 'Forest', 'Cloud', 'Shadow', 'Water', 'Grassland', 'Bare ground']
sizes = [1737019, 105209472, 5210012, 4638330, 148082,1276550, 2340935]
colors = ['tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple', 'tab:brown', 'tab:pink']
patches, texts = plt.pie(sizes, colors=colors, shadow=False, startangle=90)
plt.pie(sizes, labels=labels, autopct='%1.0f%%', pctdistance=1.1, labeldistance=0.65, rotatelabels =True,
       textprops = dict(rotation_mode = 'anchor', va='center', ha='left'),)
plt.legend(patches, labels, loc="lower left")
plt.axis('equal')
plt.tight_layout()

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.