Issue
I would like to have a legend like the one appearing on the plot below: As you can see the legend entry shows the red line and the blue line on the same entry.
PD: In my case, the red line is always the same curve, a horizontal straight line.
How can I do this? I have tried with the examples in this guide, but they do not apply to my case, since I do not find a "handlebox artist" which applies to my case.
Edit: I have tried to apply @Mr.T answer, but in my case I am plotting the blue plot as a bar plot in matplotlib, and I get the following error AttributeError: 'BarContainer' object has no attribute '_transform'
.
What I am doing is
blue_bars = axes[i].bar(bins[:-1], Wi, width = binsize, label = label_W)
red_line = axes[i].hlines(0, tstart, tstop, color='red', linewidth = 0.8)
axes[i].legend([red_line, blue_bars], labels = label_W,
handler_map={blue_bars: HandlerLine2D(numpoints=5)},
loc='upper right')
Note that I am creating several subplots in the same axes object, within a for loop that iterates over the variable i
. This works with no problem.
Solution
Based on the linked examples, we can construct a legend entry from scratch as you did not tell us how you plot the graph:
import matplotlib.pyplot as plt
import matplotlib.lines as mlines
from matplotlib.legend_handler import HandlerLine2D
fig, ax = plt.subplots()
red_hline = mlines.Line2D([], [], color="red")
blue_uptick = mlines.Line2D([], [], color="blue", lw=0, marker=2, markersize=5)
orange_downtick = mlines.Line2D([], [], color="orange", lw=0, marker=3, markersize=5)
ax.legend(handles=[(red_hline, blue_uptick), (red_hline, orange_downtick)],
labels=["the ups", "and the downs"],
handler_map={blue_uptick: HandlerLine2D(numpoints=5), orange_downtick: HandlerLine2D(numpoints=3)})
plt.show()
Answered By - Mr. T
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.