matplotlib - Python - Legend overlaps with the pie chart -
using matplotlib in python. legend overlaps pie chart. tried various options "loc" such "best" ,1,2,3... no avail. suggestions how either mention legend position (such giving padding pie chart boundaries) or @ least make sure not overlap?
the short answer is: may use plt.legend
's arguments loc
, bbox_to_anchor
, additionally bbox_transform
, mode
, position legend in axes or figure.
long version:
step 1: making sure legend needed.
in many cases no legend needed @ , information can inferred context or color directly:
if indeed plot cannot live without legend, proceed step 2.
step 2: making sure, pie chart needed.
in many cases pie charts not best way convey information.
if need pie chart unambiguously determined, let's proceed place legend.
placing legend
plt.legend()
has 2 main arguments determine position of legend. important , in sufficient loc
argument.
e.g. plt.legend(loc="upper left")
placed legend such sits in upper left corner of bounding box. if no further argument specified, bounding box entire axes.
however, may specify our own bounding box using bbox_to_anchor
argument. if bbox_to_anchor
given 2-tuple e.g. bbox_to_anchor=(1,1)
means bounding box located @ upper right corner of axes , has no extent. acts point relative legend placed according loc
argument. expand out of zero-size bounding box. e.g. if loc
"upper left"
, upper left corner of legend @ position (1,1) , legend expand right , downwards.
this concept used above plot, tells shocking truth bias in miss universe elections.
import matplotlib.pyplot plt import matplotlib.patches total = [100] labels = ["earth", "mercury", "venus", "mars", "jupiter", "saturn", "uranus", "neptune", "pluto *"] plt.title('origin of miss universe since 1952') plt.gca().axis("equal") pie = plt.pie(total, startangle=90, colors=[plt.cm.set3(0)], wedgeprops = { 'linewidth': 2, "edgecolor" :"k" }) handles = [] i, l in enumerate(labels): handles.append(matplotlib.patches.patch(color=plt.cm.set3((i)/8.), label=l)) plt.legend(handles,labels, bbox_to_anchor=(0.85,1.025), loc="upper left") plt.gcf().text(0.93,0.04,"* out of competition since 2006", ha="right") plt.subplots_adjust(left=0.1, bottom=0.1, right=0.75)
in order legend not exceed figure, use plt.subplots_adjust
obtain more space between figure edge , axis, can taken legend.
there option use 4-tuple bbox_to_anchor
. how use or interprete detailed in question: what 4-element tuple argument 'bbox_to_anchor' mean in matplotlib?
, 1 may use mode="expand"
argument make legend fit specified bounding box.
there useful alternatives approach:
using figure coordinates
instead of specifying legend position in axes coordinates, 1 may use figure coordinates. advantage allow place legend in 1 corner of figure without adjusting of rest. end, 1 use bbox_transform
argument , supply figure transformation it. coordinates given bbox_to_anchor
interpreted figure coordinates.
plt.legend(pie[0],labels, bbox_to_anchor=(1,0), loc="lower right", bbox_transform=plt.gcf().transfigure)
here (1,0)
lower right corner of figure. because of default spacings between axes , figure edge, suffices place legend such not overlap pie.
in other cases, 1 might still need adapt spacings such no overlap seen, e.g.
title = plt.title('what slows down computer') title.set_ha("left") plt.gca().axis("equal") pie = plt.pie(total, startangle=0) labels=["trojans", "viruses", "too many open tabs", "the anti-virus software"] plt.legend(pie[0],labels, bbox_to_anchor=(1,0.5), loc="center right", fontsize=10, bbox_transform=plt.gcf().transfigure) plt.subplots_adjust(left=0.0, bottom=0.1, right=0.45)
saving file bbox_inches="tight"
now there may cases more interested in saved figure @ shown on screen. may position legend @ edge of figure, so
but save using bbox_inches="tight"
savefig
,
plt.savefig("output.png", bbox_inches="tight")
this create larger figure, sits tight around contents of canvas:
a sophisticated approach, allows place legend tightly inside figure, without changing figure size presented here: creating figure exact size , no padding (and legend outside axes)
using subplots
an alternative use subplots reserve space legend. in case 1 subplot take pie chart, subplot contain legend. shown below.
fig = plt.figure(4, figsize=(3,3)) ax = fig.add_subplot(211) total = [4,3,2,81] labels = ["tough working conditions", "high risk of accident", "harsh weather", "it's not allowed watch dvds"] ax.set_title('what people know oil rigs') ax.axis("equal") pie = ax.pie(total, startangle=0) ax2 = fig.add_subplot(212) ax2.axis("off") ax2.legend(pie[0],labels, loc="center")
Comments
Post a Comment