18

I would like to know how it is possible to label an arrow and show it in the legend of a plot.

For instance if I do this

 arrow(0,1,'dummy',label='My label')

 legend()

I do not see anything in the legend. I would like to see in the legend box an arrow next to its label.

Brian
  • 13,996
  • 19
  • 70
  • 94

2 Answers2

16

You can add arbitrary artists to the legend command, as explained here

import matplotlib.pyplot as plt

f = plt.figure()
arrow = plt.arrow(0, 0, 0.5, 0.6, 'dummy',label='My label')
plt.legend([arrow,], ['My label',])

The arrow artist does not allow a marker parameter, so you'll need to do some additional manual tinkering to replace the marker in the legend.

EDIT

To get the custom marker you need to define your own handler_map. The following code is inspired in the example here:

from matplotlib.legend_handler import HandlerPatch
import matplotlib.patches as mpatches

def make_legend_arrow(legend, orig_handle,
                      xdescent, ydescent,
                      width, height, fontsize):
    p = mpatches.FancyArrow(0, 0.5*height, width, 0, length_includes_head=True, head_width=0.75*height )
    return p

f = plt.figure(figsize=(10,6))
arrow = plt.arrow(0,0, 0.5, 0.6, 'dummy', label='My label', )
plt.legend([arrow], ['My label'], handler_map={mpatches.FancyArrow : HandlerPatch(patch_func=make_legend_arrow),
                    })
Javier
  • 722
  • 4
  • 14
  • 1
    thank you, but this only partly answer to my question. The thing is that I would like to have an arrow as the marker. – Brian Mar 12 '14 at 11:17
  • 1
    That's cool. How to annotate both an up and down arrow in the legend? – zyxue Jan 18 '17 at 16:33
  • Alternatively, is it possible to get the label from `legend` or `orig_handle` in the arguments passed to the function? I checked `.get_lablel()`, but it returns empty string, why? – zyxue Jan 18 '17 at 16:51
  • In this example, some FacyArrow arguments don't seem to have an effect, such as fc, ec, alpha: the arrow is always show in in default color. Why is that? – tiagoams Oct 07 '21 at 09:37
9

You can add any latex symbol as a marker. For example: for an arrow pointing down you can specify:

scatter( x ,y, c='purple',marker=r'$\downarrow$',s=20, label='arrow' )
KeithB
  • 243
  • 2
  • 6
firefly
  • 953
  • 2
  • 11
  • 18