Bird
Raised Fist0
Matplotlibdata~10 mins

Legend placement and styling in Matplotlib - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Legend placement and styling
Create plot with data
↓
Add legend with default placement
↓
Choose legend location
↓
Apply styling options
↓
Display plot with styled legend
The flow shows creating a plot, adding a legend, choosing where to place it, styling it, and then displaying the final plot.
Execution Sample
Matplotlib
import matplotlib.pyplot as plt
plt.plot([1,2,3], label='Line 1')
plt.legend(loc='upper left', fontsize=10, shadow=True)
plt.show()
This code plots a line, adds a legend at the upper left with font size 10 and shadow, then shows the plot.
Execution Table
StepActionLegend LocationFont SizeShadowResult
1Plot line with labelNoneDefaultFalseLine plotted, no legend yet
2Add legend with loc='upper left'upper leftDefaultFalseLegend appears at upper left
3Set fontsize=10upper left10FalseLegend font size changed
4Enable shadow=Trueupper left10TrueLegend shadow enabled
5Show plotupper left10TruePlot displayed with styled legend
💡 Plot displayed with legend placed and styled as specified
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4Final
legend_locationNoneNoneupper leftupper leftupper leftupper left
legend_fontsizeDefaultDefaultDefault101010
legend_shadowFalseFalseFalseFalseTrueTrue
Key Moments - 3 Insights
Why does the legend not appear until plt.legend() is called?
The legend is created and shown only when plt.legend() is called, as shown in execution_table step 2 where the legend location changes from None to 'upper left'.
How does changing the 'loc' parameter affect the legend?
Changing 'loc' moves the legend to different positions on the plot, as seen in step 2 where 'upper left' places the legend in the top-left corner.
What effect does setting shadow=True have?
Setting shadow=True adds a shadow behind the legend box, making it visually distinct, as shown in step 4 where shadow changes from False to True.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the legend location after step 3?
ANone
Blower right
Cupper left
Dcenter
💡 Hint
Check the 'Legend Location' column in the execution_table at step 3
At which step does the legend shadow become enabled?
AStep 2
BStep 4
CStep 3
DStep 5
💡 Hint
Look at the 'Shadow' column in the execution_table to see when it changes to True
If we remove the fontsize parameter, what would be the font size after step 3?
ADefault
B10
CShadowed
DNone
💡 Hint
Refer to the 'Font Size' column in execution_table and variable_tracker for default values
Concept Snapshot
matplotlib legend placement and styling:
- Use plt.legend(loc='position') to place legend (e.g., 'upper left')
- Customize font size with fontsize=number
- Add shadow with shadow=True
- Call plt.legend() after plotting data
- Show plot with plt.show()
Full Transcript
This visual execution traces how to place and style a legend in matplotlib. First, a line plot is created with a label. Then plt.legend() is called with location 'upper left' to place the legend. Next, the font size is set to 10, and shadow is enabled. Finally, the plot is displayed showing the styled legend. Variables like legend location, font size, and shadow state change step-by-step. Key moments clarify why the legend appears only after plt.legend(), how location affects placement, and what shadow does. Quiz questions test understanding of legend location, shadow enabling step, and default font size behavior.

Practice

(1/5)
1. What does the loc parameter control in a matplotlib legend?
easy
A. The type of plot line used
B. The color of the legend text
C. The size of the plot markers
D. The position of the legend on the plot

Solution

  1. Step 1: Understand the role of loc in legend

    The loc parameter specifies where the legend appears on the plot, such as 'upper right' or 'lower left'.
  2. Step 2: Differentiate from other styling options

    Other options control color, size, or line style, but loc only controls position.
  3. Final Answer:

    The position of the legend on the plot -> Option D
  4. Quick Check:

    Legend position = loc [OK]
Hint: Remember: loc means location of legend [OK]
Common Mistakes:
  • Confusing loc with color or font size
  • Thinking loc changes plot markers
  • Assuming loc controls line style
2. Which of the following is the correct syntax to place a legend at the lower left corner in matplotlib?
easy
A. plt.legend(loc='lower left')
B. plt.legend(location='lower left')
C. plt.legend(loc='lower_left')
D. plt.legend(position='lower left')

Solution

  1. Step 1: Identify the correct parameter name

    The correct parameter to set legend position is loc, not location or position.
  2. Step 2: Use the correct string value

    The valid string is 'lower left' with a space, not 'lower_left' with underscore.
  3. Final Answer:

    plt.legend(loc='lower left') -> Option A
  4. Quick Check:

    Correct syntax uses loc='lower left' [OK]
Hint: Use loc='lower left' exactly, no underscores [OK]
Common Mistakes:
  • Using 'location' instead of 'loc'
  • Using underscores instead of spaces
  • Using 'position' parameter which doesn't exist
3. What will be the effect of this code snippet?
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], label='Line A')
plt.plot([3, 2, 1], label='Line B')
plt.legend(loc='upper center', shadow=True, fontsize='small')
plt.show()
medium
A. Code will raise an error due to invalid fontsize
B. Legend appears at the top center with a shadow and small font
C. Legend appears inside the plot area without shadow
D. Legend appears at the bottom right with default font size

Solution

  1. Step 1: Analyze legend parameters

    The loc='upper center' places the legend at the top center. shadow=True adds a shadow behind the legend box. fontsize='small' sets the font size smaller than default.
  2. Step 2: Confirm no errors in parameters

    All parameters are valid and supported by matplotlib.
  3. Final Answer:

    Legend appears at the top center with a shadow and small font -> Option B
  4. Quick Check:

    loc + shadow + fontsize = top center, shadow, small font [OK]
Hint: Check loc for position, shadow=True adds shadow, fontsize sets text size [OK]
Common Mistakes:
  • Assuming fontsize='small' causes error
  • Confusing loc='upper center' with bottom right
  • Ignoring shadow parameter effect
4. Identify the error in this code snippet for legend placement:
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], label='A')
plt.plot([3, 2, 1], label='B')
plt.legend(loc='bottomright')
plt.show()
medium
A. plt.legend() must be called before plt.plot()
B. Missing label parameter in plot calls
C. The loc value 'bottomright' is invalid; should be 'lower right'
D. plt.show() is missing parentheses

Solution

  1. Step 1: Check the loc parameter value

    The valid location string is 'lower right', not 'bottomright'. 'bottomright' is not recognized by matplotlib.
  2. Step 2: Verify other parts of the code

    Labels are correctly set, plt.legend() can be called after plotting, and plt.show() has parentheses.
  3. Final Answer:

    The loc value 'bottomright' is invalid; should be 'lower right' -> Option C
  4. Quick Check:

    Valid loc strings = 'lower right' not 'bottomright' [OK]
Hint: Use exact loc strings like 'lower right', not 'bottomright' [OK]
Common Mistakes:
  • Using invalid loc strings
  • Thinking plt.legend() must come before plt.plot()
  • Forgetting parentheses in plt.show()
5. You want to place a legend outside the plot on the right side with a title 'Legend', font size 12, and a shadow. Which code snippet achieves this correctly?
hard
A. plt.legend(loc='center right', bbox_to_anchor=(1, 0.5), title='Legend', fontsize='12pt', shadow=True)
B. plt.legend(loc='right side', bbox_to_anchor=(1, 0.5), title='Legend', fontsize=12, shadow=True)
C. plt.legend(loc='center left', bbox_to_anchor=(1, 0.5), title='Legend', fontsize=12, shadow=True)
D. plt.legend(loc='outside right', bbox_to_anchor=(1, 0.5), title='Legend', fontsize=12, shadow=True)

Solution

  1. Step 1: Understand placing legend outside plot

    Using loc='center right' with bbox_to_anchor=(1, 0.5) places the legend outside on the right side centered vertically.
  2. Step 2: Check styling parameters

    Title 'Legend', font size 12 (string with units '12pt'), and shadow=True are correctly set. loc='right side' and loc='outside right' are invalid.
  3. Final Answer:

    plt.legend(loc='center right', bbox_to_anchor=(1, 0.5), title='Legend', fontsize='12pt', shadow=True) -> Option A
  4. Quick Check:

    loc + bbox_to_anchor + title + fontsize + shadow = correct legend outside right [OK]
Hint: Use loc='center right' with bbox_to_anchor=(1, 0.5) for outside right legend [OK]
Common Mistakes:
  • Using invalid loc like 'right side' or 'outside right'
  • Passing fontsize as integer without units
  • Forgetting bbox_to_anchor for outside placement
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard