![]() |
|
[Tut] Python ? Put Legend Outside Plot ? – Easy Guide - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] Python ? Put Legend Outside Plot ? – Easy Guide (/thread-101014.html) |
[Tut] Python ? Put Legend Outside Plot ? – Easy Guide - xSicKxBot - 04-22-2023 Python ? Put Legend Outside Plot ? – Easy Guide 5/5 – (1 vote) Are you tired of feeling boxed in by your Python plots and ready to break free from the constraints of traditional legend placement? In this guide, I’ll show you how to put legends outside your plot for (click to jump):Let’s start with the first! ![]() ![]() Matplotlib Put Legend Outside Plot Let’s start with various ways to position the legend outside for better visualization and presentation. Matplotlib Set Legend Outside Plot (General) First, let’s adjust the legend’s position outside the plot in general. To do this, use the Code: bbox_to_anchorCode: matplotlib.pyplot.legend(bbox_to_anchor=(x, y)) . Here, adjust the values of Code: xCode: y![]() Code: 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()In this example, the Code: bbox_to_anchorCode: (1.05, 1) Info: The Code: bbox_to_anchorCode: matplotlib.pyplot.legend()Code: xCode: yCode: x=0/1Code: y=0/1Generally, in axes coordinates:
However, the values of Code: xCode: yCode: [0, 1]For example:
Using negative values is also allowed. For example:
The range of Code: xCode: y![]() Matplotlib Set Legend Below or Above Plot To place the legend below the plot, you can set the Code: locCode: bbox_to_anchorCode: plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.1))Code: bbox_to_anchor=(0.5, 1.1) .![]() Matplotlib Set Legend Left of Plot (Upper, Center, Lower Left) For positioning the legend to the left of the plot, use the following examples:
Matplotlib Set Legend Right of Plot (Upper, Center, Lower Right) To position the legend to the right of the plot, you can try the following:
![]() Matplotlib Set Subplots Legend Outside Plot When working with subplots, you can place a single, unified legend outside the plot by iterating over the axes and using the Code: legend() . Remember to use the Code: bbox_to_anchorHere’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: ![]() Code: 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()If your legend is cut off, you can adjust the saved figure’s dimensions using Code: plt.savefig('filename.ext', bbox_inches='tight')Code: bbox_inches .Add Legend Outside a Scatter Plot For a scatter plot, you can use the same approach as mentioned earlier by adding the Code: locCode: bbox_to_anchorCode: plt.legend(loc='upper right', bbox_to_anchor=(1.1, 1)) .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:
Here’s an example demonstrating these steps: ![]() Code: 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()In this example, you use the Code: subplots_adjust()You can also use the Code: tight_layout()![]() Code: # ...
# 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()In this case, the Code: rectCode: [left, bottom, right, top]Code: rectAdditional Legend Configurations 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. Python Set Legend Position As you already know by now, you can place the legend at a specific position in the plot by using the Code: bbox_to_anchorCode: (1.05, 0.5)Code: import matplotlib.pyplot as plt
plt.legend(bbox_to_anchor=(1.05, 0.5))This will place the legend slightly outside the right border of the plot, with its vertical center aligned with the plot center. Python Set Legend Location You can easily change the location of the legend by using the Code: locCode: 'upper right'Code: 'lower left'Code: plt.legend(loc='upper left')This will place the legend in the upper-left corner of the plot. ![]() Python Set Legend Font Size To change the font size of the legend, you can use the Code: fontsizeCode: 'small'Code: 'medium'Code: 'large'Code: plt.legend(fontsize='large')This will increase the font size of the legend text. ![]() Python Set Legend Title If you want to add a title to your legend, you can use the Code: titleCode: plt.legend(title='My Legend Title')This will add the title “My Legend Title” above your legend. ![]() Python Set Legend Labels If you’d like to customize the legend labels, you can pass the Code: labelsCode: plt.legend(labels=['Label 1', 'Label 2'])Your legend will now display the custom labels “Label 1” and “Label 2” for the corresponding plot elements. ![]() Python Set Legend Color Changing the color of the legend text and lines can be achieved by using the Code: labelcolorCode: plt.legend(labelcolor='red')This will change the color of the legend text and lines to red. ![]() Seaborn Put Legend Outside Plot 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. ![]() Sns Set Legend Outside Plot (General) First, let’s talk about the general approach: You can use the Code: legend()Code: bbox_to_anchorCode: loc![]() Here’s a quick example: ![]() Code: 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()Now let’s move the legend below or above the plot. Simply adjust the Code: bbox_to_anchorCode: bbox_to_anchor=(0.5, -0.1)Code: ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.1))And to place the legend above the plot, use Code: bbox_to_anchor=(0.5, 1.1)Code: ax.legend(loc='lower center', bbox_to_anchor=(0.5, 1.1))Similarly, to position the legend on the left side of the plot, you can use the following code snippets: ![]() Upper left: Code: ax.legend(loc='upper right', bbox_to_anchor=(-0.15, 1))Center left: Code: ax.legend(loc='center right', bbox_to_anchor=(-0.15, 0.5))Lower left: Code: ax.legend(loc='lower right', bbox_to_anchor=(-0.15, 0))Lastly, to place the legend on the right side of the plot, adjust the Code: bbox_to_anchor![]() Upper right: Code: ax.legend(loc='upper left', bbox_to_anchor=(1.05, 1))Center right: Code: ax.legend(loc='center left', bbox_to_anchor=(1.05, 0.5))Lower right: Code: ax.legend(loc='lower left', bbox_to_anchor=(1.05, 0))With these techniques, you can easily position the legend outside the plot using Seaborn! Happy plotting! ![]() Pandas Put Legend Outside Plot When working with Pandas and Matplotlib, you often want to move the legend outside the plot to improve readability. No worries! You can do this by taking advantage of the fact that Code: .plot()Code: .legend(bbox_to_anchor=(x, y))Here’s how: ![]() First, import the necessary libraries like Pandas and Matplotlib: Code: import pandas as pd
import matplotlib.pyplot as pltCreate your DataFrame and plot it using the Code: plot()Code: data = {'A': [1, 2, 3], 'B': [4, 5, 6]}
df = pd.DataFrame(data)
ax = df.plot()Next, you’ll want to place the legend outside the plot. Adjust the coordinates parameter, Code: bbox_to_anchorCode: ax.legend(bbox_to_anchor=(1.05, 1)) plt.tight_layout()
plt.show()This code will place the legend to the right of the plot, at the top .Bokeh Put Legend Outside Plot Placing a legend outside the plot in Bokeh can be easily done by using the Code: add_layoutCode: LegendCode: add_layout![]() Here’s a short example to help you move the legend outside the plot in Bokeh: ![]() Code: 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)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. With Bokeh, you have full control over your plot’s appearance, so enjoy exploring different options to find the perfect fit for your data! ![]() ![]() Keep Learning With Your Python Cheat Sheet! ![]() 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! |