切片很小时避免重叠

时间:2020-08-25 20:09:16

标签: python pandas matplotlib

我想知道我可以在饼图中添加标注。 我有这个数据集:

       ID   Colour
0   27995   red
1   36185   orange
2   57204   blue
3   46009   red
4   36241   white
5   63286   blue
6   68905   blue
7   3798    green
8   53861   yellow
...
199 193 brown

当我尝试使用熊猫生成饼图时:

df.groupby(Colour).size().plot(kind='pie',figsize=(15,15), label="", labeldistance=0.8, autopct='%1.0f%%',  pctdistance=0.5,legend=True)

我得到一个可怕的图表,其中的颜色重叠,因为切片非常小,百分比值也重叠。 我知道按以下方式管理图表可能会更容易:

How to avoid overlapping of labels & autopct in a matplotlib pie chart?

但是我无法使用答案中的代码。

您能告诉我该答案中建议的代码中应该更改什么吗?

1 个答案:

答案 0 :(得分:1)

微调在'matplotlib'中更易于处理。我以官方参考资料为例来修改您的数据。来自here。点是explode=(),它设置要从元组中切出的切片的数量。

import matplotlib.pyplot as plt

colours = ['red', 'orange', 'blue', 'white', 'green', 'yellow', 'brown']

labels = colours
sizes = df.groupby('Colour').size().tolist()
# only "explode" the 3nd,4th slice (i.e. 'Blue, White')
explode = (0, 0, 0.2, 0.2, 0, 0, 0)

fig1, ax1 = plt.subplots()
ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True, startangle=90, colors=colours)

# Equal aspect ratio ensures that pie is drawn as a circle.
ax1.axis('equal')  

plt.show()

enter image description here