0
0
Matplotlibdata~15 mins

Legend placement options in Matplotlib - Mini Project: Build & Apply

Choose your learning style9 modes available
Legend placement options
📖 Scenario: You are creating a simple line chart to compare sales of two products over 5 months. You want to add a legend to explain which line is which. The legend can be placed in different positions on the chart.
🎯 Goal: Learn how to add a legend to a matplotlib plot and place it in different positions using the loc parameter.
📋 What You'll Learn
Create a line plot with two lines representing sales data for Product A and Product B.
Add a legend with labels for each product.
Set the legend position using the loc parameter with a string value.
💡 Why This Matters
🌍 Real World
Legends help explain different data series in charts, making them easier to understand in reports and presentations.
💼 Career
Data scientists and analysts often create visualizations with legends to clearly communicate insights to stakeholders.
Progress0 / 4 steps
1
Create sales data and plot lines
Create two lists called months and sales_a with values [1, 2, 3, 4, 5] and [10, 15, 13, 17, 20] respectively. Also create a list called sales_b with values [12, 14, 16, 18, 22]. Then import matplotlib.pyplot as plt and plot sales_a and sales_b against months using plt.plot(). Use labels 'Product A' and 'Product B' for the lines.
Matplotlib
Need a hint?

Use plt.plot(x_values, y_values, label='name') to plot lines with labels.

2
Add a legend with default placement
Add a legend to the plot by calling plt.legend() without any arguments.
Matplotlib
Need a hint?

Call plt.legend() to add the legend with default position.

3
Change legend position to upper left
Modify the legend call to place the legend in the upper left corner by passing loc='upper left' to plt.legend().
Matplotlib
Need a hint?

Use plt.legend(loc='upper left') to move the legend.

4
Display the plot
Add a line to display the plot by calling plt.show().
Matplotlib
Need a hint?

Use plt.show() to display the plot window.