5 Best Ways to Add Legends to Charts in Python

Rate this post

💡 Problem Formulation: When visualizing data using charts in Python, adding legends is crucial for interpreting the data points correctly. Suppose you have multiple data series represented on a single plot; a legend helps distinguish between them. The desired outcome is a clear, informative chart where the data series can be easily differentiated through a legend.

Method 1: Using Matplotlib’s legend function

Matplotlib is a popular Python library for creating static, animated, and interactive visualizations. Its legend() function can be used to add a legend to plots. You simply need to label your plot elements and call the legend() function. The function allows for customization of the legend’s location and appearance.

Here’s an example:

import matplotlib.pyplot as plt

plt.plot([1, 2, 3], label='Rising Trend')
plt.plot([3, 2, 1], label='Falling Trend')
plt.legend()
plt.show()

The output is a chart with two lines representing ‘Rising Trend’ and ‘Falling Trend’, and a legend box that labels each line accordingly.

This code snippet creates a simple plot with two lines. Each plot() call includes a label argument that specifies the name to be used in the legend. The legend() function is then called to display the legend on the plot. The show() function displays the plot in a window.

Method 2: Specifying the Legend Location

Matplotlib’s legend() function allows you to specify the location of the legend on the chart. This can be valuable when you need to avoid obscuring important data. The location can be set with a location code, like ‘upper right’, or with a tuple indicating the lower-left point of the legend in the axes coordinates.

Here’s an example:

import matplotlib.pyplot as plt

plt.plot([1, 2, 3], label='Trend A')
plt.plot([3, 2, 1], label='Trend B')
plt.legend(loc='lower center')
plt.show()

The output is a chart with a legend located at the bottom center of the plot area.

This snippet is similar to the previous one, but here we use the loc parameter inside the legend() function to set the legend’s location to ‘lower center’. This places the legend at the bottom in the center of the plot.

Method 3: Creating a Custom Legend

For more control over the appearance of the legend, the legend can be customized with additional parameters, such as fontsize, frameon (to display a frame or not), and title. Custom legends provide enhanced flexibility for matching the legend style with the plot aesthetics.

Here’s an example:

import matplotlib.pyplot as plt

plt.plot([10, 20, 30], label='Data X')
plt.plot([30, 20, 10], label='Data Y')
plt.legend(title='My Legend', frameon=False, fontsize=10)
plt.show()

The output is a customized legend with the title “My Legend,” no frame, and smaller font size.

The code specifies custom options for the legend. The parameter title adds a title to the legend, frameon=False removes the box around the legend, and fontsize adjusts the size of the text within the legend.

Method 4: Using the Legend Handles and Labels

If you need detailed control over the legend items, you can use handles and labels to construct the legend directly. This is useful when plotting complex figures, and you want to create a legend for selected elements only, or when you want to modify labels that were automatically generated.

Here’s an example:

import matplotlib.pyplot as plt
from matplotlib.lines import Line2D

line1, = plt.plot([1, 2, 3], label='Inline label')
line2, = plt.plot([3, 2, 1], label='_nolegend_')
legend_handles = [Line2D([0], [0], color=line1.get_color(), label='Custom label for line1')]
plt.legend(handles=legend_handles)
plt.show()

The output shows a chart with one line labeled with a custom label in the legend, while the other line is not included in the legend at all.

This code uses the Line2D object from Matplotlib to create a custom handle for the legend. The label='_nolegend_' argument to the second plot() function tells Matplotlib to exclude that line from the legend. Then we create a legend using our custom handle that includes a custom label for the first line only.

Bonus One-Liner Method 5: Using Seaborn’s legend function

For those who prefer a higher-level interface, Seaborn, a statistical data visualization library built on top of Matplotlib, provides a convenient way of adding legends. When using Seaborn’s plotting functions, a legend is often added automatically, or it can be customized with a simple function call.

Here’s an example:

import seaborn as sns

tips = sns.load_dataset("tips")
sns.scatterplot(data=tips, x="total_bill", y="tip", hue="time")
plt.show()

The output of this code displays a scatterplot with a legend differentiating between two time periods: ‘Lunch’ and ‘Dinner’.

This example uses Seaborn’s scatterplot() function with the “hue” argument to automatically create a legend based on the “time” column in the “tips” dataset. Seaborn takes care of legend placement and styling by default, making it a quick and easy solution for adding legends to plots.

Summary/Discussion

  • Method 1: Using Matplotlib’s legend function. This is straightforward and works well for simple legends. However, it may lack detail for more complex legends.
  • Method 2: Specifying the Legend Location. Offers additional control over the placement of the legend but still relies on predefined locations or manual axis coordinates.
  • Method 3: Creating a Custom Legend. Great for when you need to have greater control over the appearance of your legend, allowing the plot to be more professionally styled.
  • Method 4: Using the Legend Handles and Labels. Provides the utmost level of customization for legends but requires a deeper understanding of Matplotlib objects.
  • Bonus Method 5: Using Seaborn’s legend function. A very convenient and concise option for adding legends, best-suited for quick plotting with automated legend generation.