简体   繁体   English

Matplotlib:饼图中的标签重叠

[英]Matplotlib: Overlapping labels in pie chart

I have to make a piechart for the following data:我必须为以下数据制作饼图:

在此处输入图像描述

However, because the larger numbers are in the hundreds while the smaller numbers are lesser than 1, the labels for the graph end up illegible due to overlapping.但是,由于较大的数字以数百为单位,而较小的数字小于 1,因此图形的标签由于重叠而变得难以辨认。 For example, this is the graph for Singapore:例如,这是新加坡的图表:

在此处输入图像描述

I have tried decreasing the font size and increasing the graph size but because it overlaps so much, doing so doesn't really help at all.我试过减小字体大小并增加图形大小,但因为重叠太多,所以这样做根本没有帮助。 Here are the necessary codes for my graph:以下是我的图表的必要代码:

import matplotlib.pyplot as plt
plt.pie(consumption["Singapore"], labels = consumption.index)
fig = plt.gcf()
fig.set_size_inches(8,8)
ax = plt.gca()
handles, labels = ax.get_legend_handles_labels()
labels, handles = zip(*sorted(zip(labels, handles), key=lambda t: t[0], reverse=True))
plt.show()

Is there any way to solve this issue?有什么办法可以解决这个问题吗?

The problem of overlapping label characters cannot be completely solved by programming. label个字符重叠的问题不能完全靠编程来解决。 If you're dealing with your challenges only, first group them to aggregate the number of labels.如果您只处理挑战,请先将它们分组以汇总标签数量。 The grouped data frames are targeted for the pie chart.分组的数据框针对饼图。 However, it still overlaps, so get the current label position and change the position of the overlapping label.但是还是重叠了,所以得到当前的label position 把重叠的label换成position。

new_df = consumption.groupby('Singapore')['Entity'].apply(list).reset_index()
new_df['Entity'] = new_df['Entity'].apply(lambda x: ','.join(x)) 
new_df

    Singapore   Entity
0   0.000000    Biofuels,Wind,Hydro,Nuclear
1   0.679398    Other
2   0.728067    Solar
3   5.463305    Coal
4   125.983605  Gas
5   815.027694  Oil

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(8,8))

wedges, texts = ax.pie(new_df["Singapore"], wedgeprops=dict(width=0.5), startangle=0, labels=new_df.Entity)
# print(wedges, texts)

texts[0].set_position((1.1,0.0))
texts[1].set_position((1.95,0.0))
texts[2].set_position((2.15,0.0))

plt.legend()

plt.show()

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM