0
0
Matplotlibdata~15 mins

Legend outside the plot in Matplotlib - Mini Project: Build & Apply

Choose your learning style9 modes available
Legend outside the plot
📖 Scenario: You are creating a simple line chart to compare sales data for two products over four quarters. You want to make sure the legend explaining the lines is placed outside the main plot area so the chart looks clean and easy to read.
🎯 Goal: Build a line plot with two lines representing sales of two products. Place the legend outside the plot area on the right side.
📋 What You'll Learn
Create two lists named quarters and sales_product_a with exact values.
Create a list named sales_product_b with exact values.
Plot both sales lines with labels 'Product A' and 'Product B'.
Add a legend outside the plot on the right side using plt.legend with bbox_to_anchor and loc parameters.
Display the plot with plt.show().
💡 Why This Matters
🌍 Real World
Placing legends outside the plot is common in reports and dashboards to keep the chart area clean and readable.
💼 Career
Data analysts and scientists often need to create clear visualizations for presentations and reports, including customizing legend placement.
Progress0 / 4 steps
1
Create the sales data lists
Create a list called quarters with values ['Q1', 'Q2', 'Q3', 'Q4']. Create a list called sales_product_a with values [150, 200, 250, 300].
Matplotlib
Need a hint?

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

2
Add sales data for Product B
Create a list called sales_product_b with values [180, 220, 260, 310].
Matplotlib
Need a hint?

Make sure to use the exact list name and values.

3
Plot the sales lines with labels
Import matplotlib.pyplot as plt. Use plt.plot to plot quarters vs sales_product_a with label 'Product A'. Then plot quarters vs sales_product_b with label 'Product B'.
Matplotlib
Need a hint?

Use plt.plot(x, y, label='name') to add lines with labels.

4
Place the legend outside the plot and show it
Use plt.legend with loc='center left' and bbox_to_anchor=(1, 0.5) to place the legend outside the plot on the right side. Then call plt.show() to display the plot.
Matplotlib
Need a hint?

Use plt.legend(loc='center left', bbox_to_anchor=(1, 0.5)) to place the legend outside on the right.

Call plt.show() to display the plot.