【问题标题】:Avoiding overlapping when slices are tiny当切片很小时避免重叠
【发布时间】:2020-08-26 12:22:06
【问题描述】:

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

       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

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

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?

但在我的情况下,我无法使用答案中的代码。

你能告诉我我应该在那个答案中建议的代码中改变什么吗?

【问题讨论】:

  • plt.legend(patches, labels, loc='center right', bbox_to_anchor=(-0.1, 1.), fontsize=8)中使用loc='center right'
  • 请添加更多详细信息,为什么它不适合您?
  • 如果您认为另一个答案是您想要的,那么您只需要在您的案例中定义 x、y 和颜色。尝试s = df.groupby(Colour).size() 然后x = s.indexy = s.valuescolor = x,那么它应该可以工作吗?
  • @Ben。 T. 当我收到(red, None) 时,我遇到了color = x 的一些问题。
  • @Pygirl,我不知道在我的情况下 x 和 y 是什么字段。

标签: python pandas matplotlib


【解决方案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()

【讨论】:

  • 感谢@r-beginners。我收到此错误:ValueError:“explode”的长度必须为“x”。你知道我该如何解决吗?
  • 这个错误可能是饼图中的元素个数和explode=()的元素个数不一样。
猜你喜欢
  • 2020-01-30
  • 1970-01-01
  • 2014-07-02
  • 1970-01-01
  • 2018-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-13
相关资源
最近更新 更多