× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Matplotlib legends — position and arrangement

<p>You can alter the properties of any matplotlib legend by passing parameters to <code>ax.legend()</code></p> <h2>Position</h2> <p>A lot of the common positions can be defined using combinations of <code>upper lower left right center</code>. </p> <pre> center left center right right lower right upper left best center upper center upper right lower left lower center</pre> <p> </p> <p>Using these positions anchors that corner/point of the legend to that corner/point of the plot. So for example setting:</p> <pre><code class="language-python">ax.legend(loc='top left')</code></pre> <p>will position the top left of the legend at the top left of the axes. While the following</p> <pre><code class="language-python">ax.legend(loc='center left')</code></pre> <p>will anchor the center (halfway up) left side of the axis to that position in the plot.</p> <p>Once this anchor is defined you can also position the legend directly using bbox. This is defined in axis units, with the xaxis running 0...1 horizontally left to right and yaxis  0...1 bottom to top. For example</p> <pre><code class="language-python">ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))</code></pre> <p>will anchor the center (y, middle) left side of the legend, and place it at x=1 (far right of the axis), y=0.5 (half way down the axis), with the effect of placing the legend off the plot to the right, half way down.</p> <p> </p> <h2>Arrangement</h2> <p>Legend arrangement/layout of elements can be customized by passing the <code>ncol</code> parameter. For example, for horizontal legends with 6 items in matplotlib you can pass the number of columns as follows:</p> <pre><code><span style="color:rgb(0, 0, 0)">ax.</span><span style="color:rgb(0, 0, 0)">legend</span><span style="color:rgb(0, 0, 0)">(</span><span style="color:rgb(0, 0, 0)">ncol</span><span style="color:rgb(0, 0, 0)">=</span>6<span style="color:rgb(0, 0, 0)">)</span></code> </pre> <p>This will arrange legend horizontally up to a width of 6.</p> <p> </p> <p> </p>

Get New Tutorials Delivered to Your Inbox

New tutorials will be sent to your Inbox once a week.

comments powered by Disqus