Based on the question and answer here (Line plus shaded region for error band in matplotlib's legend and similar to Combined legend entry for plot and fill_between) I was able to create a legend entry which combines a line and patch elements.
In my use-case I need to plot multiple of these. When I do, I only get a legend entry for the last line+patch combination.
import numpy as np
import matplotlib.pyplot as plt
def plot(x, y, ax, col, group, **kwargs):
hline, = ax.plot(x, y, 'k--', color=col)
hpatch = ax.fill_between(x, y+10, y-10, color=col, alpha=0.5)
ax.legend([(hline, hpatch)], [f"group {group}: Mean + interval"])
fig, ax = plt.subplots()
x = np.linspace(1, 100, 100)
plot(x, x, ax, "C0", 1)
plot(x, x+30, ax, "C1", 2)
plot(x, x+60, ax, "C2", 3)
Note the presence of only the final (group 3) entry in the legend.
Is there a way to get all line/path groups included in the legend so that (in this case) there are 3 items in the legend?
Bonus points if this can be handled entirely within the plot
function, avoiding having to pass out handles from the plot function.
This question is not asking about multiple separate legends.