0
0
Matplotlibdata~30 mins

Multiple legends in Matplotlib - Mini Project: Build & Apply

Choose your learning style9 modes available
Creating Multiple Legends in Matplotlib
📖 Scenario: You are working on a sales report for two different products over a week. You want to show their sales trends and also highlight their average sales with different styles on the same plot.
🎯 Goal: Build a line plot with two products' daily sales and add two separate legends: one for the sales lines and one for the average sales lines.
📋 What You'll Learn
Create two lists with daily sales data for Product A and Product B.
Create two variables for average sales of Product A and Product B.
Plot daily sales lines for both products.
Plot average sales lines for both products with a different style.
Add two separate legends: one for daily sales lines and one for average sales lines.
💡 Why This Matters
🌍 Real World
Multiple legends help show different groups of information clearly on one chart, like sales trends and averages.
💼 Career
Data scientists and analysts often need to present complex data visually with clear legends to help decision makers understand multiple data aspects.
Progress0 / 4 steps
1
Create sales data lists
Create two lists called sales_product_a and sales_product_b with these exact daily sales values: [10, 12, 15, 14, 13, 16, 18] for Product A and [8, 9, 11, 10, 12, 13, 15] for Product B.
Matplotlib
Need a hint?

Use square brackets to create lists with the exact numbers given.

2
Calculate average sales
Create two variables called avg_a and avg_b that store the average sales of sales_product_a and sales_product_b respectively. Use the sum() and len() functions.
Matplotlib
Need a hint?

Use sum() to add all values and len() to count the number of days.

3
Plot sales and average lines
Import matplotlib.pyplot as plt. Plot sales_product_a and sales_product_b as lines with labels 'Product A Sales' and 'Product B Sales'. Then plot horizontal lines for averages avg_a and avg_b with dashed style and labels 'Product A Average' and 'Product B Average'.
Matplotlib
Need a hint?

Use plt.plot() for lines. Use 'r--' and 'g--' for dashed red and green lines.

4
Add two separate legends and show plot
Create two legends: one for the sales lines using plt.legend() with handles line1 and line2 placed at the upper left, and another for the average lines with handles line3 and line4 placed at the lower right. Then display the plot with plt.show().
Matplotlib
Need a hint?

Use plt.legend(handles=[...], loc='...') to create each legend. Use plt.gca().add_artist() to add the first legend before adding the second.