Last active
March 5, 2025 17:42
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See the Legend Guide for more ideas and explanation.