'Missing Labels from Legend With Subplots
I'm trying to plot multiple things in a figure with subplots. When I try generating a legend for the figure, it is only showing labels for the data in the very last subplot, instead of for the entire figure.
fig, axs = plt.subplots(3, 2, figsize=(16,18))
first_pops = {"M71 (Masseron)":[1., "purple"], \
"6273 (Yong)":[0.1, "yellowgreen"], \
"2419 (Carretta)":[0.0, "olive"], \
"6218 (Carretta)":[0.25, "darkcyan"],
}
elements = ["O I", "Na I", "Mg I", "Si I", "Ti I", "Ca I"]
element_labels = ["[O/Fe]", "[Na/Fe]", "[Mg/Fe]", "[Si/Fe]", "[Ti/Fe]", "[Ca/Fe]"]
for k, ax in enumerate(axs.ravel()):
element = elements[k]
element_label = element_labels[k]
for GC in first_pops.keys():
try:
plot_background_stars(glob_dict[GC]["[Fe/H]"],\
glob_dict[GC][element_label],\
label = GC, ax=ax, color = first_pops[GC][1],\
s = 140, marker="*", facecolors='none', linewidth=2)
except KeyError:
print(GC+" doesn't have "+element+" measured")
ax.set_xlabel("[Fe/H]")
ax.set_ylabel(element_label)
handles, labels = fig.gca().get_legend_handles_labels()
by_label = dict(zip(labels, handles))
fig.legend(by_label.values(), by_label.keys())
I've tried replacing "fig" with "plt" and vice versa.
I'm using the following to plot each data set:
def plot_background_stars(x, y, ax=None, **plt_kwargs):
if ax is None:
ax = plt.gca()
ax.scatter(x, y, **plt_kwargs)
return(ax)
The resulting legend has just two of the plotted colors, instead of four. Like maybe it's only pulling the labels from the last subplot? But why would it do that?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

