Home > Back-end >  Matplotlib: Overlapping labels in pie chart
Matplotlib: Overlapping labels in pie chart

Time:04-06

I have to make a piechart for the following data:

enter image description here

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. For example, this is the graph for Singapore:

enter image description here

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?

CodePudding user response:

The problem of overlapping label characters cannot be completely solved by programming. 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.

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()

enter image description here

  • Related