0
0
Matplotlibdata~30 mins

Custom legend entries in Matplotlib - Mini Project: Build & Apply

Choose your learning style9 modes available
Custom legend entries
📖 Scenario: You are creating a simple line chart to compare sales data for two products over four quarters. You want to add a legend to explain the lines, but you want to customize the legend entries to use your own labels and colors.
🎯 Goal: Build a line chart with two lines and add a custom legend with your own labels and colors that do not depend on the plotted lines' default labels.
📋 What You'll Learn
Create two lists of sales data for Product A and Product B for four quarters.
Create a list of quarter labels for the x-axis.
Plot the sales data for both products using matplotlib's plot function.
Create a custom legend with exactly two entries using matplotlib.patches.Patch for the legend handles.
Use the custom legend handles and labels in plt.legend().
Display the plot with plt.show().
💡 Why This Matters
🌍 Real World
Custom legends help make charts clearer and more professional, especially when default labels are not descriptive or when you want to highlight specific information.
💼 Career
Data scientists and analysts often customize legends in reports and presentations to improve communication and make visualizations easier to understand.
Progress0 / 4 steps
1
Create sales data and quarter labels
Create a list called quarters with values ["Q1", "Q2", "Q3", "Q4"]. Create two lists called sales_a and sales_b with values [150, 200, 250, 300] and [180, 210, 260, 310] respectively.
Matplotlib
Need a hint?

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

2
Plot sales data lines
Import matplotlib.pyplot as plt. Use plt.plot() to plot sales_a and sales_b against quarters. Use colors "blue" for sales_a and "green" for sales_b. Do not add labels to the plot lines.
Matplotlib
Need a hint?

Use plt.plot(x, y, color="colorname") to plot lines with specific colors.

3
Create custom legend handles
Import matplotlib.patches.Patch. Create two variables blue_patch and green_patch as Patch objects with colors "blue" and "green" respectively. These will be used as custom legend handles.
Matplotlib
Need a hint?

Use Patch(color="colorname") to create a colored patch for the legend.

4
Add custom legend and display plot
Use plt.legend() with handles=[blue_patch, green_patch] and labels=["Product A Sales", "Product B Sales"] to add a custom legend. Then call plt.show() to display the plot.
Matplotlib
Need a hint?

Use plt.legend(handles=[...], labels=[...]) to create a custom legend. Then call plt.show() to display the plot.