How to add a legend to a scatter plot in Matplotlib?
0 1120
Enhancing Scatter Plots with Legends in Matplotlib
Scatter plots are invaluable for visualizing relationships between two numerical variables. However, when plotting multiple datasets on the same graph, it's essential to distinguish between them. Adding a legend provides clarity, helping viewers identify which data corresponds to which set. In this guide, we'll explore how to effectively add legends to scatter plots using Matplotlib in Python.
Why Add a Legend?
A legend acts as a key to your scatter plot, associating colors, markers, or sizes with specific datasets or categories. Without a legend, viewers might struggle to interpret the data correctly. By assigning labels to different datasets and displaying them in a legend, you make your visualizations more informative and accessible.
Basic Usage of Legends
Matplotlib offers several methods to add legends to scatter plots. The most straightforward approach is by using the label parameter within the scatter() function. Once labels are assigned, calling plt.legend() will display the legend on the plot.
Here's an example:
import matplotlib.pyplot as plt
import numpy as np
# Sample data
x = np.arange(1, 6)
y1 = x**2
y2 = x**3
# Scatter plots with labels
plt.scatter(x, y1, label="x²")
plt.scatter(x, y2, label="x³")
# Display legend
plt.legend()
plt.show()
In this example, two scatter plots are created: one for x² and another for x³. The label parameter assigns names to these datasets, and plt.legend() displays the legend accordingly.
Customizing Legend Placement
By default, Matplotlib places the legend in the "best" location, which might overlap with your data points. To avoid this, you can specify the position using the loc parameter. Additionally, the ncol parameter allows you to set the number of columns in the legend, making it more compact or spread out as needed.
Example:
plt.scatter(x, y1, label="x*2")
plt.scatter(x, y2, label="x*3")
# Customizing legend
plt.legend(loc="lower right", ncol=2)
plt.show()
In this case, the legend is positioned at the lower right corner with two columns, ensuring it doesn't overlap with the data points.
Manual Legend Assignment
If you haven't assigned labels during the scatter plot creation, you can manually specify them when calling plt.legend(). This method is useful when you want to add legends to pre-existing plots or when labels are determined dynamically.
plt.scatter(x, y1)
plt.scatter(x, y2)
# Manual legend assignment
plt.legend(["x*2", "x*3"])
plt.show()
Here, the legend labels are provided as a list, corresponding to the order of the scatter plots.
Advanced Legend Customization
Matplotlib provides additional parameters to further customize the appearance of legends:
fontsize: Adjusts the font size of the legend text.frameon: If set toFalse, removes the background frame of the legend.shadow: Adds a shadow effect to the legend box.title: Sets a title for the legend.
Example:
plt.scatter(x, y1, label="x²")
plt.scatter(x, y2, label="x³")
# Customizing legend appearance
plt.legend(loc="upper left", fontsize=10, title="Functions", frameon=False)
plt.show()
This customization adds a title to the legend, adjusts the font size, and removes the background frame for a cleaner look.
Conclusion
Adding legends to scatter plots in Matplotlib enhances the interpretability of your visualizations. By assigning meaningful labels and customizing the legend's appearance and placement, you can create clear and informative plots that effectively communicate your data insights.
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!
Share:



Comments
Waiting for your comments