Miguel
Miguel

Reputation: 122

Adding a legend entry with two curves on same entry, python matplotlib

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.

Example graph 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.

Upvotes: 0

Views: 497

Answers (1)

Mr. T
Mr. T

Reputation: 12410

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()

Sample output: enter image description here

Upvotes: 1

Related Questions