Skip to content

Legend annotation #10802

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions lib/matplotlib/legend.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
import matplotlib.colors as colors
from matplotlib.font_manager import FontProperties
from matplotlib.lines import Line2D
from matplotlib.text import Annotation
from matplotlib.patches import Patch, Rectangle, Shadow, FancyBboxPatch
from matplotlib.collections import (LineCollection, RegularPolyCollection,
CircleCollection, PathCollection,
Expand Down Expand Up @@ -815,7 +816,8 @@ def _approx_text_height(self, renderer=None):
update_func=legend_handler.update_from_first_child),
tuple: legend_handler.HandlerTuple(),
PathCollection: legend_handler.HandlerPathCollection(),
PolyCollection: legend_handler.HandlerPolyCollection()
PolyCollection: legend_handler.HandlerPolyCollection(),
Annotation: legend_handler.HandlerAnnotation()
}

# (get|set|update)_default_handler_maps are public interfaces to
Expand Down Expand Up @@ -1307,12 +1309,12 @@ def _get_legend_handles(axs, legend_handler_map=None):
"""
handles_original = []
for ax in axs:
handles_original += (ax.lines + ax.patches +
handles_original += (ax.lines + ax.patches + ax.texts +
ax.collections + ax.containers)
# support parasite axes:
if hasattr(ax, 'parasites'):
for axx in ax.parasites:
handles_original += (axx.lines + axx.patches +
handles_original += (axx.lines + axx.patches + ax.texts +
axx.collections + axx.containers)

handler_map = Legend.get_default_handler_map()
Expand Down
66 changes: 65 additions & 1 deletion lib/matplotlib/legend_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ def legend_artist(self, legend, orig_handle, fontsize, handlebox):
import numpy as np

from matplotlib.lines import Line2D
from matplotlib.patches import Rectangle
from matplotlib.text import Text, Annotation
from matplotlib.patches import Rectangle, FancyArrowPatch
import matplotlib.collections as mcoll
import matplotlib.colors as mcolors

Expand Down Expand Up @@ -728,3 +729,66 @@ def create_artists(self, legend, orig_handle,
self.update_prop(p, orig_handle, legend)
p.set_transform(trans)
return [p]


class HandlerText(HandlerBase):
"""
Handler for ".Text" which are used by ".Annotations".
"""
def create_artists(self, legend, orig_handle, xdescent, ydescent, width,
height, fontsize, trans):
p = Text(x=-xdescent, y=-ydescent,
text=orig_handle.get_text())
self.update_prop(p, orig_handle, legend)
p.set_transform(trans)
p.set_fontsize(0.75*fontsize)
c = Rectangle(xy=(-xdescent, -ydescent - (height/5)), width=width, height=7*height/5,
facecolor="none", edgecolor="none")
c.set_transform(trans)
p.set_clip_path(c)
return[p]


class HandlerFancyArrowPatch(HandlerBase):
"""
Handler for ".FancyArrow" which are used by ".Annotations".
"""
def update_prop(self, legend_handle, orig_handle, legend):
self._update_prop(legend_handle, orig_handle)
legend_handle.set_arrowstyle(orig_handle.get_arrowstyle())
legend_handle.set_linestyle(orig_handle.get_linestyle())
legend_handle.set_mutation_aspect(orig_handle.get_mutation_aspect())

def create_artists(self, legend, orig_handle, xdescent, ydescent, width,
height, fontsize, trans):

p = FancyArrowPatch(posA=(-xdescent - (width/10), -ydescent +
height/2),
posB=(-xdescent + width + (width/10), -ydescent +
height/2),
mutation_scale=height*1.5)
self.update_prop(p, orig_handle, legend)
p.set_transform(trans)
return [p]


class HandlerAnnotation(HandlerBase):
"""
Handler for ".Annotation" instances.
"""
def create_artists(self, legend, orig_handle, xdescent, ydescent, width,
height, fontsize, trans):
if (orig_handle.arrow_patch is not None):
arrow_handler = HandlerFancyArrowPatch()
p = arrow_handler.create_artists(legend, orig_handle.arrow_patch,
xdescent, ydescent, width, height,
fontsize, trans)
elif (orig_handle.get_text() != ""):
text_handler = HandlerText()
p = text_handler.create_artists(legend, orig_handle, xdescent,
ydescent, width, height, fontsize,
trans)
else:
p = [Rectangle(xy=(-xdescent, -ydescent), width=width,
height=height, facecolor="none", edgecolor="none")]
return p
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
230 changes: 230 additions & 0 deletions lib/matplotlib/tests/test_legend.py
Original file line number Diff line number Diff line change
Expand Up @@ -522,3 +522,233 @@ def test_legend_title_empty():
leg = ax.legend()
assert leg.get_title().get_text() == ""
assert leg.get_title().get_visible() is False


@image_comparison(baseline_images=['simple_annotation'],
extensions=['png'])
def test_simple_annotation():
# tests that a simple example graph with annotations
# appear on the legend with their image and label
x = np.arange(0.0, 15.0, 0.01)
y = np.sin(0.3*np.pi*x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y, lw=2, label="sin(x)")
ax.annotate("",
xy=(1.6, 1.03),
xytext=(8.4, 1.03),
arrowprops={'arrowstyle':'<->'},
label="wavelength")
ax.annotate("",
xy=(8.4, 0),
xytext=(8.35, 1.0),
arrowprops={'arrowstyle':'<->', 'ls':'dashed'},
label="amplitude")
ax.set_ylim(-1.5, 1.5)
ax.legend()
plt.show()


@image_comparison(baseline_images=['all_linestyles'],
extensions=['png'])
def test_all_linestyles():
# tests that annotations with different linestyles
# appear on the legend with their image and label
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlim(0, 1.7)
ax.annotate("",
xy=(0.1, 0.1),
xytext=(0.1, 0.9),
arrowprops={'arrowstyle':'-', 'ls':'solid'},
label="solid")
ax.annotate("",
xy=(0.3, 0.1),
xytext=(0.3, 0.9),
arrowprops={'arrowstyle':'-', 'ls':'dashed'},
label="dashed")
ax.annotate("",
xy=(0.5, 0.1),
xytext=(0.5, 0.9),
arrowprops={'arrowstyle':'-', 'ls':'dashdot'},
label="dashdot")
ax.annotate("",
xy=(0.7, 0.1),
xytext=(0.7, 0.9),
arrowprops={'arrowstyle':'-', 'ls':'dotted'},
label="dotted")
ax.annotate("",
xy=(0.9, 0.1),
xytext=(0.9, 0.9),
arrowprops={'arrowstyle':'-', 'ls':(0, (1,5))},
label="offset, on-off-dash-seq")
ax.legend()
plt.show()


@image_comparison(baseline_images=['all_arrowstyles'],
extensions=['png'])
def test_all_arrowstyles():
# tests that annotations with different arrowstyles
# appear on the legend with their image and label
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_ylim(0, 2.5)
ax.annotate("",
xy=(0.1, 0.1),
xytext=(0.5, 0.1),
arrowprops={'arrowstyle':'-'},
label="-")
ax.annotate("",
xy=(0.1, 0.3),
xytext=(0.5, 0.3),
arrowprops={'arrowstyle':'->'},
label="->")
ax.annotate("",
xy=(0.1, 0.5),
xytext=(0.5, 0.5),
arrowprops={'arrowstyle':'-['},
label="-[")
ax.annotate("",
xy=(0.1, 0.7),
xytext=(0.5, 0.7),
arrowprops={'arrowstyle':'|-|'},
label="|-|")
ax.annotate("",
xy=(0.1, 0.9),
xytext=(0.5, 0.9),
arrowprops={'arrowstyle':'-|>'},
label="-|>")
ax.annotate("",
xy=(0.1, 1.1),
xytext=(0.5, 1.1),
arrowprops={'arrowstyle':'<-'},
label="<-")
ax.annotate("",
xy=(0.1, 1.3),
xytext=(0.5, 1.3),
arrowprops={'arrowstyle':'<->'},
label="<->")
ax.annotate("",
xy=(0.1, 1.5),
xytext=(0.5, 1.5),
arrowprops={'arrowstyle':'<|-'},
label="<|-")
ax.annotate("",
xy=(0.1, 1.7),
xytext=(0.5, 1.7),
arrowprops={'arrowstyle':'<|-|>'},
label="<|-|>")
ax.annotate("",
xy=(0.1, 1.9),
xytext=(0.5, 1.9),
arrowprops={'arrowstyle':'fancy'},
label="fancy")
ax.annotate("",
xy=(0.1, 2.1),
xytext=(0.5, 2.1),
arrowprops={'arrowstyle':'simple'},
label="simple")
ax.annotate("",
xy=(0.1, 2.3),
xytext=(0.5, 2.3),
arrowprops={'arrowstyle':'wedge'},
label="wedge")
ax.legend()
plt.show()


@image_comparison(baseline_images=['annotation_colours'],
extensions=['png'])
def test_annotation_colours():
# tests that annotations with different colors
# appear on the legend with their image and label
fig = plt.figure()
ax = fig.add_subplot(111)
ax.annotate("",
xy=(0.1, 0.1),
xytext=(0.1, 0.9),
arrowprops={'arrowstyle':'<|-|>',
'ls':'solid',
'color':'blue'},
label="blue")
ax.annotate("",
xy=(0.2, 0.1),
xytext=(0.2, 0.9),
arrowprops={'arrowstyle':'-',
'ls':'dashed',
'color':'red'},
label="red")
ax.annotate("",
xy=(0.3, 0.1),
xytext=(0.3, 0.9),
arrowprops={'arrowstyle':'|-|',
'ls':'dashdot',
'color':'yellow'},
label="yellow")
ax.legend()
plt.show()


@image_comparison(baseline_images=['annotation_text'],
extensions=['png'])
def test_annotation_text():
# tests that annotations with different texts
# appear on the legend with their image and label
# note: the text itself does not appear on the legend,
# only the arrow. The text itself is self-explanatory.
# However, if only text is passed, the image will be
# the text.
fig = plt.figure()
ax = fig.add_subplot(111)
ax.annotate("hello",
xy=(0.1, 0.9),
xytext=(0.1, 0.1),
arrowprops={'arrowstyle':'-',
'ls':'dashed',
'color':'green'},
label="hello")
ax.annotate("world",
xy=(0.3, 0.9),
xytext=(0.3, 0.1),
arrowprops={'arrowstyle':'<->',
'ls':'dashdot',
'color':'purple'},
label="world")
ax.annotate("short text",
xy=(0.5, 0.9),
xytext=(0.5, 0.1),
label="short text")
ax.annotate("long text",
xy=(0.7, 0.9),
xytext=(0.7, 0.1),
label="long text")

ax.legend()
plt.show()


@image_comparison(baseline_images=['annotation_no_line_text'],
extensions=['png'])
def test_annotation_no_line_text():
# tests that annotations with no line, text, or both
# appear on the legend with their image and label
# note: if no text, it will not appear in the legend
fig = plt.figure()
ax = fig.add_subplot(111)
ax.annotate("",
xy=(0.1, 0.9),
xytext=(0.1, 0.1),
arrowprops={'arrowstyle':'-',
'ls':'dashed'},
label="no text")
ax.annotate("no line",
xy=(0.3, 0.1),
xytext=(0.3, 0.9),
label="no line")
ax.annotate("",
xy=(0.5, 0.1),
xytext=(0.5, 0.9),
label="no line or text")
ax.legend()
plt.show()