0
0
Matplotlibdata~15 mins

Legend placement and styling in Matplotlib - Mini Project: Build & Apply

Choose your learning style9 modes available
Legend placement and styling
📖 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 clearly show which line belongs to which product. You will place the legend in a specific location and style it to make the chart easy to understand.
🎯 Goal: Build a line chart with two product sales lines, add a legend with labels, place the legend at the upper left corner, and style the legend with a shadow and a fancy box.
📋 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 both sales lines with labels for the legend.
Add a legend placed at the upper left corner.
Style the legend with a shadow and a fancy box.
Display the plot.
💡 Why This Matters
🌍 Real World
Legends help viewers understand which data lines or points represent which categories in charts, making reports and presentations clearer.
💼 Career
Data scientists and analysts often need to create clear visualizations with legends to communicate insights effectively to stakeholders.
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_product_a with values [150, 200, 250, 300] and sales_product_b with values [180, 210, 240, 310].
Matplotlib
Need a hint?

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

2
Plot sales lines with labels
Import matplotlib.pyplot as plt. Use plt.plot() to plot sales_product_a and sales_product_b against quarters. Add labels "Product A" and "Product B" to each line for the legend.
Matplotlib
Need a hint?

Use plt.plot(x, y, label="...") to add labels for the legend.

3
Add and style the legend
Add a legend to the plot using plt.legend(). Place the legend at the upper left corner by setting loc='upper left'. Style the legend with a shadow by setting shadow=True and a fancy box by setting fancybox=True.
Matplotlib
Need a hint?

Use plt.legend() with the parameters loc, shadow, and fancybox.

4
Display the plot
Use plt.show() to display the plot with the legend.
Matplotlib
Need a hint?

Call plt.show() to see the chart.