Skip to content

Instantly share code, notes, and snippets.

@cfperez
Created August 14, 2018 21:50
Show Gist options
  • Save cfperez/4a6ca616134262f6d3a40ea1c0bd52af to your computer and use it in GitHub Desktop.
Save cfperez/4a6ca616134262f6d3a40ea1c0bd52af to your computer and use it in GitHub Desktop.
Ways to combine legends in matplotlib
def combined_legend(*axes):
"""Creates combines legends from provided axes.
Usually used for ax and ax.twinx()
"""
lines, labels = [], []
for ax in axes:
line, label = ax.get_legend_handles_labels()
lines.extend(line)
labels.extend(label)
ax.legend(lines, labels)
# E.g., combined_legend(ax, ax.twinx())
# Or use a figure caption in mpl >= 2.1
# https://stackoverflow.com/a/47370214/1612867
# In general, position specified by loc should match bbox_to_anchor
# in terms of its relative position (upper left, upper right, etc.)
# Upper right
plt.gcf().legend(loc=1, bbox_to_anchor=(1,1), bbox_transform=ax.transAxes);
# Upper left
plt.gcf().legend(loc=2, bbox_to_anchor=(0,1), bbox_transform=ax.transAxes);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment