Fine-Tune Your Matplotlib Legends for Perfect Plots
Legend is an essential component of a Matplotlib axis, used to identify and differentiate various elements within a plot.
A legend is generated by ax.legend()
or plt.legend()
function.
This article demonstrates several arguments for these functions
that allow precise control over the legend's appearance.
Legend Location: loc
Use legend(loc=)
to specify the location of the legend.
Can be either accurate coordinates or string.
For example: ax.legend(loc=(0, 0.5))
or ax.legend("upper left")
.
fig, axes = plt.subplots(1, 3, figsize=(8, 3))
for i, ax in enumerate(axes):
ax.set_ylim(-2, 1.1)
for y in ys:
axes[i].plot(x, y)
axes[i].legend([f"i={i}" for i in range(5)], loc=(i/3, i/3))
plt.tight_layout()
Legend at different locations.
Font size: fontsize
Use legend(fontsize=)
to specify the font size.
fig, axes = plt.subplots(1, 3, figsize=(8, 3))
for i, ax in enumerate(axes):
ax.set_ylim(-2, 1.1)
for y in ys:
axes[i].plot(x, y)
axes[i].legend([f"i={i}" for i in range(5)], loc=(0, 0), fontsize=8+i*3)
plt.tight_layout()
Legend with various font sizes.
Number of Columns: ncol
fig, axes = plt.subplots(1, 3, figsize=(8, 3))
for i, ax in enumerate(axes):
ax.set_ylim(-2, 1.1)
for y in ys:
axes[i].plot(x, y)
axes[i].legend([f"i={i}" for i in range(5)], loc=(0, 0), ncol=i+1)
plt.tight_layout()
Legends of different columns.
Row spacing: labelspacing
fig, axes = plt.subplots(1, 3, figsize=(8, 3))
for i, ax in enumerate(axes):
ax.set_ylim(-2, 1.1)
for y in ys:
axes[i].plot(x, y)
axes[i].legend([f"i={i}" for i in range(5)], loc=(0, 0), ncol=2, labelspacing=2*i)
plt.tight_layout()
Adjust the spacing between columns.
Column Spacing: columnspacing
fig, axes = plt.subplots(1, 3, figsize=(8, 3))
for i, ax in enumerate(axes):
ax.set_ylim(-2, 1.1)
for y in ys:
axes[i].plot(x, y)
axes[i].legend([f"i={i}" for i in range(5)], loc=(0, 0), ncol=2, columnspacing=2*i)
plt.tight_layout()
Adjust the spacing between columns.
Handle Length: handlelength
fig, axes = plt.subplots(1, 3, figsize=(8, 3))
for i, ax in enumerate(axes):
ax.set_ylim(-2, 1.1)
for y in ys:
axes[i].plot(x, y)
axes[i].legend([f"i={i}" for i in range(5)], loc=(0, 0), ncol=2, handlelength=i+1)
plt.tight_layout()
Adjust handle length.
Space Between Handle and Text: handletextpad
fig, axes = plt.subplots(1, 3, figsize=(8, 3))
for i, ax in enumerate(axes):
ax.set_ylim(-2, 1.1)
for y in ys:
axes[i].plot(x, y)
axes[i].legend([f"i={i}" for i in range(5)], loc=(0, 0), ncol=2, handletextpad=i)
plt.tight_layout()
Space between handle and text.