Issue
I want to display two pie-charts, well donut charts, side by side. But using the code below all I'm getting is overlapping graphs. I've tried using various values for subplot adjust but the legends always end up overlapping. Chopped out all the non relevant code in the function
#Function to draw graphs for sports data
#Create figure with two subplots
fig,ax=plt.subplots(1,2,subplot_kw=dict(aspect="equal"))
j=0
#Loop through all columns we want to graph
for type in types:
#Create a pie chart
wedges, texts, autotexts = ax[j].pie(to_plot,
explode=explode,
labels=labels,
colors=colors,
autopct=lambda pct: func(pct, data),
pctdistance=0.8,
counterclock=False,
startangle=90,
wedgeprops={'width': 0.75},
radius=1.75
)
#Set label colors
for text in texts:
text.set_color('grey')
#Create legend
ax[j].legend(wedges, leg_labels,
title=title,
title_fontsize="x-large",
loc="center left",
bbox_to_anchor=(1.5, 0, 0.5, 1),
prop={'size': 12})
j += 1
plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0.5, hspace=None)
plt.show()
return
Solution
The bbox setting that determines the position of the legend is set to the right of each pie chart, so they overlap. Therefore, we can avoid overlapping the legends by setting the respective positions for the graphs.
import matplotlib.pyplot as plt
# Some data
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
fracs = [15, 30, 45, 10]
titles = ['20 members\nfollow Basketball','23 members\nfollow Basketball']
legend_pos = ['center left','center right']
bboxes = [(-1.0, 0, 0.5, 1),(1.5, 0, 0.5, 1)]
# Make figure and axes
fig, axs = plt.subplots(1, 2, subplot_kw=dict(aspect="equal"))
for i in range(2):
wedges, texts,_ = axs[i].pie(fracs,
labels=labels,
autopct='%.0f%%',
shadow=True,
explode=(0, 0.1, 0, 0),
wedgeprops=dict(width=0.6))
axs[i].legend(wedges,
labels,
title=titles[i],
title_fontsize="x-large",
loc=legend_pos[i],
bbox_to_anchor=bboxes[i],
prop={'size': 12})
plt.show()
Answered By - r-beginners
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.