![subplot legend subplot legend](https://i.stack.imgur.com/Gh7v4.jpg)
L2 = plt.legend(bbox_to_anchor=(1.04, 0), loc="lower left", borderaxespad=0) Places the legend outside the axes, such that the upper left corner of the legend is at position (1.04, 1) in axes coordinates.įurther examples are given below, where additionally the interplay between different arguments like mode and ncols are shown. This creates a zero span box, out of which the legend will expand in the direction given by the loc argument. One can restrict oneself to supply only the (x0, y0) part of the bbox. plt.legend(loc=(1.04, 0))Ī more versatile approach is to manually specify the bounding box into which the legend should be placed, using the bbox_to_anchor argument.
![subplot legend subplot legend](https://matplotlib.org/2.0.0/_images/legend_demo3.png)
![subplot legend subplot legend](https://i.stack.imgur.com/7qUJM.png)
To place the legend outside of the axes bounding box, one may specify a tuple (x0, y0) of axes coordinates of the lower left corner of the legend. You might also take a look at plt.figlegend().Ī legend is positioned inside the bounding box of the axes using the loc argument to plt.legend.Į.g., loc="upper right" places the legend in the upper right corner of the bounding box, which by default extents from (0, 0) to (1, 1) in axes coordinates (or in bounding box notation (x0, y0, width, height) = (0, 0, 1, 1)). Have a look at the matplotlib legend guide. # Shrink current axis's height by 10% on the bottomĪx.set_position([box.x0, box.y0 + box.height * 0.1,Īx.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05), # Put a legend to the right of the current axisĪx.legend(loc='center left', bbox_to_anchor=(1, 0.5))Īnd in a similar manner, shrink the plot vertically, and put a horizontal legend at the bottom: import matplotlib.pyplot as plt Line, = ax.plot(x, i * x, label='$y = %ix$'%i)Īx.legend(loc='upper center', bbox_to_anchor=(0.5, 1.05),Īlternatively, shrink the current plot's width, and put the legend entirely outside the axis of the figure (note: if you use tight_layout(), then leave out ax.set_position(): import matplotlib.pyplot as pltĪx.set_position() Similarly, make the legend more horizontal and/or put it at the top of the figure (I'm also turning on rounded corners and a simple drop shadow): import matplotlib.pyplot as plt If we do the same thing, but use the bbox_to_anchor keyword argument we can shift the legend slightly outside the axes boundaries: import matplotlib.pyplot as plt So, let's start with a generic example: import matplotlib.pyplot as plt To add to what Christian Alis and Navi already said, you can use the bbox_to_anchor keyword argument to place the legend partially outside the axes and/or decrease the font size.īefore you consider decreasing the font size (which can make things awfully hard to read), try playing around with placing the legend in different places: There are a number of ways to do what you want.