8000 Annotation legend by jlecoeur · Pull Request #8292 · matplotlib/matplotlib · GitHub
[go: up one dir, main page]

Skip to content

Annotation legend #8292

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 13 commits into from
Closed
Show file tree
Hide file tree
Changes from 6 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
3 changes: 2 additions & 1 deletion lib/matplotlib/axes/_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,8 @@ def _get_legend_handles(self, legend_handler_map=None):

"""
handles_original = (self.lines + self.patches +
self.collections + self.containers)
self.collections + self.containers +
self.texts)
handler_map = mlegend.Legend.get_default_handler_map()

if legend_handler_map is not None:
Expand Down
8 changes: 6 additions & 2 deletions lib/matplotlib/legend.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@
from matplotlib.cbook import is_string_like, silent_list, is_hashable
from matplotlib.font_manager import FontProperties
from matplotlib.lines import Line2D
from matplotlib.patches import Patch, Rectangle, Shadow, FancyBboxPatch
from matplotlib.patches import Patch, Rectangle, Shadow, FancyBboxPatch, FancyArrowPatch
from matplotlib.text import Text, Annotation
from matplotlib.collections import (LineCollection, RegularPolyCollection,
CircleCollection, PathCollection,
PolyCollection)
Expand Down Expand Up @@ -493,7 +494,10 @@ 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(),
Text:legend_handler.HandlerText(),
FancyArrowPatch:legend_handler.HandlerFancyArrowPatch(),
Annotation:legend_handler.HandlerAnnotation(),
}

# (get|set|update)_default_handler_maps are public interfaces to
Expand Down
103 changes: 95 additions & 8 deletions lib/matplotlib/legend_handler.py
10000
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,13 @@ 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.patches import Rectangle, FancyArrowPatch
from matplotlib.text import Text, Annotation
import matplotlib.collections as mcoll
import matplotlib.colors as mcolors



def update_from_first_child(tgt, src):
tgt.update_from(src.get_children()[0])

Expand Down Expand Up @@ -256,6 +258,21 @@ def create_artists(self, legend, orig_handle,
return [p]


class HandlerFancyArrowPatch(HandlerPatch):
"""
Handler for FancyArrowPatch instances.
"""
def _create_patch(self, legend, orig_handle,
xdescent, ydescent, width, height, fontsize):
arrow = FancyArrowPatch( [-xdescent,
-ydescent + height / 2],
[-xdescent + width,
-ydescent + height / 2],
mutation_scale=width / 3)
arrow.set_arrowstyle(orig_handle.get_arrowstyle())
return arrow


class HandlerLineCollection(HandlerLine2D):
"""
Handler for LineCollection instances.
Expand Down Expand Up @@ -578,18 +595,25 @@ class HandlerTuple(HandlerBase):
The number of sections to divide the legend area into. If None,
use the length of the input tuple. Default is 1.


pad : float, optional
If None, fall back to `legend.borderpad` as the default.
In units of fraction of font size. Default is None.


width_ratios : tuple, optional
The relative width of sections. Must be of length ndivide.
If None, all sections will have the same width. Default is None.

"""
def __init__(self, ndivide=1, pad=None, **kwargs):
def __init__(self, ndivide=1, pad=None, width_ratios=None, **kwargs):

self._ndivide = ndivide
self._pad = pad

if (width_ratios is not None) and (len(width_ratios) == ndivide):
self._width_ratios = width_ratios
else:
self._width_ratios = None

HandlerBase.__init__(self, **kwargs)

def create_artists(self, legend, orig_handle,
Expand All @@ -608,10 +632,16 @@ def create_artists(self, legend, orig_handle,
else:
pad = self._pad * fontsize

if ndivide > 1:
width = (width - pad*(ndivide - 1)) / ndivide
if self._width_ratios is not None:
sumratios = sum(self._width_ratios)
widths = [(width - pad * (ndivide - 1)) * ratio / sumratios
for ratio in self._width_ratios]
else:
widths = [(width - pad * (ndivide - 1)) / ndivide
for _ in range(ndivide)]
widths_cycle = cycle(widths)

xds = [xdescent - (width + pad) * i for i in range(ndivide)]
xds = [xdescent - (widths[-i-1] + pad) * i for i in range(ndivide)]
xds_cycle = cycle(xds)

a_list = []
Expand All @@ -620,7 +650,8 @@ def create_artists(self, legend, orig_handle,
_a_list = handler.create_artists(legend, handle1,
six.next(xds_cycle),
ydescent,
width, height,
six.next(widths_cycle),
height,
fontsize,
trans)
a_list.extend(_a_list)
Expand Down Expand Up @@ -661,3 +692,59 @@ 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 instances.
"""
def create_artists(self, legend, orig_handle,
xdescent, ydescent, width, height, fontsize, trans):
t = Text(x=-xdescent + width / 3,
y=-ydescent + height / 4,
text="a")

# Use original text if it is short
text = orig_handle.get_text()
if len(text) < 2:
t.set_text(text)

# Copy text attributes, except fontsize
self.update_prop(t, orig_handle, legend)
t.set_transform(trans)
t.set_fontsize(2 * fontsize / 3)

return [t]


class HandlerAnnotation(HandlerBase):
"""
Handler for FancyArrowPatch instances.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FancyArrowPatch <- Annotation?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed!

"""
def create_artists(self, legend, orig_handle,
xdescent, ydescent, width, height, fontsize, trans):
if (orig_handle.arrow_patch is not None) and (orig_handle.get_text() is not ""):
# Draw a tuple (text, arrow)
handler = HandlerTuple(ndivide=2, pad=None, width_ratios=[1,4])

# Create a Text instance from annotation text
text_handle = Text(text=orig_handle.get_text())
text_handle.update_from(orig_handle)
handle = (text_handle, orig_handle.arrow_patch)
elif orig_handle.arrow_patch is not None:
# Arrow without text
handler = HandlerFancyArrowPatch()
handle = orig_handle.arrow_patch
elif orig_handle.get_text() is not "":
# Text without arrow
handler = HandlerText()
handle = orig_handle
else:
# No text, no arrow
handler = HandlerPatch()
handle = Rectangle(xy=[0,0],width=0,height=0,color='w')

return handler.create_artists(legend, handle,
xdescent, ydescent,
width, height,
fontsize, trans)
0