Consider the following Python code using matplotlib. What will be the position of the legend relative to the plot?
import matplotlib.pyplot as plt plt.plot([1, 2, 3], label='Line 1') plt.plot([3, 2, 1], label='Line 2') plt.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.show()
Look at the bbox_to_anchor coordinates and the loc parameter.
The loc='center left' places the legend's center left point at the coordinates given by bbox_to_anchor=(1, 0.5). This means the legend is placed outside the plot on the right side, vertically centered.
Given the following code, how many entries will the legend display?
import matplotlib.pyplot as plt plt.plot([1, 2, 3], label='A') plt.plot([3, 2, 1]) plt.plot([2, 2, 2], label='B') plt.legend(loc='upper left', bbox_to_anchor=(1, 1)) plt.show()
Only lines with a label are shown in the legend.
Only the first and third lines have labels ('A' and 'B'), so the legend shows 2 entries.
Which code snippet correctly places the legend centered below the plot area?
Think about the legend anchor point and its position below the plot.
Using loc='upper center' with bbox_to_anchor=(0.5, -0.1) places the legend below the plot, centered horizontally. The ncol=2 arranges legend entries in two columns.
Examine the code below. The user wants the legend outside the plot on the right, but it appears inside. Why?
import matplotlib.pyplot as plt plt.plot([1, 2, 3], label='X') plt.legend(loc='right', bbox_to_anchor=(1, 0.5)) plt.show()
Consider what point of the legend loc='right' places at bbox_to_anchor.
loc='right' is valid, but it places the midpoint of the legend's right edge at bbox_to_anchor=(1, 0.5). This causes the legend to extend leftward into the plot area. To place the legend outside on the right, use loc='center left', which places the legend's left edge at the axes right edge.
You want to place the legend outside the plot on the right side without overlapping the plot content. Which approach is best?
Think about how to make space for the legend outside the plot area.
Placing the legend outside requires shrinking the plot area using plt.subplots_adjust so the plot and legend do not overlap. Just placing the legend outside without adjusting the plot area causes overlap.