Python - Legend overlaps with the pie chart - python

Using matplotlib in python. The legend overlaps with my pie chart. Tried various options for "loc" such as "best" ,1,2,3... but to no avail. Any Suggestions as to how to either exactly mention the legend position (such as giving padding from the pie chart boundaries) or at least make sure that it does not overlap?

The short answer is: You may use plt.legend's arguments loc, bbox_to_anchor and additionally bbox_transform and mode, to position the legend in an axes or figure.
The long version:
Step 1: Making sure a legend is needed.
In many cases no legend is needed at all and the information can be inferred by the context or the color directly:
If indeed the plot cannot live without a legend, proceed to step 2.
Step 2: Making sure, a pie chart is needed.
In many cases pie charts are not the best way to convey information.
If the need for a pie chart is unambiguously determined, let's proceed to place the legend.
Placing the legend
plt.legend() has two main arguments to determine the position of the legend. The most important and in itself sufficient is the loc argument.
E.g. plt.legend(loc="upper left") placed the legend such that it sits in the upper left corner of its bounding box. If no further argument is specified, this bounding box will be the entire axes.
However, we may specify our own bounding box using the bbox_to_anchor argument. If bbox_to_anchor is given a 2-tuple e.g. bbox_to_anchor=(1,1) it means that the bounding box is located at the upper right corner of the axes and has no extent. It then acts as a point relative to which the legend will be placed according to the loc argument. It will then expand out of the zero-size bounding box. E.g. if loc is "upper left", the upper left corner of the legend is at position (1,1) and the legend will expand to the right and downwards.
This concept is used for the above plot, which tells us the shocking truth about the bias in Miss Universe elections.
import matplotlib.pyplot as 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 = []
for 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 for the legend not to exceed the figure, we use plt.subplots_adjust to obtain more space between the figure edge and the axis, which can then be taken up by the legend.
There is also the option to use a 4-tuple to bbox_to_anchor. How to use or interprete this is detailed in this question: What does a 4-element tuple argument for 'bbox_to_anchor' mean in matplotlib?
and one may then use the mode="expand" argument to make the legend fit into the specified bounding box.
There are some useful alternatives to this approach:
Using figure coordinates
Instead of specifying the legend position in axes coordinates, one may use figure coordinates. The advantage is that this will allow to simply place the legend in one corner of the figure without adjusting much of the rest. To this end, one would use the bbox_transform argument and supply the figure transformation to it. The coordinates given to bbox_to_anchor are then interpreted as figure coordinates.
plt.legend(pie[0],labels, bbox_to_anchor=(1,0), loc="lower right",
bbox_transform=plt.gcf().transFigure)
Here (1,0) is the lower right corner of the figure. Because of the default spacings between axes and figure edge, this suffices to place the legend such that it does not overlap with the pie.
In other cases, one might still need to adapt those spacings such that no overlap is seen, e.g.
title = plt.title('What slows down my 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 the file with bbox_inches="tight"
Now there may be cases where we are more interested in the saved figure than at what is shown on the screen. We may then simply position the legend at the edge of the figure, like so
but then save it using the bbox_inches="tight" to savefig,
plt.savefig("output.png", bbox_inches="tight")
This will create a larger figure, which sits tight around the contents of the canvas:
A sophisticated approach, which allows to place the legend tightly inside the figure, without changing the figure size is presented here:
Creating figure with exact size and no padding (and legend outside the axes)
Using Subplots
An alternative is to use subplots to reserve space for the legend. In this case one subplot could take the pie chart, another subplot would contain the legend. This is 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 to watch DVDs"]
ax.set_title('What people know about 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")

Related

Cannot position plotly legend outside plot borders

I have a plotly graph that uses the Dash library to manipulate the x-values on the plot for simple comparison. When x values, in this case countries, is greater than 1, the legend is properly positioned outside of the graph. However, when there is only one country on the plot, the legend covers half of the plot.
I have tried: setting the legend x attribute to 3, x anchor to right, and changing the graph margin to add padding. I haven't found a solution that works.
Below is the section of the code that updates the plotly fig.
window_width = 1500
fig = px.bar(data_frame=dfi5.loc[(value_country)], width=(window_width / 4) * len(value_country))
fig.update_xaxes(showticklabels=True, title='')
fig.update_yaxes(showticklabels=True, title='Percent of Respondents')
fig.update_layout(autosize=False, title_text='Favorite K-Drama by Country', title_x=.46, title_font_size=20,
legend_title_text='Drama Title', margin_r=1, legend_xanchor='right', legend_x=3, legend_itemsizing='constant')
Update: I was able to find a workaround by reducing the legend font size, which reduces the area of the legend. I would be interested to learn if there is a way to explicitly set the location of the legend. The issue seems to occur when the legend area is wider than the plot area.

How to change the catplot bar positions

I'm having trouble with the location of the bars on the scale. I understand it to be that some of the hue amounts are 0, so this is throwing off the position of the bars. In the image, the top right plot shows the green and brown bars for 'labour' with a gap between, presumably because that color is 0. Is there a way to put the bars together, and in line with their correspondence on the y-axis?
grid = sns.catplot(x='Type', y='count',
row='Age', col='Gender',
hue='Nationality',
data=dfNorthumbria2, kind='bar', ci=None,legend=True)
grid.set(ylim=(0,5), yticks=[0,1,2,3,4,5])
grid.set(xlabel="Type of Exploitation",ylabel="Total Referrals")
for ax in grid.axes.flatten():
ax.tick_params(labelbottom=True, rotation=90)
ax.tick_params(labelleft=True)
grid.fig.tight_layout()
leg = grid._legend
leg.set_bbox_to_anchor([1.1,0.5])
You can pass a hue_order argument to sns.barplot() via sns.catplot, e.g.
grid = sns.catplot(..., hue_order=['British', 'Romanian', 'Vietnamese',
'Albanian', 'Pakistani', 'Slovak'])
This should close the gap between the green and brown bars, and they will be centered at the tick mark, as they are now in the middle of the list. However, groups of other bars will still not be centered around their tick mark.
This may be an unavoidable consequence of how this plotting function works, it's not designed for such sparse data. So if you want all the different groups of bars to be centered at their respective tick marks, you may have to use a more flexible matplotlib plotting function and create the color subsets manually.

How can I fix the space between a plot and legend so that new text doesn't change the spacing?

To be more specific, How can I fix the space between a plot and legend such that if more text is included the legend won't overlap the plot?
For example, if you look at the plots below, when I add more text from "back now"(Plot 1) to "let's break hu"(Plot 2) in the first legend entry -- the legend extends to the left where it begins to cover the plot.
Is there a way to keep the space between the plot and the legend fixed? So that when there is more text the figure extends to the right rather than onto the plot itself.
Plot 1, Plot 2
Code used for the legend:
lgd = ax.legend( patches, lgnd, loc="center right", bbox_to_anchor=(1.25, 0.5), prop=font )
Part of the answer you're looking for depends on how you made the legend and placed them in the first place. That's why people emphasize "Minimal, Complete, and Verifiable example".
To give you a simple introduction, you can control legend location using bbox_to_anchor, which accepts tuple of floats. Since you want to put the legend on the right, I would suggest using bbox_to_anchor with loc=2. This setting comes from bbox_transform. A simplified way to understand it is: bbox_to_anchor defines the relative location of the corner of the legend box and which corner of the 4 is defined by loc.
In the following example, it puts the "upper left" corner of the legend box at (1, 1) which is the upper right corner of the plot ((0,0) is the "lower left" corner of the plot). And to make it clear, I set borderaxespad to 0.
import matplotlib.pyplot as plt
plt.plot([1,2,3], label="test1")
plt.legend(bbox_to_anchor=(1, 1), loc=2, borderaxespad=0.)
plt.show()

Matplotlib automatic legend outside plot [duplicate]

This question already has answers here:
How to put the legend outside the plot
(18 answers)
Closed 5 years ago.
I am trying to use the keyword bbox_to_anchor() in a matplotlib plot in Python.
Here is a very basic plot that I have produced based on this example. :
import matplotlib.pyplot as plt
x = [1,2,3]
plt.subplot(211)
plt.plot(x, label="test1")
plt.plot([3,2,1], label="test2")
plt.legend(bbox_to_anchor=(0, -0.15, 1, 0), loc=2, ncol=2, mode="expand", borderaxespad=0)
plt.show()
I am trying to automatically place the legend outside the plot using bbox_to_anchor(). In this example, bbox_to_anchor() has 4 arguments listed.
In this particular example (above), the legend is placed below the plot so the number -0.15 needs to be manually entered each time a plot is changed (font size, axis title removed, etc.).
Is it possible to automatically calculate these 4 numbers for the following scenarios?:
legend below plot
legend above plot
legend to right of plot
If not, is it possible to make good guesses about these numbers, in Python?
Also, in the example code above I have set the last 2 numbers in bbox_to_anchor() to 1 and 0 since I do not understand what they are or how they work. What do the last 2 numbers in bbox_to_anchor() mean?
EDIT:
I HIGHLY RECOMMEND USING THE ANSWER FROM ImportanceOfBeingErnest:
How to put the legend outside the plot
EDIT END
This one is easier to understand:
import matplotlib.pyplot as plt
x = [1,2,3]
plt.subplot(211)
plt.plot(x, label="test1")
plt.plot([3,2,1], label="test2")
plt.legend(bbox_to_anchor=(0, 1), loc='upper left', ncol=1)
plt.show()
now play with the to coordinates (x,y). For loc you can use:
valid locations are:
right
center left
upper right
lower right
best
center
lower left
center right
upper left
upper center
lower center
The argument to bbox_to_anchor is in Axes Coordinates. matplotlib uses different coordinate systems to ease placement of objects on the screen. When dealing with positioning legends, the critical coordinate systems to deal with are Axes coordinates, Figure coordinates, and Display coordinates (in pixels) as shown below:
matplotlib coordinate systems
As previously mentioned, bbox_to_anchor is in Axes coordinates and does not require all 4 tuple arguments for a rectangle. You can simply give it a two-argument tuple containing (xpos, ypos) in Axes coordinates. The loc argument in this case will define the anchor point for the legend. So to pin the legend to the outer right of the axes and aligned with the top edge, you would issue the following:
lgd = plt.legend(bbox_to_anchor=(1.01, 1), loc='upper left')
This however does not reposition the Axes with respect to the Figure and this will likely position the legend off of the Figure canvas. To automatically reposition the Figure canvas to align with the Axes and legend, I have used the following algorithm.
First, draw the legend on the canvas to assign it real pixel coordinates:
plt.gcf().canvas.draw()
Then define the transformation to go from pixel coordinates to Figure coordinates:
invFigure = plt.gcf().transFigure.inverted()
Next, get the legend extents in pixels and convert to Figure coordinates. Pull out the farthest extent in the x direction since that is the canvas direction we need to adjust:
lgd_pos = lgd.get_window_extent()
lgd_coord = invFigure.transform(lgd_pos)
lgd_xmax = lgd_coord[1, 0]
Do the same for the Axes:
ax_pos = plt.gca().get_window_extent()
ax_coord = invFigure.transform(ax_pos)
ax_xmax = ax_coord[1, 0]
Finally, adjust the Figure canvas using tight_layout for the proportion of the Axes that must move over to allow room for the legend to fit within the canvas:
shift = 1 - (lgd_xmax - ax_xmax)
plt.gcf().tight_layout(rect=(0, 0, shift, 1))
Note that the rect argument to tight_layout is in Figure coordinates and defines the lower left and upper right corners of a rectangle containing the tight_layout bounds of the Axes, which does not include the legend. So a simple tight_layout call is equivalent to setting rect bounds of (0, 0, 1, 1).

How to turn off the ticks AND marks of a matlibplot axes?

I want to plot 2 subplots by using matlibplot axes. Since these two subplots have the same ylabel and ticks, I want to turn off both the ticks AND marks of the second subplot. Following is my short script:
import matplotlib.pyplot as plt
ax1=plt.axes([0.1,0.1,0.4,0.8])
ax1.plot(X1,Y1)
ax2=plt.axes([0.5,0.1,0.4,0.8])
ax2.plot(X2,Y2)
BTW, the X axis marks overlapped and not sure whether there is a neat solution or not. (A solution might be make the last mark invisible for each subplot except for the last one, but not sure how). Thanks!
A quick google and I found the answers:
plt.setp(ax2.get_yticklabels(), visible=False)
ax2.yaxis.set_tick_params(size=0)
ax1.yaxis.tick_left()
A slightly different solution might be to actually set the ticklabels to ''. The following will get rid of all the y-ticklabels and tick marks:
# This is from #pelson's answer
plt.setp(ax2.get_yticklabels(), visible=False)
# This actually hides the ticklines instead of setting their size to 0
# I can never get the size=0 setting to work, unsure why
plt.setp(ax2.get_yticklines(),visible=False)
# This hides the right side y-ticks on ax1, because I can never get tick_left() to work
# yticklines alternate sides, starting on the left and going from bottom to top
# thus, we must start with "1" for the index and select every other tickline
plt.setp(ax1.get_yticklines()[1::2],visible=False)
And now to get rid of the last tickmark and label for the x-axis
# I used a for loop only because it's shorter
for ax in [ax1, ax2]:
plt.setp(ax.get_xticklabels()[-1], visible=False)
plt.setp(ax.get_xticklines()[-2:], visible=False)

Categories