Skip to content

Instantly share code, notes, and snippets.

@rcomer
Last active March 5, 2025 17:42
Show Gist options
  • Save rcomer/8865353da4d1bccdac5d51a11b25f504 to your computer and use it in GitHub Desktop.
Save rcomer/8865353da4d1bccdac5d51a11b25f504 to your computer and use it in GitHub Desktop.
Make a single legend entry for a contourf plot by stacking proxy artists together. Proposed solution for https://stackoverflow.com/questions/77842076
import matplotlib.pyplot as plt
import matplotlib.lines as mlines
import numpy as np
x, y = np.meshgrid(np.arange(10),np.arange(10))
z = np.sqrt(x**2 + y**2)
fig, ax = plt.subplots()
cs = ax.contourf(x,y,z,levels=[2,3,4,6])
colors = cs.get_facecolors()
proxies = []
for size, color in enumerate(colors, 1):
proxies.append(
mlines.Line2D([], [], color=color, marker='o', ls='none', markersize=size))
proxies.reverse() # Put smallest marker on top
ax.legend(handles=[tuple(proxies)], labels=['My Contour'], borderpad=1.5, markerscale=10)
plt.show()
@rcomer
Copy link
Author

rcomer commented Jan 19, 2024

See the Legend Guide for more ideas and explanation.

@rcomer
Copy link
Author

rcomer commented Jan 19, 2024

Output:

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment