Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python ? Put Legend Outside Plot ? – Easy Guide

#1
Python ? Put Legend Outside Plot ? – Easy Guide

<div>
<div class="kk-star-ratings kksr-auto kksr-align-left kksr-valign-top" data-payload='{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;1311124&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;ignore&quot;:&quot;&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;class&quot;:&quot;&quot;,&quot;count&quot;:&quot;1&quot;,&quot;legendonly&quot;:&quot;&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;5&quot;,&quot;starsonly&quot;:&quot;&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;5&quot;,&quot;greet&quot;:&quot;Rate this post&quot;,&quot;legend&quot;:&quot;5\/5 - (1 vote)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;title&quot;:&quot;Python \ud83d\udc0d Put Legend Outside Plot \ud83d\udcc8 - Easy Guide&quot;,&quot;width&quot;:&quot;142.5&quot;,&quot;_legend&quot;:&quot;{score}\/{best} - ({count} {votes})&quot;,&quot;font_factor&quot;:&quot;1.25&quot;}'>
<div class="kksr-stars">
<div class="kksr-stars-inactive">
<div class="kksr-star" data-star="1" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="2" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="3" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="4" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="5" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
<div class="kksr-stars-active" style="width: 142.5px;">
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
</div>
<div class="kksr-legend" style="font-size: 19.2px;"> 5/5 – (1 vote) </div>
</p></div>
<p>Are you tired of feeling boxed in by your Python plots and ready to break free from the constraints of traditional legend placement?</p>
<p>In this guide, I’ll show you how to put legends outside your plot for (click to <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f998.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> jump): </p>
<ul>
<li><a href="#matplotlib" data-type="internal" data-id="#matplotlib" target="_blank" rel="noreferrer noopener">Matplotlib</a></li>
<li><a href="#seaborn" data-type="internal" data-id="#seaborn">Seaborn</a></li>
<li><a href="#pandas" data-type="internal" data-id="#pandas">Pandas</a></li>
<li><a href="#bokeh">Bokeh</a></li>
</ul>
<p>Let’s start with the first! <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f447.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f469-200d-1f4bb.png" alt="?‍?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h2 class="wp-block-heading" id="matplotlib">Matplotlib Put Legend Outside Plot</h2>
<p>Let’s start with various ways to position the legend outside for better visualization and presentation.</p>
<h3 class="wp-block-heading">Matplotlib Set Legend Outside Plot (General)</h3>
<p class="has-global-color-8-background-color has-background">First, let’s adjust the legend’s position outside the plot in general. To do this, use the <code>bbox_to_anchor</code> parameter in the legend function like this: <code>matplotlib.pyplot.legend(bbox_to_anchor=(x, y))</code> <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f603.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" />. Here, adjust the values of <code>x</code> and <code>y</code> to control the legend’s position.</p>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="791" height="520" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-220.png" alt="" class="wp-image-1311674" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-220.png 791w, https://blog.finxter.com/wp-content/uplo...00x197.png 300w, https://blog.finxter.com/wp-content/uplo...68x505.png 768w" sizes="(max-width: 791px) 100vw, 791px" /></figure>
</div>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="13" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import matplotlib.pyplot as plt # Sample data for plotting
x = [1, 2, 3, 4, 5]
y1 = [1, 4, 9, 16, 25]
y2 = [1, 8, 27, 64, 125] # Create the plot
plt.plot(x, y1, label='y = x^2')
plt.plot(x, y2, label='y = x^3') # Set the legend's position outside the plot using bbox_to_anchor
plt.legend(bbox_to_anchor=(1.05, 1)) # Add axis labels and title
plt.xlabel('x')
plt.ylabel('y')
plt.title('Plotting with External Legend') # Display the plot
plt.show()
</pre>
<p>In this example, the <code>bbox_to_anchor</code> parameter is set to <code>(1.05, 1)</code>, which moves the legend slightly to the right of the plot.</p>
<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Info</strong>: The <code>bbox_to_anchor</code> parameter in <code>matplotlib.pyplot.legend()</code> uses a tuple of two values, <code>x</code> and <code>y</code>, to control the position of the legend. <code>x=0/1</code> controls the <strong><em>left/right</em></strong> and <code>y=0/1</code> controls the <strong><em>bottom/top</em></strong> legend placement.</p>
<p>Generally, in axes coordinates:</p>
<ul>
<li><code>(0, 0)</code> represents the <strong>left-bottom</strong> corner of the axes.</li>
<li><code>(0, 1)</code> represents the <strong>left-top</strong> corner of the axes.</li>
<li><code>(1, 0)</code> represents the <strong>right-bottom</strong> corner of the axes.</li>
<li><code>(1, 1)</code> represents the <strong>right-top</strong> corner of the axes.</li>
</ul>
<p>However, the values of <code>x</code> and <code>y</code> are not limited to the range <code>[0, 1]</code>. You can use values outside of this range to place the legend beyond the axes’ boundaries.</p>
<p>For example:</p>
<ul>
<li>(1.05, 1) places the legend slightly to the right of the top-right corner of the axes.</li>
<li>(0, 1.1) places the legend slightly above the top-left corner of the axes.</li>
</ul>
<p>Using negative values is also allowed. For example:</p>
<ul>
<li>(-0.3, 0) places the legend to the left of the bottom-left corner of the axes.</li>
<li>(1, -0.2) places the legend below the bottom-right corner of the axes.</li>
</ul>
<p>The range of <code>x</code> and <code>y</code> depends on the desired position of the legend relative to the plot. By adjusting these values, you can fine-tune the legend’s position to create the perfect visualization. <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4ab.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> </p>
<h3 class="wp-block-heading">Matplotlib Set Legend Below or Above Plot</h3>
<p class="has-global-color-8-background-color has-background">To place the legend below the plot, you can set the <code>loc</code> parameter as ‘upper center’ and use <code>bbox_to_anchor</code> like this: <code>plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.1))</code>. For placing the legend above the plot, use <code>bbox_to_anchor=(0.5, 1.1)</code> instead <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4ca.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" />.</p>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" loading="lazy" width="929" height="436" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-221.png" alt="" class="wp-image-1311717" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-221.png 929w, https://blog.finxter.com/wp-content/uplo...00x141.png 300w, https://blog.finxter.com/wp-content/uplo...68x360.png 768w" sizes="(max-width: 929px) 100vw, 929px" /></figure>
</div>
<h3 class="wp-block-heading">Matplotlib Set Legend Left of Plot (Upper, Center, Lower Left)</h3>
<p>For positioning the legend to the left of the plot, use the following examples:</p>
<ul>
<li>Upper left: <code>plt.legend(loc='center left', bbox_to_anchor=(-0.2, 0.5))</code> <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f31f.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></li>
<li>Center left: <code>plt.legend(loc='center left', bbox_to_anchor=(-0.1, 0.5))</code></li>
<li>Lower left: <code>plt.legend(loc='lower left', bbox_to_anchor=(-0.2, 0))</code></li>
</ul>
<h3 class="wp-block-heading">Matplotlib Set Legend Right of Plot (Upper, Center, Lower Right)</h3>
<p>To position the legend to the right of the plot, you can try the following:</p>
<ul>
<li>Upper right: <code>plt.legend(loc='upper right', bbox_to_anchor=(1.1, 1))</code> <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f44d.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></li>
<li>Center right: <code>plt.legend(loc='center right', bbox_to_anchor=(1.1, 0.5))</code></li>
<li>Lower right: <code>plt.legend(loc='lower right', bbox_to_anchor=(1.1, 0))</code></li>
</ul>
<div class="wp-block-image">
<figure class="aligncenter size-large"><img decoding="async" loading="lazy" width="1024" height="447" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-222-1024x447.png" alt="" class="wp-image-1311719" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-222-1024x447.png 1024w, https://blog.finxter.com/wp-content/uplo...00x131.png 300w, https://blog.finxter.com/wp-content/uplo...68x335.png 768w, https://blog.finxter.com/wp-content/uplo...ge-222.png 1073w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
</div>
<h3 class="wp-block-heading">Matplotlib Set Subplots Legend Outside Plot</h3>
<p class="has-global-color-8-background-color has-background">When working with subplots, you can place a single, unified legend outside the plot by iterating over the axes and using the <code>legend()</code> method on the last axis <a href="https://stackoverflow.com/questions/4700614/how-to-put-the-legend-outside-the-plot">(source)</a> <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f60a.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" />. Remember to use the <code>bbox_to_anchor</code> parameter to control the legend’s position.</p>
<p>Here’s an example that does two things, i.e., (1) placing the legend on the right and (2) adjusting the layout to accommodate the external legend:</p>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" loading="lazy" width="662" height="460" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-223.png" alt="" class="wp-image-1311729" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-223.png 662w, https://blog.finxter.com/wp-content/uplo...00x208.png 300w" sizes="(max-width: 662px) 100vw, 662px" /></figure>
</div>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="35" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import numpy as np
import matplotlib.pyplot as plt # Sample data for plotting
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x) # Create subplots
fig, axes = plt.subplots(nrows=2, ncols=1, sharex=True) # Plot data on the first subplot
axes[0].plot(x, y1, label='sin(x)')
axes[0].set_title('Sine Wave') # Plot data on the second subplot
axes[1].plot(x, y2, label='cos(x)', color='orange')
axes[1].set_title('Cosine Wave') # Set a common x-label for both subplots
fig.text(0.5, 0.04, 'x', ha='center') # Set y-labels for individual subplots
axes[0].set_ylabel('sin(x)')
axes[1].set_ylabel('cos(x)') # Create a unified legend for both subplots
handles, labels = axes[-1].get_legend_handles_labels()
for ax in axes[:-1]: h, l = ax.get_legend_handles_labels() handles += h labels += l # Place the unified legend outside the plot using bbox_to_anchor
fig.legend(handles, labels, loc='upper right', bbox_to_anchor=(1, 0.75)) # Adjust the layout to accommodate the external legend
fig.subplots_adjust(right=0.7) # Display the subplots
plt.show()
</pre>
<h3 class="wp-block-heading">Legend Outside Plot Is Cut Off</h3>
<p>If your legend is cut off, you can adjust the saved figure’s dimensions using <code>plt.savefig('filename.ext', bbox_inches='tight')</code>. The <code>bbox_inches</code> parameter with the value ‘tight’ will ensure that the whole legend is visible on the saved figure <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f389.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" />.</p>
<h3 class="wp-block-heading">Add Legend Outside a Scatter Plot</h3>
<p>For a scatter plot, you can use the same approach as mentioned earlier by adding the <code>loc</code> and <code>bbox_to_anchor</code> parameters to position the legend outside the plot. For instance, <code>plt.legend(loc='upper right', bbox_to_anchor=(1.1, 1))</code> will place the legend in the upper right corner outside the scatter plot <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" />.</p>
<p>If your legend is cut off when placing it outside the plot in Python’s Matplotlib, you can adjust the layout and save or display the entire figure, including the external legend, by following these steps:</p>
<ol>
<li>Use the <code>bbox_to_anchor</code> parameter in the <code>legend()</code> function to control the position of the legend.</li>
<li>Adjust the layout of the figure using the <code>subplots_adjust()</code> or <code>tight_layout()</code> function to make room for the legend.</li>
<li>Save or display the entire figure, including the external legend.</li>
</ol>
<p>Here’s an example demonstrating these steps:</p>
<div class="wp-block-image">
<figure class="aligncenter size-large"><img decoding="async" loading="lazy" width="1024" height="462" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-224-1024x462.png" alt="" class="wp-image-1311730" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-224-1024x462.png 1024w, https://blog.finxter.com/wp-content/uplo...00x135.png 300w, https://blog.finxter.com/wp-content/uplo...68x346.png 768w, https://blog.finxter.com/wp-content/uplo...ge-224.png 1113w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
</div>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import matplotlib.pyplot as plt # Sample data for plotting
x = [1, 2, 3, 4, 5]
y1 = [1, 4, 9, 16, 25]
y2 = [1, 8, 27, 64, 125] # Create the plot
plt.plot(x, y1, label='y = x^2')
plt.plot(x, y2, label='y = x^3') # Set the legend's position outside the plot using bbox_to_anchor
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left') # Add axis labels and title
plt.xlabel('x')
plt.ylabel('y')
plt.title('Plotting with External Legend') # Adjust the layout to accommodate the external legend
plt.subplots_adjust(right=0.7) # Display the plot
plt.show()
</pre>
<p>In this example, you use the <code>subplots_adjust()</code> function to adjust the layout of the figure and make room for the legend. </p>
<p>You can also use the <code>tight_layout()</code> function, which automatically adjusts the layout based on the elements in the figure:</p>
<div class="wp-block-image">
<figure class="aligncenter size-large"><img decoding="async" loading="lazy" width="1024" height="508" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-225-1024x508.png" alt="" class="wp-image-1311731" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-225-1024x508.png 1024w, https://blog.finxter.com/wp-content/uplo...00x149.png 300w, https://blog.finxter.com/wp-content/uplo...68x381.png 768w, https://blog.finxter.com/wp-content/uplo...ge-225.png 1195w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
</div>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># ...
# Set the legend's position outside the plot using bbox_to_anchor
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left') # Add axis labels and title
plt.xlabel('x')
plt.ylabel('y')
plt.title('Plotting with External Legend') # Automatically adjust the layout to accommodate the external legend
plt.tight_layout(rect=[0, 0, 0.7, 1]) # Display the plot
plt.show()
</pre>
<p>In this case, the <code>rect</code> parameter is a list <code>[left, bottom, right, top]</code>, which specifies the normalized figure coordinates of the new bounding box for the subplots. Adjust the values in the <code>rect</code> parameter as needed to ensure the legend is not cut off.</p>
<h2 class="wp-block-heading">Additional Legend Configurations</h2>
<p>In this section, you’ll learn about some additional ways to customize the legend for your plots in Python using Matplotlib. This will help you create more meaningful and visually appealing visualizations. However, feel free to skip ahead to the following sections on plotting the legend outside the figure in Seaborn, Pandas, and Bokeh.</p>
<h3 class="wp-block-heading">Python Set Legend Position</h3>
<p>As you already know by now, you can place the legend at a specific position in the plot by using the <code>bbox_to_anchor</code> parameter. For example, you could place the legend outside the plot to the right by passing <code>(1.05, 0.5)</code> as the argument:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import matplotlib.pyplot as plt
plt.legend(bbox_to_anchor=(1.05, 0.5))</pre>
<p>This will place the legend slightly outside the right border of the plot, with its vertical center aligned with the plot center.</p>
<h3 class="wp-block-heading">Python Set Legend Location</h3>
<p>You can easily change the location of the legend by using the <code>loc</code> parameter. Matplotlib allows you to use predefined locations like <code>'upper right'</code>, <code>'lower left'</code>, etc., or use a specific coordinate by passing a tuple:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">plt.legend(loc='upper left')</pre>
<p>This will place the legend in the upper-left corner of the plot.<img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4cd.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h3 class="wp-block-heading">Python Set Legend Font Size</h3>
<p>To change the font size of the legend, you can use the <code>fontsize</code> parameter. You can pass a numeric value or a string like <code>'small'</code>, <code>'medium'</code>, or <code>'large'</code> to set the font size:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">plt.legend(fontsize='large')</pre>
<p>This will increase the font size of the legend text.<img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f603.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h3 class="wp-block-heading">Python Set Legend Title</h3>
<p>If you want to add a title to your legend, you can use the <code>title</code> parameter. Just pass a string as the argument to set the title:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">plt.legend(title='My Legend Title')</pre>
<p>This will add the title “My Legend Title” above your legend.<img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f44d.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h3 class="wp-block-heading">Python Set Legend Labels</h3>
<p>If you’d like to customize the legend labels, you can pass the <code>labels</code> parameter. It takes a list of strings as the argument:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">plt.legend(labels=['Label 1', 'Label 2'])</pre>
<p>Your legend will now display the custom labels “Label 1” and “Label 2” for the corresponding plot elements.<img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f3f7.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h3 class="wp-block-heading">Python Set Legend Color</h3>
<p>Changing the color of the legend text and lines can be achieved by using the <code>labelcolor</code> parameter. Just pass a color string or a list of colors:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">plt.legend(labelcolor='red')</pre>
<p>This will change the color of the legend text and lines to red.<img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f534.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h2 class="wp-block-heading" id="seaborn">Seaborn Put Legend Outside Plot</h2>
<p>In this section, I’ll show you how to move the legend outside the plot using Seaborn. Let’s dive into various ways of setting the legend position, like below, above, left or right of the plot.<img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f468-200d-1f4bb.png" alt="?‍?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h3 class="wp-block-heading">Sns Set Legend Outside Plot (General)</h3>
<p>First, let’s talk about the general approach:</p>
<p class="has-global-color-8-background-color has-background">You can use the <code>legend()</code> function and the <code>bbox_to_anchor</code> parameter from Matplotlib to move the legend. You can combine this with the <code>loc</code> parameter to fine-tune the legend’s position.<img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4c8.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>Here’s a quick example:</p>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" loading="lazy" width="669" height="455" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-226.png" alt="" class="wp-image-1311735" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-226.png 669w, https://blog.finxter.com/wp-content/uplo...00x204.png 300w" sizes="(max-width: 669px) 100vw, 669px" /></figure>
</div>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="12" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import seaborn as sns
import matplotlib.pyplot as plt # Sample data for plotting
tips = sns.load_dataset("tips") # Create a Seaborn plot with axis variable 'ax'
fig, ax = plt.subplots()
sns_plot = sns.scatterplot(x="total_bill", y="tip", hue="day", data=tips, ax=ax) # Set the legend's position outside the plot using bbox_to_anchor on 'ax'
ax.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0.) # Add axis labels and title
ax.set_xlabel('Total Bill')
ax.set_ylabel('Tip')
ax.set_title('Tips by Total Bill and Day') # Display the plot
plt.show()
</pre>
<h3 class="wp-block-heading">Sns Set Legend Below or Above Plot</h3>
<p>Now let’s move the legend below or above the plot.<img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Simply adjust the <code>bbox_to_anchor</code> parameter accordingly. For example, to place the legend below the plot, you can use <code>bbox_to_anchor=(0.5, -0.1)</code>:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.1))
</pre>
<p>And to place the legend above the plot, use <code>bbox_to_anchor=(0.5, 1.1)</code>:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">ax.legend(loc='lower center', bbox_to_anchor=(0.5, 1.1))
</pre>
<h3 class="wp-block-heading">Sns Set Legend Left of Plot (Upper, Center, Lower Left)</h3>
<p>Similarly, to position the legend on the left side of the plot, you can use the following code snippets:<img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f3a8.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>Upper left:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">ax.legend(loc='upper right', bbox_to_anchor=(-0.15, 1))
</pre>
<p>Center left:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">ax.legend(loc='center right', bbox_to_anchor=(-0.15, 0.5))
</pre>
<p>Lower left:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">ax.legend(loc='lower right', bbox_to_anchor=(-0.15, 0))
</pre>
<h3 class="wp-block-heading">Sns Set Legend Right of Plot (Upper, Center, Lower Right)</h3>
<p>Lastly, to place the legend on the right side of the plot, adjust the <code>bbox_to_anchor</code> parameter like so:<img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f680.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>Upper right:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">ax.legend(loc='upper left', bbox_to_anchor=(1.05, 1))
</pre>
<p>Center right:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">ax.legend(loc='center left', bbox_to_anchor=(1.05, 0.5))
</pre>
<p>Lower right:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">ax.legend(loc='lower left', bbox_to_anchor=(1.05, 0))
</pre>
<p>With these techniques, you can easily position the legend outside the plot using Seaborn! Happy plotting!<img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f469-200d-1f52c.png" alt="?‍?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h2 class="wp-block-heading" id="pandas">Pandas Put Legend Outside Plot</h2>
<p class="has-global-color-8-background-color has-background">When working with Pandas and Matplotlib, you often want to move the legend outside the plot <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f5bc.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> to improve readability. No worries! You can do this by taking advantage of the fact that <code>.plot()</code> returns a Matplotlib axis, enabling you to add <code>.legend(bbox_to_anchor=(x, y))</code> to your code. </p>
<p>Here’s how:</p>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" loading="lazy" width="988" height="478" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-227.png" alt="" class="wp-image-1311740" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-227.png 988w, https://blog.finxter.com/wp-content/uplo...00x145.png 300w, https://blog.finxter.com/wp-content/uplo...68x372.png 768w" sizes="(max-width: 988px) 100vw, 988px" /></figure>
</div>
<p>First, import the necessary libraries like Pandas and Matplotlib:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import pandas as pd
import matplotlib.pyplot as plt
</pre>
<p>Create your DataFrame and plot it using the <code>plot()</code> function, like this:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">data = {'A': [1, 2, 3], 'B': [4, 5, 6]}
df = pd.DataFrame(data)
ax = df.plot()
</pre>
<p>Next, you’ll want to place the legend outside the plot. Adjust the coordinates parameter, <code>bbox_to_anchor</code>, to position it according to your preferences. For example, if you want to place the legend to the right of the plot, use:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">ax.legend(bbox_to_anchor=(1.05, 1)) plt.tight_layout()
plt.show()
</pre>
<p>This code will place the legend to the right of the plot, at the top <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f680.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" />.</p>
<h2 class="wp-block-heading" id="bokeh">Bokeh Put Legend Outside Plot</h2>
<p class="has-global-color-8-background-color has-background">Placing a legend outside the plot in Bokeh can be easily done by using the <code>add_layout</code> method. You’ll need to create a <code>Legend</code> object manually and then add it to your plot using <code>add_layout</code>. This gives you the flexibility to position the legend anywhere on your plot, which is particularly helpful when you have many curves that might be obscured by an overlapping legend. <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f60a.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>Here’s a short example to help you move the legend outside the plot in Bokeh:</p>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" loading="lazy" width="722" height="718" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-228.png" alt="" class="wp-image-1311741" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-228.png 722w, https://blog.finxter.com/wp-content/uplo...00x298.png 300w, https://blog.finxter.com/wp-content/uplo...50x150.png 150w" sizes="(max-width: 722px) 100vw, 722px" /></figure>
</div>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from bokeh.plotting import figure, show
from bokeh.models import Legend, LegendItem
from bokeh.io import output_notebook
output_notebook() # Example data
x = list(range(10))
y1 = [i**2 for i in x]
y2 = [i**0.5 for i in x] # Create a figure
p = figure(title="Example Plot") # Add line glyphs and store their renderer
r1 = p.line(x, y1, line_color="blue", legend_label="Line 1")
r2 = p.line(x, y2, line_color="red", legend_label="Line 2") # Create Legend object
legend = Legend(items=[ LegendItem(label="Line 1", renderers=[r1]), LegendItem(label="Line 2", renderers=[r2])
], location="top_left") # Add legend to plot
p.add_layout(legend, 'right') # Show plot
show(p)
</pre>
<p>To ensure your plot is as clear as possible, we recommend experimenting with different legend positions and layouts. By customizing your plot, you can maintain a clean and organized display of your curves even when there’s a lot of information to convey. </p>
<p>With Bokeh, you have full control over your plot’s appearance, so enjoy exploring different options to find the perfect fit for your data! <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4c8.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f389.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<hr class="wp-block-separator has-alpha-channel-opacity"/>
<h2 class="wp-block-heading">Keep Learning With Your Python Cheat Sheet! <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /></h2>
<p>Feel free to download our free cheat sheet and join our tech and coding academy by downloading the free Finxter cheat sheets — it’s fun!</p>
</div>


https://www.sickgaming.net/blog/2023/04/...asy-guide/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016