GitHub Viewer
r"""
Patches are `.Artist`\s with a face color and an edge color.
"""
import functools
import inspect
import math
from numbers import Number, Real
import textwrap
from types import SimpleNamespace
from collections import namedtuple
from matplotlib.transforms import Affine2D
import numpy as np
import matplotlib as mpl
from . import (_api, artist, cbook, colors, _docstring, hatch as mhatch,
lines as mlines, transforms)
from .bezier import (
NonIntersectingPathException, get_cos_sin, get_intersection,
get_parallels, inside_circle, make_wedged_bezier2,
split_bezier_intersecting_with_closedpath, split_path_inout)
from .path import Path
from ._enums import JoinStyle, CapStyle
@_docstring.interpd
@_api.define_aliases({
"antialiased": ["aa"],
"edgecolor": ["ec"],
"facecolor": ["fc"],
"linestyle": ["ls"],
"linewidth": ["lw"],
})
class Patch(artist.Artist):
"""
A patch is a 2D artist with a face color and an edge color.
If any of *edgecolor*, *facecolor*, *linewidth*, or *antialiased*
are *None*, they default to their rc params setting.
"""
zorder = 1
# Whether to draw an edge by default. Set on a
# subclass-by-subclass basis.
_edge_default = False
def __init__(self, *,
edgecolor=None,
facecolor=None,
color=None,
linewidth=None,
linestyle=None,
antialiased=None,
hatch=None,
fill=True,
capstyle=None,
joinstyle=None,
hatchcolor=None,
edgegapcolor=None,
**kwargs):
"""
The following kwarg properties are supported
%(Patch:kwdoc)s
"""
super().__init__()
if linestyle is None:
linestyle = "solid"
if capstyle is None:
capstyle = CapStyle.butt
if joinstyle is None:
joinstyle = JoinStyle.miter
self._hatch_linewidth = mpl.rcParams['hatch.linewidth']
self._fill = bool(fill) # needed for set_facecolor call
if color is not None:
if edgecolor is not None or facecolor is not None:
_api.warn_external(
"Setting the 'color' property will override "
"the edgecolor or facecolor properties.")
self.set_color(color)
else:
self.set_edgecolor(edgecolor)
self.set_hatchcolor(hatchcolor)
self.set_facecolor(facecolor)
self._linewidth = 0
self._unscaled_dash_pattern = (0, None) # offset, dash
self._dash_pattern = (0, None) # offset, dash (scaled by linewidth)
self._gapcolor = None
self.set_linestyle(linestyle)
self.set_linewidth(linewidth)
self.set_antialiased(antialiased)
self.set_hatch(hatch)
self.set_capstyle(capstyle)
self.set_joinstyle(joinstyle)
self.set_edgegapcolor(edgegapcolor)
if len(kwargs):
self._internal_update(kwargs)
def get_verts(self):
"""
Return a copy of the vertices used in this patch.
If the patch contains Bézier curves, the curves will be interpolated by
line segments. To access the curves as curves, use `get_path`.
"""
trans = self.get_transform()
path = self.get_path()
polygons = path.to_polygons(trans)
if len(polygons):
return polygons[0]
return []
def _process_radius(self, radius):
if radius is not None:
return radius
if isinstance(self._picker, Number):
_radius = self._picker
else:
if self.get_edgecolor()[3] == 0:
_radius = 0
else:
_radius = self.get_linewidth()
return _radius
def contains(self, mouseevent, radius=None):
"""
Test whether the mouse event occurred in the patch.
Parameters
----------
mouseevent : `~matplotlib.backend_bases.MouseEvent`
Where the user clicked.
radius : float, optional
Additional margin on the patch in target coordinates of
`.Patch.get_transform`. See `.Path.contains_point` for further
details.
If `None`, the default value depends on the state of the object:
- If `.Artist.get_picker` is a number, the default
is that value. This is so that picking works as expected.
- Otherwise if the edge color has a non-zero alpha, the default
is half of the linewidth. This is so that all the colored
pixels are "in" the patch.
- Finally, if the edge has 0 alpha, the default is 0. This is
so that patches without a stroked edge do not have points
outside of the filled region report as "in" due to an
invisible edge.
Returns
-------
(bool, empty dict)
"""
if self._different_canvas(mouseevent):
return False, {}
radius = self._process_radius(radius)
codes = self.get_path().codes
if codes is not None:
vertices = self.get_path().vertices
# if the current path is concatenated by multiple sub paths.
# get the indexes of the starting code(MOVETO) of all sub paths
idxs, = np.where(codes == Path.MOVETO)
# Don't split before the first MOVETO.
idxs = idxs[1:]
subpaths = map(
Path, np.split(vertices, idxs), np.split(codes, idxs))
else:
subpaths = [self.get_path()]
inside = any(
subpath.contains_point(
(mouseevent.x, mouseevent.y), self.get_transform(), radius)
for subpath in subpaths)
return inside, {}
def contains_point(self, point, radius=None):
"""
Return whether the given point is inside the patch.
Parameters
----------
point : (float, float)
The point (x, y) to check, in target coordinates of
``.Patch.get_transform()``. These are display coordinates for patches
that are added to a figure or Axes.
radius : float, optional
Additional margin on the patch in target coordinates of
`.Patch.get_transform`. See `.Path.contains_point` for further
details.
If `None`, the default value depends on the state of the object:
- If `.Artist.get_picker` is a number, the default
is that value. This is so that picking works as expected.
- Otherwise if the edge color has a non-zero alpha, the default
is half of the linewidth. This is so that all the colored
pixels are "in" the patch.
- Finally, if the edge has 0 alpha, the default is 0. This is
so that patches without a stroked edge do not have points
outside of the filled region report as "in" due to an
invisible edge.
Returns
-------
bool
Notes
-----
The proper use of this method depends on the transform of the patch.
Isolated patches do not have a transform. In this case, the patch
creation coordinates and the point coordinates match. The following
example checks that the center of a circle is within the circle
>>> center = 0, 0
>>> c = Circle(center, radius=1)
>>> c.contains_point(center)
True
The convention of checking against the transformed patch stems from
the fact that this method is predominantly used to check if display
coordinates (e.g. from mouse events) are within the patch. If you want
to do the above check with data coordinates, you have to properly
transform them first:
>>> center = 0, 0
>>> c = Circle(center, radius=3)
>>> plt.gca().add_patch(c)
>>> transformed_interior_point = c.get_data_transform().transform((0, 2))
>>> c.contains_point(transformed_interior_point)
True
"""
radius = self._process_radius(radius)
return self.get_path().contains_point(point,
self.get_transform(),
radius)
def contains_points(self, points, radius=None):
"""
Return whether the given points are inside the patch.
Parameters
----------
points : (N, 2) array
The points to check, in target coordinates of
``self.get_transform()``. These are display coordinates for patches
that are added to a figure or Axes. Columns contain x and y values.
radius : float, optional
Additional margin on the patch in target coordinates of
`.Patch.get_transform`. See `.Path.contains_point` for further
details.
If `None`, the default value depends on the state of the object:
- If `.Artist.get_picker` is a number, the default
is that value. This is so that picking works as expected.
- Otherwise if the edge color has a non-zero alpha, the default
is half of the linewidth. This is so that all the colored
pixels are "in" the patch.
- Finally, if the edge has 0 alpha, the default is 0. This is
so that patches without a stroked edge do not have points
outside of the filled region report as "in" due to an
invisible edge.
Returns
-------
length-N bool array
Notes
-----
The proper use of this method depends on the transform of the patch.
See the notes on `.Patch.contains_point`.
"""
radius = self._process_radius(radius)
return self.get_path().contains_points(points,
self.get_transform(),
radius)
def update_from(self, other):
# docstring inherited.
super().update_from(other)
# For some properties we don't need or don't want to go through the
# getters/setters, so we just copy them directly.
self._edgecolor = other._edgecolor
self._facecolor = other._facecolor
self._original_edgecolor = other._original_edgecolor
self._original_facecolor = other._original_facecolor
self._fill = other._fill
self._hatch = other._hatch
self._hatch_color = other._hatch_color
self._original_hatchcolor = other._original_hatchcolor
self._unscaled_dash_pattern = other._unscaled_dash_pattern
self._gapcolor = other._gapcolor
self.set_linewidth(other._linewidth) # also sets scaled dashes
self.set_transform(other.get_data_transform())
# If the transform of other needs further initialization, then it will
# be the case for this artist too.
self._transformSet = other.is_transform_set()
def get_extents(self):
"""
Return the `Patch`'s axis-aligned extents as a `~.transforms.Bbox`.
"""
return self.get_path().get_extents(self.get_transform())
def get_transform(self):
"""Return the `~.transforms.Transform` applied to the `Patch`."""
return self.get_patch_transform() + artist.Artist.get_transform(self)
def get_data_transform(self):
"""
Return the `~.transforms.Transform` mapping data coordinates to
physical coordinates.
"""
return artist.Artist.get_transform(self)
def get_patch_transform(self):
"""
Return the `~.transforms.Transform` instance mapping patch coordinates
to data coordinates.
For example, one may define a patch of a circle which represents a
radius of 5 by providing coordinates for a unit circle, and a
transform which scales the coordinates (the patch coordinate) by 5.
"""
return transforms.IdentityTransform()
def get_antialiased(self):
"""Return whether antialiasing is used for drawing."""
return self._antialiased
def get_edgecolor(self):
"""Return the edge color."""
return self._edgecolor
def get_facecolor(self):
"""Return the face color."""
return self._facecolor
def get_hatchcolor(self):
"""Return the hatch color."""
if self._hatch_color == 'edge':
if self._edgecolor[3] == 0: # fully transparent
return colors.to_rgba(mpl.rcParams['patch.edgecolor'])
return self.get_edgecolor()
return self._hatch_color
def get_linewidth(self):
"""Return the line width in points."""
return self._linewidth
def get_linestyle(self):
"""Return the linestyle."""
return self._linestyle
def set_antialiased(self, aa):
"""
Set whether to use antialiased rendering.
Parameters
----------
aa : bool or None
"""
self._antialiased = mpl._val_or_rc(aa, 'patch.antialiased')
self.stale = True
def _set_edgecolor(self, color):
if color is None:
if (mpl.rcParams['patch.force_edgecolor'] or
not self._fill or self._edge_default):
color = mpl.rcParams['patch.edgecolor']
else:
color = 'none'
self._edgecolor = colors.to_rgba(color, self._alpha)
self.stale = True
def set_edgecolor(self, color):
"""
Set the patch edge color.
Parameters
----------
color : :mpltype:`color` or None
"""
self._original_edgecolor = color
self._set_edgecolor(color)
def _set_facecolor(self, color):
color = mpl._val_or_rc(color, 'patch.facecolor')
alpha = self._alpha if self._fill else 0
self._facecolor = colors.to_rgba(color, alpha)
self.stale = True
def set_facecolor(self, color):
"""
Set the patch face color.
Parameters
----------
color : :mpltype:`color` or None
"""
self._original_facecolor = color
self._set_facecolor(color)
def set_color(self, c):
"""
Set both the edgecolor and the facecolor.
Parameters
----------
c : :mpltype:`color`
See Also
--------
Patch.set_facecolor, Patch.set_edgecolor
For setting the edge or face color individually.
"""
self.set_edgecolor(c)
self.set_hatchcolor(c)
self.set_facecolor(c)
def _set_hatchcolor(self, color):
color = mpl._val_or_rc(color, 'hatch.color')
if cbook._str_equal(color, 'edge'):
self._hatch_color = 'edge'
else:
self._hatch_color = colors.to_rgba(color, self._alpha)
self.stale = True
def set_hatchcolor(self, color):
"""
Set the patch hatch color.
Parameters
----------
color : :mpltype:`color` or 'edge' or None
"""
self._original_hatchcolor = color
self._set_hatchcolor(color)
def get_edgegapcolor(self):
"""
Return the edge gap color.
.. versionadded:: 3.11
See also `~.Patch.set_edgegapcolor`.
"""
return self._gapcolor
def set_edgegapcolor(self, edgegapcolor):
"""
Set a color to fill the gaps in the dashed edge style.
.. versionadded:: 3.11
.. note::
Striped edges are created by drawing two interleaved dashed lines.
There can be overlaps between those two, which may result in
artifacts when using transparency.
This functionality is experimental and may change.
Parameters
----------
edgegapcolor : :mpltype:`color` or None
The color with which to fill the gaps. If None, the gaps are
unfilled.
"""
if edgegapcolor is not None:
self._gapcolor = colors.to_rgba(edgegapcolor, self._alpha)
else:
self._gapcolor = None
self.stale = True
def set_alpha(self, alpha):
# docstring inherited
super().set_alpha(alpha)
self._set_facecolor(self._original_facecolor)
self._set_edgecolor(self._original_edgecolor)
self._set_hatchcolor(self._original_hatchcolor)
# stale is already True
def set_linewidth(self, w):
"""
Set the patch linewidth in points.
Parameters
----------
w : float or None
"""
w = mpl._val_or_rc(w, 'patch.linewidth')
w = float(w)
self._linewidth = w
self._dash_pattern = mlines._scale_dashes(*self._unscaled_dash_pattern, w)
self.stale = True
def set_linestyle(self, ls):
"""
Set the patch linestyle.
Parameters
----------
ls : {'-', '--', '-.', ':', '', ...} or (offset, on-off-seq)
Possible values:
- A string:
======================================================= ================
linestyle description
======================================================= ================
``'-'`` or ``'solid'`` solid line
``'--'`` or ``'dashed'`` dashed line
``'-.'`` or ``'dashdot'`` dash-dotted line
``':'`` or ``'dotted'`` dotted line
``''`` or ``'none'`` (discouraged: ``'None'``, ``' '``) draw nothing
======================================================= ================
- A tuple describing the start position and lengths of dashes and spaces:
(offset, onoffseq)
where
- *offset* is a float specifying the offset (in points); i.e. how much
is the dash pattern shifted.
- *onoffseq* is a sequence of on and off ink in points. There can be
arbitrary many pairs of on and off values.
Example: The tuple ``(0, (10, 5, 1, 5))`` means that the pattern starts
at the beginning of the line. It draws a 10 point long dash,
then a 5 point long space, then a 1 point long dash, followed by a 5 point
long space, and then the pattern repeats.
For examples see :doc:`/gallery/lines_bars_and_markers/linestyles`.
"""
if ls is None:
ls = "solid"
if ls in [' ', '', 'none']:
ls = 'None'
self._linestyle = ls
self._unscaled_dash_pattern = mlines._get_dash_pattern(ls)
self._dash_pattern = mlines._scale_dashes(
*self._unscaled_dash_pattern, self._linewidth)
self.stale = True
def set_fill(self, b):
"""
Set whether to fill the patch.
Parameters
----------
b : bool
"""
self._fill = bool(b)
self._set_facecolor(self._original_facecolor)
self._set_edgecolor(self._original_edgecolor)
self._set_hatchcolor(self._original_hatchcolor)
self.stale = True
def get_fill(self):
"""Return whether the patch is filled."""
return self._fill
# Make fill a property so as to preserve the long-standing
# but somewhat inconsistent behavior in which fill was an
# attribute.
fill = property(get_fill, set_fill)
@_docstring.interpd
def set_capstyle(self, s):
"""
Set the `.CapStyle`.
The default capstyle is 'round' for `.FancyArrowPatch` and 'butt' for
all other patches.
Parameters
----------
s : `.CapStyle` or %(CapStyle)s
"""
cs = CapStyle(s)
self._capstyle = cs
self.stale = True
def get_capstyle(self):
"""Return the capstyle."""
return self._capstyle.name
@_docstring.interpd
def set_joinstyle(self, s):
"""
Set the `.JoinStyle`.
The default joinstyle is 'round' for `.FancyArrowPatch` and 'miter' for
all other patches.
Parameters
----------
s : `.JoinStyle` or %(JoinStyle)s
"""
js = JoinStyle(s)
self._joinstyle = js
self.stale = True
def get_joinstyle(self):
"""Return the joinstyle."""
return self._joinstyle.name
def set_hatch(self, hatch):
r"""
Set the hatching pattern.
*hatch* can be one of::
/ - diagonal hatching
\ - back diagonal
| - vertical
- - horizontal
+ - crossed
x - crossed diagonal
o - small circle
O - large circle
. - dots
* - stars
Letters can be combined, in which case all the specified
hatchings are done. If same letter repeats, it increases the
density of hatching of that pattern.
In regular (non-raw) Python strings, backslashes must be doubled:
``'\\\\'`` and ``r'\\'`` are both a double back-diagonal hatch.
Parameters
----------
hatch : {'/', '\\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
"""
# Use validate_hatch(list) after deprecation.
mhatch._validate_hatch_pattern(hatch)
self._hatch = hatch
self.stale = True
def get_hatch(self):
"""Return the hatching pattern."""
return self._hatch
def set_hatch_linewidth(self, lw):
"""Set the hatch linewidth."""
self._hatch_linewidth = lw
def get_hatch_linewidth(self):
"""Return the hatch linewidth."""
return self._hatch_linewidth
def _has_dashed_edge(self):
"""
Return whether the patch edge has a dashed linestyle.
A custom linestyle is assumed to be dashed, we do not inspect the
``onoffseq`` directly.
See also `~.Patch.set_linestyle`.
"""
return self._linestyle not in ('solid', '-')
def _draw_paths_with_artist_properties(
self, renderer, draw_path_args_list):
"""
``draw()`` helper factored out for sharing with `FancyArrowPatch`.
Configure *renderer* and the associated graphics context *gc*
from the artist properties, then repeatedly call
``renderer.draw_path(gc, *draw_path_args)`` for each tuple
*draw_path_args* in *draw_path_args_list*.
"""
renderer.open_group('patch', self.get_gid())
gc = renderer.new_gc()
lw = self._linewidth
if self._edgecolor[3] == 0 or self._linestyle == 'None':
lw = 0
gc.set_linewidth(lw)
gc.set_capstyle(self._capstyle)
gc.set_joinstyle(self._joinstyle)
gc.set_antialiased(self._antialiased)
self._set_gc_clip(gc)
gc.set_url(self._url)
gc.set_snap(self.get_snap())
gc.set_alpha(self._alpha)
if self._hatch:
gc.set_hatch(self._hatch)
gc.set_hatch_color(self.get_hatchcolor())
gc.set_hatch_linewidth(self._hatch_linewidth)
if self.get_sketch_params() is not None:
gc.set_sketch_params(*self.get_sketch_params())
if self.get_path_effects():
from matplotlib.patheffects import PathEffectRenderer
renderer = PathEffectRenderer(self.get_path_effects(), renderer)
# We first draw a path within the gaps if needed, but only for visible
# dashed edges; zero-width edges would otherwise yield all-zero dashes.
if lw > 0 and self._has_dashed_edge() and self._gapcolor is not None:
gc.set_foreground(self._gapcolor, isRGBA=True)
offset_gaps, gaps = mlines._get_inverse_dash_pattern(
*self._dash_pattern)
gc.set_dashes(offset_gaps, gaps)
for draw_path_args in draw_path_args_list:
renderer.draw_path(gc, *draw_path_args)
# Draw the main edge
gc.set_foreground(self._edgecolor, isRGBA=True)
if lw > 0:
gc.set_dashes(*self._dash_pattern)
else:
gc.set_dashes(0, None)
for draw_path_args in draw_path_args_list:
renderer.draw_path(gc, *draw_path_args)
gc.restore()
renderer.close_group('patch')
self.stale = False
@artist.allow_rasterization
def draw(self, renderer):
# docstring inherited
if not self.get_visible():
return
path = self.get_path()
transform = self.get_transform()
tpath = transform.transform_path_non_affine(path)
affine = transform.get_affine()
self._draw_paths_with_artist_properties(
renderer,
[(tpath, affine,
# Work around a bug in the PDF and SVG renderers, which
# do not draw the hatches if the facecolor is fully
# transparent, but do if it is None.
self._facecolor if self._facecolor[3] else None)])
def get_path(self):
"""Return the path of this patch."""
raise NotImplementedError('Derived must override')
def get_window_extent(self, renderer=None):
return self.get_path().get_extents(self.get_transform())
def _convert_xy_units(self, xy):
"""Convert x and y units for a tuple (x, y)."""
x = self.convert_xunits(xy[0])
y = self.convert_yunits(xy[1])
return x, y
class Shadow(Patch):
def __str__(self):
return f"Shadow({self.patch})"
@_docstring.interpd
def __init__(self, patch, ox, oy, *, shade=0.7, **kwargs):
"""
Create a shadow of the given *patch*.
By default, the shadow will have the same face color as the *patch*,
but darkened. The darkness can be controlled by *shade*.
Parameters
----------
patch : `~matplotlib.patches.Patch`
The patch to create the shadow for.
ox, oy : float
The shift of the shadow in data coordinates, scaled by a factor
of dpi/72.
shade : float, default: 0.7
How the darkness of the shadow relates to the original color. If 1, the
shadow is black, if 0, the shadow has the same color as the *patch*.
.. versionadded:: 3.8
**kwargs
Properties of the shadow patch. Supported keys are:
%(Patch:kwdoc)s
"""
super().__init__()
self.patch = patch
self._ox, self._oy = ox, oy
self._shadow_transform = transforms.Affine2D()
self.update_from(self.patch)
if not 0 Path
*x0*, *y0*, *width* and *height* specify the location and size of the box
to be drawn; *mutation_size* scales the outline properties such as padding.
"""
_style_list = {}
@_register_style(_style_list)
class Square:
"""A square box."""
def __init__(self, pad=0.3):
"""
Parameters
----------
pad : float, default: 0.3
The amount of padding around the original box.
"""
self.pad = pad
def __call__(self, x0, y0, width, height, mutation_size):
pad = mutation_size * self.pad
# width and height with padding added.
width, height = width + 2 * pad, height + 2 * pad
# boundary of the padded box
x0, y0 = x0 - pad, y0 - pad
x1, y1 = x0 + width, y0 + height
return Path._create_closed(
[(x0, y0), (x1, y0), (x1, y1), (x0, y1)])
@_register_style(_style_list)
class Circle:
"""A circular box."""
def __init__(self, pad=0.3):
"""
Parameters
----------
pad : float, default: 0.3
The amount of padding around the original box.
"""
self.pad = pad
def __call__(self, x0, y0, width, height, mutation_size):
pad = mutation_size * self.pad
width, height = width + 2 * pad, height + 2 * pad
# boundary of the padded box
x0, y0 = x0 - pad, y0 - pad
return Path.circle((x0 + width / 2, y0 + height / 2),
max(width, height) / 2)
@_register_style(_style_list)
class Ellipse:
"""
An elliptical box.
.. versionadded:: 3.7
"""
def __init__(self, pad=0.3):
"""
Parameters
----------
pad : float, default: 0.3
The amount of padding around the original box.
"""
self.pad = pad
def __call__(self, x0, y0, width, height, mutation_size):
pad = mutation_size * self.pad
width, height = width + 2 * pad, height + 2 * pad
# boundary of the padded box
x0, y0 = x0 - pad, y0 - pad
a = width / math.sqrt(2)
b = height / math.sqrt(2)
trans = Affine2D().scale(a, b).translate(x0 + width / 2,
y0 + height / 2)
return trans.transform_path(Path.unit_circle())
@_register_style(_style_list)
class RArrow:
"""A box in the shape of a right-pointing arrow."""
def __init__(self, pad=0.3, head_width=1.5, head_angle=90):
"""
Parameters
----------
pad : float, default: 0.3
The amount of padding around the original box.
head_width : float, default: 1.5
The head width, relative to the arrow shaft width; must be
nonnegative.
head_angle : float, default: 90
The angle at the tip of the arrow, in degrees; must be nonzero
(modulo 360). Negative angles result in arrow heads pointing
backwards.
"""
self.pad = pad
if head_width < 0:
raise ValueError("'head_width' must be nonnegative")
self.head_width = head_width
if head_angle % 360 == 0:
raise ValueError("'head_angle' must be nonzero")
self.head_angle = head_angle
def __call__(self, x0, y0, width, height, mutation_size):
# padding & padded dimensions
pad = mutation_size * self.pad
dx, dy = width + 2 * pad, height + 2 * pad
x0, y0 = x0 - pad, y0 - pad,
x1, y1 = x0 + dx, y0 + dy
head_dy = self.head_width * dy
mid_y = (y0 + y1) / 2
shaft_y0 = mid_y - head_dy / 2
shaft_y1 = mid_y + head_dy / 2
cot = 1 / math.tan(math.radians(self.head_angle / 2))
if cot > 0:
# tip_x is chosen s.t. the angled line moving back from the tip hits
# i) if head_width > 1: the box corner, or ii) if head_width <
# 1 the box edge at the point giving the correct shaft width.
tip_x = x1 + cot * min(dy, head_dy) / 2
shaft_x = tip_x - cot * head_dy / 2
return Path._create_closed([
(x0, y0), (shaft_x, y0), (shaft_x, shaft_y0),
(tip_x, mid_y),
(shaft_x, shaft_y1), (shaft_x, y1), (x0, y1),
])
else: # Reverse arrowhead.
# Make the long (outer) side of the arrowhead flush with the
# original box, and move back accordingly (but clipped to no
# more than the box length). If this clipping is necessary,
# the y positions at the short (inner) side of the arrowhead
# will be thicker than the original box, hence the need to
# recompute mid_y0 & mid_y1.
# If head_width < 1 no arrowhead is drawn.
dx = min(-cot * max(head_dy - dy, 0) / 2, dx) # cot < 0!
mid_y0 = min(shaft_y0, y0) - dx / cot
mid_y1 = max(shaft_y1, y1) + dx / cot
return Path._create_closed([
(x0, y0), (x1 - dx, mid_y0), (x1, shaft_y0),
(x1, shaft_y1), (x1 - dx, mid_y1), (x0, y1),
])
@_register_style(_style_list)
class LArrow(RArrow):
"""A box in the shape of a left-pointing arrow."""
def __call__(self, x0, y0, width, height, mutation_size):
p = super().__call__(x0, y0, width, height, mutation_size)
p.vertices[:, 0] = 2 * x0 + width - p.vertices[:, 0]
return p
@_register_style(_style_list)
class DArrow(RArrow):
"""A box in the shape of a two-way arrow."""
# Modified from RArrow to have arrows on both sides; see comments above.
def __call__(self, x0, y0, width, height, mutation_size):
# padding & padded dimensions
pad = mutation_size * self.pad
dx, dy = width + 2 * pad, height + 2 * pad
x0, y0 = x0 - pad, y0 - pad,
x1, y1 = x0 + dx, y0 + dy
head_dy = self.head_width * dy
mid_y = (y0 + y1) / 2
shaft_y0 = mid_y - head_dy / 2
shaft_y1 = mid_y + head_dy / 2
cot = 1 / math.tan(math.radians(self.head_angle / 2))
if cot > 0:
tip_x0 = x0 - cot * min(dy, head_dy) / 2
shaft_x0 = tip_x0 + cot * head_dy / 2
tip_x1 = x1 + cot * min(dy, head_dy) / 2
shaft_x1 = tip_x1 - cot * head_dy / 2
return Path._create_closed([
(shaft_x0, y1), (shaft_x0, shaft_y1),
(tip_x0, mid_y),
(shaft_x0, shaft_y0), (shaft_x0, y0),
(shaft_x1, y0), (shaft_x1, shaft_y0),
(tip_x1, mid_y),
(shaft_x1, shaft_y1), (shaft_x1, y1),
])
else:
# Don't move back by more than half the box length.
dx = min(-cot * max(head_dy - dy, 0) / 2, dx / 2) # cot < 0!
mid_y0 = min(shaft_y0, y0) - dx / cot
mid_y1 = max(shaft_y1, y1) + dx / cot
return Path._create_closed([
(x0, shaft_y0), (x0 + dx, mid_y0),
(x1 - dx, mid_y0), (x1, shaft_y0),
(x1, shaft_y1), (x1 - dx, mid_y1),
(x0 + dx, mid_y1), (x0, shaft_y1),
])
@_register_style(_style_list)
class Round:
"""A box with round corners."""
def __init__(self, pad=0.3, rounding_size=None):
"""
Parameters
----------
pad : float, default: 0.3
The amount of padding around the original box.
rounding_size : float, default: *pad*
Radius of the corners.
"""
self.pad = pad
self.rounding_size = rounding_size
def __call__(self, x0, y0, width, height, mutation_size):
# padding
pad = mutation_size * self.pad
# size of the rounding corner
if self.rounding_size:
dr = mutation_size * self.rounding_size
else:
dr = pad
width, height = width + 2 * pad, height + 2 * pad
x0, y0 = x0 - pad, y0 - pad,
x1, y1 = x0 + width, y0 + height
# Round corners are implemented as quadratic Bezier, e.g.,
# [(x0, y0-dr), (x0, y0), (x0+dr, y0)] for lower left corner.
cp = [(x0 + dr, y0),
(x1 - dr, y0),
(x1, y0), (x1, y0 + dr),
(x1, y1 - dr),
(x1, y1), (x1 - dr, y1),
(x0 + dr, y1),
(x0, y1), (x0, y1 - dr),
(x0, y0 + dr),
(x0, y0), (x0 + dr, y0),
(x0 + dr, y0)]
com = [Path.MOVETO,
Path.LINETO,
Path.CURVE3, Path.CURVE3,
Path.LINETO,
Path.CURVE3, Path.CURVE3,
Path.LINETO,
Path.CURVE3, Path.CURVE3,
Path.LINETO,
Path.CURVE3, Path.CURVE3,
Path.CLOSEPOLY]
return Path(cp, com)
@_register_style(_style_list)
class Round4:
"""A box with rounded edges."""
def __init__(self, pad=0.3, rounding_size=None):
"""
Parameters
----------
pad : float, default: 0.3
The amount of padding around the original box.
rounding_size : float, default: *pad*/2
Rounding of edges.
"""
self.pad = pad
self.rounding_size = rounding_size
def __call__(self, x0, y0, width, height, mutation_size):
# padding
pad = mutation_size * self.pad
# Rounding size; defaults to half of the padding.
if self.rounding_size:
dr = mutation_size * self.rounding_size
else:
dr = pad / 2.
width = width + 2 * pad - 2 * dr
height = height + 2 * pad - 2 * dr
x0, y0 = x0 - pad + dr, y0 - pad + dr,
x1, y1 = x0 + width, y0 + height
cp = [(x0, y0),
(x0 + dr, y0 - dr), (x1 - dr, y0 - dr), (x1, y0),
(x1 + dr, y0 + dr), (x1 + dr, y1 - dr), (x1, y1),
(x1 - dr, y1 + dr), (x0 + dr, y1 + dr), (x0, y1),
(x0 - dr, y1 - dr), (x0 - dr, y0 + dr), (x0, y0),
(x0, y0)]
com = [Path.MOVETO,
Path.CURVE4, Path.CURVE4, Path.CURVE4,
Path.CURVE4, Path.CURVE4, Path.CURVE4,
Path.CURVE4, Path.CURVE4, Path.CURVE4,
Path.CURVE4, Path.CURVE4, Path.CURVE4,
Path.CLOSEPOLY]
return Path(cp, com)
@_register_style(_style_list)
class Sawtooth:
"""A box with a sawtooth outline."""
def __init__(self, pad=0.3, tooth_size=None):
"""
Parameters
----------
pad : float, default: 0.3
The amount of padding around the original box.
tooth_size : float, default: *pad*/2
Size of the sawtooth.
"""
self.pad = pad
self.tooth_size = tooth_size
def _get_sawtooth_vertices(self, x0, y0, width, height, mutation_size):
# padding
pad = mutation_size * self.pad
# size of sawtooth
if self.tooth_size is None:
tooth_size = self.pad * .5 * mutation_size
else:
tooth_size = self.tooth_size * mutation_size
hsz = tooth_size / 2
width = width + 2 * pad - tooth_size
height = height + 2 * pad - tooth_size
# the sizes of the vertical and horizontal sawtooth are
# separately adjusted to fit the given box size.
dsx_n = round((width - tooth_size) / (tooth_size * 2)) * 2
dsy_n = round((height - tooth_size) / (tooth_size * 2)) * 2
x0, y0 = x0 - pad + hsz, y0 - pad + hsz
x1, y1 = x0 + width, y0 + height
xs = [
x0, *np.linspace(x0 + hsz, x1 - hsz, 2 * dsx_n + 1), # bottom
*([x1, x1 + hsz, x1, x1 - hsz] * dsy_n)[:2*dsy_n+2], # right
x1, *np.linspace(x1 - hsz, x0 + hsz, 2 * dsx_n + 1), # top
*([x0, x0 - hsz, x0, x0 + hsz] * dsy_n)[:2*dsy_n+2], # left
]
ys = [
*([y0, y0 - hsz, y0, y0 + hsz] * dsx_n)[:2*dsx_n+2], # bottom
y0, *np.linspace(y0 + hsz, y1 - hsz, 2 * dsy_n + 1), # right
*([y1, y1 + hsz, y1, y1 - hsz] * dsx_n)[:2*dsx_n+2], # top
y1, *np.linspace(y1 - hsz, y0 + hsz, 2 * dsy_n + 1), # left
]
return [*zip(xs, ys), (xs[0], ys[0])]
def __call__(self, x0, y0, width, height, mutation_size):
saw_vertices = self._get_sawtooth_vertices(x0, y0, width,
height, mutation_size)
return Path(saw_vertices, closed=True)
@_register_style(_style_list)
class Roundtooth(Sawtooth):
"""A box with a rounded sawtooth outline."""
def __call__(self, x0, y0, width, height, mutation_size):
saw_vertices = self._get_sawtooth_vertices(x0, y0,
width, height,
mutation_size)
# Add a trailing vertex to allow us to close the polygon correctly
saw_vertices = np.concatenate([saw_vertices, [saw_vertices[0]]])
codes = ([Path.MOVETO] +
[Path.CURVE3, Path.CURVE3] * ((len(saw_vertices)-1)//2) +
[Path.CLOSEPOLY])
return Path(saw_vertices, codes)
@_docstring.interpd
class ConnectionStyle(_Style):
"""
`ConnectionStyle` is a container class which defines
several connectionstyle classes, which is used to create a path
between two points. These are mainly used with `FancyArrowPatch`.
A connectionstyle object can be either created as::
ConnectionStyle.Arc3(rad=0.2)
or::
ConnectionStyle("Arc3", rad=0.2)
or::
ConnectionStyle("Arc3, rad=0.2")
The following classes are defined
%(ConnectionStyle:table)s
An instance of any connection style class is a callable object,
whose call signature is::
__call__(self, posA, posB,
patchA=None, patchB=None,
shrinkA=2., shrinkB=2.)
and it returns a `.Path` instance. *posA* and *posB* are
tuples of (x, y) coordinates of the two points to be
connected. *patchA* (or *patchB*) is given, the returned path is
clipped so that it start (or end) from the boundary of the
patch. The path is further shrunk by *shrinkA* (or *shrinkB*)
which is given in points.
"""
_style_list = {}
class _Base:
"""
A base class for connectionstyle classes. The subclass needs
to implement a *connect* method whose call signature is::
connect(posA, posB)
where posA and posB are tuples of x, y coordinates to be
connected. The method needs to return a path connecting two
points. This base class defines a __call__ method, and a few
helper methods.
"""
def _in_patch(self, patch):
"""
Return a predicate function testing whether a point *xy* is
contained in *patch*.
"""
return lambda xy: patch.contains(
SimpleNamespace(x=xy[0], y=xy[1]))[0]
def _clip(self, path, in_start, in_stop):
"""
Clip *path* at its start by the region where *in_start* returns
True, and at its stop by the region where *in_stop* returns True.
The original path is assumed to start in the *in_start* region and
to stop in the *in_stop* region.
"""
if in_start:
try:
_, path = split_path_inout(path, in_start)
except ValueError:
pass
if in_stop:
try:
path, _ = split_path_inout(path, in_stop)
except ValueError:
pass
return path
def __call__(self, posA, posB,
shrinkA=2., shrinkB=2., patchA=None, patchB=None):
"""
Call the *connect* method to create a path between *posA* and
*posB*; then clip and shrink the path.
"""
path = self.connect(posA, posB)
path = self._clip(
path,
self._in_patch(patchA) if patchA else None,
self._in_patch(patchB) if patchB else None,
)
path = self._clip(
path,
inside_circle(*path.vertices[0], shrinkA) if shrinkA else None,
inside_circle(*path.vertices[-1], shrinkB) if shrinkB else None
)
return path
@_register_style(_style_list)
class Arc3(_Base):
"""
Creates a simple quadratic Bézier curve between two
points. The curve is created so that the middle control point
(C1) is located at the same distance from the start (C0) and
end points(C2) and the distance of the C1 to the line
connecting C0-C2 is *rad* times the distance of C0-C2.
"""
def __init__(self, rad=0.):
"""
Parameters
----------
rad : float
Curvature of the curve.
"""
self.rad = rad
def connect(self, posA, posB):
x1, y1 = posA
x2, y2 = posB
x12, y12 = (x1 + x2) / 2., (y1 + y2) / 2.
dx, dy = x2 - x1, y2 - y1
f = self.rad
cx, cy = x12 + f * dy, y12 - f * dx
vertices = [(x1, y1),
(cx, cy),
(x2, y2)]
codes = [Path.MOVETO,
Path.CURVE3,
Path.CURVE3]
return Path(vertices, codes)
@_register_style(_style_list)
class Angle3(_Base):
"""
Creates a simple quadratic Bézier curve between two points. The middle
control point is placed at the intersecting point of two lines which
cross the start and end point, and have a slope of *angleA* and
*angleB*, respectively.
"""
def __init__(self, angleA=90, angleB=0):
"""
Parameters
----------
angleA : float
Starting angle of the path.
angleB : float
Ending angle of the path.
"""
self.angleA = angleA
self.angleB = angleB
def connect(self, posA, posB):
x1, y1 = posA
x2, y2 = posB
cosA = math.cos(math.radians(self.angleA))
sinA = math.sin(math.radians(self.angleA))
cosB = math.cos(math.radians(self.angleB))
sinB = math.sin(math.radians(self.angleB))
cx, cy = get_intersection(x1, y1, cosA, sinA,
x2, y2, cosB, sinB)
vertices = [(x1, y1), (cx, cy), (x2, y2)]
codes = [Path.MOVETO, Path.CURVE3, Path.CURVE3]
return Path(vertices, codes)
@_register_style(_style_list)
class Angle(_Base):
"""
Creates a piecewise continuous quadratic Bézier path between two
points. The path has a one passing-through point placed at the
intersecting point of two lines which cross the start and end point,
and have a slope of *angleA* and *angleB*, respectively.
The connecting edges are rounded with *rad*.
"""
def __init__(self, angleA=90, angleB=0, rad=0.):
"""
Parameters
----------
angleA : float
Starting angle of the path.
angleB : float
Ending angle of the path.
rad : float
Rounding radius of the edge.
"""
self.angleA = angleA
self.angleB = angleB
self.rad = rad
def connect(self, posA, posB):
x1, y1 = posA
x2, y2 = posB
cosA = math.cos(math.radians(self.angleA))
sinA = math.sin(math.radians(self.angleA))
cosB = math.cos(math.radians(self.angleB))
sinB = math.sin(math.radians(self.angleB))
cx, cy = get_intersection(x1, y1, cosA, sinA,
x2, y2, cosB, sinB)
vertices = [(x1, y1)]
codes = [Path.MOVETO]
if self.rad == 0.:
vertices.append((cx, cy))
codes.append(Path.LINETO)
else:
dx1, dy1 = x1 - cx, y1 - cy
d1 = np.hypot(dx1, dy1)
f1 = self.rad / d1
dx2, dy2 = x2 - cx, y2 - cy
d2 = np.hypot(dx2, dy2)
f2 = self.rad / d2
vertices.extend([(cx + dx1 * f1, cy + dy1 * f1),
(cx, cy),
(cx + dx2 * f2, cy + dy2 * f2)])
codes.extend([Path.LINETO, Path.CURVE3, Path.CURVE3])
vertices.append((x2, y2))
codes.append(Path.LINETO)
return Path(vertices, codes)
@_register_style(_style_list)
class Arc(_Base):
"""
Creates a piecewise continuous quadratic Bézier path between two
points. The path can have two passing-through points, a
point placed at the distance of *armA* and angle of *angleA* from
point A, another point with respect to point B. The edges are
rounded with *rad*.
"""
def __init__(self, angleA=0, angleB=0, armA=None, armB=None, rad=0.):
"""
Parameters
----------
angleA : float
Starting angle of the path.
angleB : float
Ending angle of the path.
armA : float or None
Length of the starting arm.
armB : float or None
Length of the ending arm.
rad : float
Rounding radius of the edges.
"""
self.angleA = angleA
self.angleB = angleB
self.armA = armA
self.armB = armB
self.rad = rad
def connect(self, posA, posB):
x1, y1 = posA
x2, y2 = posB
vertices = [(x1, y1)]
rounded = []
codes = [Path.MOVETO]
if self.armA:
cosA = math.cos(math.radians(self.angleA))
sinA = math.sin(math.radians(self.angleA))
# x_armA, y_armB
d = self.armA - self.rad
rounded.append((x1 + d * cosA, y1 + d * sinA))
d = self.armA
rounded.append((x1 + d * cosA, y1 + d * sinA))
if self.armB:
cosB = math.cos(math.radians(self.angleB))
sinB = math.sin(math.radians(self.angleB))
x_armB, y_armB = x2 + self.armB * cosB, y2 + self.armB * sinB
if rounded:
xp, yp = rounded[-1]
dx, dy = x_armB - xp, y_armB - yp
dd = (dx * dx + dy * dy) ** .5
rounded.append((xp + self.rad * dx / dd,
yp + self.rad * dy / dd))
vertices.extend(rounded)
codes.extend([Path.LINETO,
Path.CURVE3,
Path.CURVE3])
else:
xp, yp = vertices[-1]
dx, dy = x_armB - xp, y_armB - yp
dd = (dx * dx + dy * dy) ** .5
d = dd - self.rad
rounded = [(xp + d * dx / dd, yp + d * dy / dd),
(x_armB, y_armB)]
if rounded:
xp, yp = rounded[-1]
dx, dy = x2 - xp, y2 - yp
dd = (dx * dx + dy * dy) ** .5
rounded.append((xp + self.rad * dx / dd,
yp + self.rad * dy / dd))
vertices.extend(rounded)
codes.extend([Path.LINETO,
Path.CURVE3,
Path.CURVE3])
vertices.append((x2, y2))
codes.append(Path.LINETO)
return Path(vertices, codes)
@_register_style(_style_list)
class Bar(_Base):
"""
A line with *angle* between A and B with *armA* and *armB*. One of the
arms is extended so that they are connected in a right angle. The
length of *armA* is determined by (*armA* + *fraction* x AB distance).
Same for *armB*.
"""
def __init__(self, armA=0., armB=0., fraction=0.3, angle=None):
"""
Parameters
----------
armA : float
Minimum length of armA.
armB : float
Minimum length of armB.
fraction : float
A fraction of the distance between two points that will be
added to armA and armB.
angle : float or None
Angle of the connecting line (if None, parallel to A and B).
"""
self.armA = armA
self.armB = armB
self.fraction = fraction
self.angle = angle
def connect(self, posA, posB):
x1, y1 = posA
x20, y20 = x2, y2 = posB
theta1 = math.atan2(y2 - y1, x2 - x1)
dx, dy = x2 - x1, y2 - y1
dd = (dx * dx + dy * dy) ** .5
ddx, ddy = dx / dd, dy / dd
armA, armB = self.armA, self.armB
if self.angle is not None:
theta0 = np.deg2rad(self.angle)
dtheta = theta1 - theta0
dl = dd * math.sin(dtheta)
dL = dd * math.cos(dtheta)
x2, y2 = x1 + dL * math.cos(theta0), y1 + dL * math.sin(theta0)
armB = armB - dl
# update
dx, dy = x2 - x1, y2 - y1
dd2 = (dx * dx + dy * dy) ** .5
ddx, ddy = dx / dd2, dy / dd2
arm = max(armA, armB)
f = self.fraction * dd + arm
cx1, cy1 = x1 + f * ddy, y1 - f * ddx
cx2, cy2 = x2 + f * ddy, y2 - f * ddx
vertices = [(x1, y1),
(cx1, cy1),
(cx2, cy2),
(x20, y20)]
codes = [Path.MOVETO,
Path.LINETO,
Path.LINETO,
Path.LINETO]
return Path(vertices, codes)
def _point_along_a_line(x0, y0, x1, y1, d):
"""
Return the point on the line connecting (*x0*, *y0*) -- (*x1*, *y1*) whose
distance from (*x0*, *y0*) is *d*.
"""
dx, dy = x0 - x1, y0 - y1
ff = d / (dx * dx + dy * dy) ** .5
x2, y2 = x0 - ff * dx, y0 - ff * dy
return x2, y2
@_docstring.interpd
class ArrowStyle(_Style):
"""
`ArrowStyle` is a container class which defines several
arrowstyle classes, which is used to create an arrow path along a
given path. These are mainly used with `FancyArrowPatch`.
An arrowstyle object can be either created as::
ArrowStyle.Fancy(head_length=.4, head_width=.4, tail_width=.4)
or::
ArrowStyle("Fancy", head_length=.4, head_width=.4, tail_width=.4)
or::
ArrowStyle("Fancy, head_length=.4, head_width=.4, tail_width=.4")
The following classes are defined
%(ArrowStyle:table)s
For an overview of the visual appearance, see
:doc:`/gallery/text_labels_and_annotations/fancyarrow_demo`.
An instance of any arrow style class is a callable object,
whose call signature is::
__call__(self, path, mutation_size, linewidth, aspect_ratio=1.)
and it returns a tuple of a `.Path` instance and a boolean
value. *path* is a `.Path` instance along which the arrow
will be drawn. *mutation_size* and *aspect_ratio* have the same
meaning as in `BoxStyle`. *linewidth* is a line width to be
stroked. This is meant to be used to correct the location of the
head so that it does not overshoot the destination point, but not all
classes support it.
Notes
-----
*angleA* and *angleB* specify the orientation of the bracket, as either a
clockwise or counterclockwise angle depending on the arrow type. 0 degrees
means perpendicular to the line connecting the arrow's head and tail.
.. plot:: gallery/text_labels_and_annotations/angles_on_bracket_arrows.py
"""
_style_list = {}
class _Base:
"""
Arrow Transmuter Base class
ArrowTransmuterBase and its derivatives are used to make a fancy
arrow around a given path. The __call__ method returns a path
(which will be used to create a PathPatch instance) and a boolean
value indicating the path is open therefore is not fillable. This
class is not an artist and actual drawing of the fancy arrow is
done by the FancyArrowPatch class.
"""
# The derived classes are required to be able to be initialized
# w/o arguments, i.e., all its argument (except self) must have
# the default values.
@staticmethod
def ensure_quadratic_bezier(path):
"""
Some ArrowStyle classes only works with a simple quadratic
Bézier curve (created with `.ConnectionStyle.Arc3` or
`.ConnectionStyle.Angle3`). This static method checks if the
provided path is a simple quadratic Bézier curve and returns its
control points if true.
"""
segments = list(path.iter_segments())
if (len(segments) != 2 or segments[0][1] != Path.MOVETO or
segments[1][1] != Path.CURVE3):
raise ValueError(
"'path' is not a valid quadratic Bezier curve")
return [*segments[0][0], *segments[1][0]]
def transmute(self, path, mutation_size, linewidth):
"""
The transmute method is the very core of the ArrowStyle class and
must be overridden in the subclasses. It receives the *path*
object along which the arrow will be drawn, and the
*mutation_size*, with which the arrow head etc. will be scaled.
The *linewidth* may be used to adjust the path so that it does not
pass beyond the given points. It returns a tuple of a `.Path`
instance and a boolean. The boolean value indicate whether the
path can be filled or not. The return value can also be a list of
paths and list of booleans of the same length.
"""
raise NotImplementedError('Derived must override')
def __call__(self, path, mutation_size, linewidth,
aspect_ratio=1.):
"""
The __call__ method is a thin wrapper around the transmute method
and takes care of the aspect ratio.
"""
if aspect_ratio is not None:
# Squeeze the given height by the aspect_ratio
vertices = path.vertices / [1, aspect_ratio]
path_shrunk = Path(vertices, path.codes)
# call transmute method with squeezed height.
path_mutated, fillable = self.transmute(path_shrunk,
mutation_size,
linewidth)
if np.iterable(fillable):
# Restore the height
path_list = [Path(p.vertices * [1, aspect_ratio], p.codes)
for p in path_mutated]
return path_list, fillable
else:
return path_mutated, fillable
else:
return self.transmute(path, mutation_size, linewidth)
class _Curve(_Base):
"""
A simple arrow which will work with any path instance. The
returned path is the concatenation of the original path, and at
most two paths representing the arrow head or bracket at the start
point and at the end point. The arrow heads can be either open
or closed.
"""
arrow = "-"
fillbegin = fillend = False # Whether arrows are filled.
def __init__(self, head_length=.4, head_width=.2, widthA=1., widthB=1.,
lengthA=0.2, lengthB=0.2, angleA=0, angleB=0, scaleA=None,
scaleB=None):
"""
Parameters
----------
head_length : float, default: 0.4
Length of the arrow head, relative to *mutation_size*.
head_width : float, default: 0.2
Width of the arrow head, relative to *mutation_size*.
widthA, widthB : float, default: 1.0
Width of the bracket.
lengthA, lengthB : float, default: 0.2
Length of the bracket.
angleA, angleB : float, default: 0
Orientation of the bracket, as a counterclockwise angle.
0 degrees means perpendicular to the line.
scaleA, scaleB : float, default: *mutation_size*
The scale of the brackets.
"""
self.head_length, self.head_width = head_length, head_width
self.widthA, self.widthB = widthA, widthB
self.lengthA, self.lengthB = lengthA, lengthB
self.angleA, self.angleB = angleA, angleB
self.scaleA, self.scaleB = scaleA, scaleB
self._beginarrow_head = False
self._beginarrow_bracket = False
self._endarrow_head = False
self._endarrow_bracket = False
if "-" not in self.arrow:
raise ValueError("arrow must have the '-' between "
"the two heads")
beginarrow, endarrow = self.arrow.split("-", 1)
if beginarrow == "":
self._endarrow_head = True
self._endarrow_bracket = False
self.fillend = True
elif endarrow in ("[", "|"):
self._endarrow_head = False
self._endarrow_bracket = True
super().__init__()
def _get_arrow_wedge(self, x0, y0, x1, y1,
head_dist, cos_t, sin_t, linewidth):
"""
Return the paths for arrow heads. Since arrow lines are
drawn with capstyle=projected, The arrow goes beyond the
desired point. This method also returns the amount of the path
to be shrunken so that it does not overshoot.
"""
# arrow from x0, y0 to x1, y1
dx, dy = x0 - x1, y0 - y1
cp_distance = np.hypot(dx, dy)
# pad_projected : amount of pad to account the
# overshooting of the projection of the wedge
pad_projected = (.5 * linewidth / sin_t)
# Account for division by zero
if cp_distance == 0:
cp_distance = 1
# apply pad for projected edge
ddx = pad_projected * dx / cp_distance
ddy = pad_projected * dy / cp_distance
# offset for arrow wedge
dx = dx / cp_distance * head_dist
dy = dy / cp_distance * head_dist
dx1, dy1 = cos_t * dx + sin_t * dy, -sin_t * dx + cos_t * dy
dx2, dy2 = cos_t * dx - sin_t * dy, sin_t * dx + cos_t * dy
vertices_arrow = [(x1 + ddx + dx1, y1 + ddy + dy1),
(x1 + ddx, y1 + ddy),
(x1 + ddx + dx2, y1 + ddy + dy2)]
codes_arrow = [Path.MOVETO,
Path.LINETO,
Path.LINETO]
return vertices_arrow, codes_arrow, ddx, ddy
def _get_bracket(self, x0, y0,
x1, y1, width, length, angle):
cos_t, sin_t = get_cos_sin(x1, y1, x0, y0)
# arrow from x0, y0 to x1, y1
from matplotlib.bezier import get_normal_points
x1, y1, x2, y2 = get_normal_points(x0, y0, cos_t, sin_t, width)
dx, dy = length * cos_t, length * sin_t
vertices_arrow = [(x1 + dx, y1 + dy),
(x1, y1),
(x2, y2),
(x2 + dx, y2 + dy)]
codes_arrow = [Path.MOVETO,
Path.LINETO,
Path.LINETO,
Path.LINETO]
if angle:
trans = transforms.Affine2D().rotate_deg_around(x0, y0, angle)
vertices_arrow = trans.transform(vertices_arrow)
return vertices_arrow, codes_arrow
def transmute(self, path, mutation_size, linewidth):
# docstring inherited
if self._beginarrow_head or self._endarrow_head:
head_length = self.head_length * mutation_size
head_width = self.head_width * mutation_size
head_dist = np.hypot(head_length, head_width)
cos_t, sin_t = head_length / head_dist, head_width / head_dist
scaleA = mutation_size if self.scaleA is None else self.scaleA
scaleB = mutation_size if self.scaleB is None else self.scaleB
# begin arrow
x0, y0 = path.vertices[0]
x1, y1 = path.vertices[1]
# If there is no room for an arrow and a line, then skip the arrow
has_begin_arrow = self._beginarrow_head and (x0, y0) != (x1, y1)
verticesA, codesA, ddxA, ddyA = (
self._get_arrow_wedge(x1, y1, x0, y0,
head_dist, cos_t, sin_t, linewidth)
if has_begin_arrow
else ([], [], 0, 0)
)
# end arrow
x2, y2 = path.vertices[-2]
x3, y3 = path.vertices[-1]
# If there is no room for an arrow and a line, then skip the arrow
has_end_arrow = self._endarrow_head and (x2, y2) != (x3, y3)
verticesB, codesB, ddxB, ddyB = (
self._get_arrow_wedge(x2, y2, x3, y3,
head_dist, cos_t, sin_t, linewidth)
if has_end_arrow
else ([], [], 0, 0)
)
# This simple code will not work if ddx, ddy is greater than the
# separation between vertices.
paths = [Path(np.concatenate([[(x0 + ddxA, y0 + ddyA)],
path.vertices[1:-1],
[(x3 + ddxB, y3 + ddyB)]]),
path.codes)]
fills = [False]
if has_begin_arrow:
if self.fillbegin:
paths.append(
Path([*verticesA, (0, 0)], [*codesA, Path.CLOSEPOLY]))
fills.append(True)
else:
paths.append(Path(verticesA, codesA))
fills.append(False)
elif self._beginarrow_bracket:
x0, y0 = path.vertices[0]
x1, y1 = path.vertices[1]
verticesA, codesA = self._get_bracket(x0, y0, x1, y1,
self.widthA * scaleA,
self.lengthA * scaleA,
self.angleA)
paths.append(Path(verticesA, codesA))
fills.append(False)
if has_end_arrow:
if self.fillend:
fills.append(True)
paths.append(
Path([*verticesB, (0, 0)], [*codesB, Path.CLOSEPOLY]))
else:
fills.append(False)
paths.append(Path(verticesB, codesB))
elif self._endarrow_bracket:
x0, y0 = path.vertices[-1]
x1, y1 = path.vertices[-2]
verticesB, codesB = self._get_bracket(x0, y0, x1, y1,
self.widthB * scaleB,
self.lengthB * scaleB,
self.angleB)
paths.append(Path(verticesB, codesB))
fills.append(False)
return paths, fills
@_register_style(_style_list, name="-")
class Curve(_Curve):
"""A simple curve without any arrow head."""
def __init__(self): # hide head_length, head_width
# These attributes (whose values come from backcompat) only matter
# if someone modifies beginarrow/etc. on an ArrowStyle instance.
super().__init__(head_length=.2, head_width=.1)
@_register_style(_style_list, name=""
@_register_style(_style_list, name="")
class CurveAB(_Curve):
"""An arrow with heads both at the start and the end point."""
arrow = ""
@_register_style(_style_list, name=""
@_register_style(_style_list, name="")
class CurveFilledAB(_Curve):
"""An arrow with filled triangle heads at both ends."""
arrow = ""
@_register_style(_style_list, name="]-")
class BracketA(_Curve):
"""An arrow with an outward square bracket at its start."""
arrow = "]-"
def __init__(self, widthA=1., lengthA=0.2, angleA=0):
"""
Parameters
----------
widthA : float, default: 1.0
Width of the bracket.
lengthA : float, default: 0.2
Length of the bracket.
angleA : float, default: 0 degrees
Orientation of the bracket, as a counterclockwise angle.
0 degrees means perpendicular to the line.
"""
super().__init__(widthA=widthA, lengthA=lengthA, angleA=angleA)
@_register_style(_style_list, name="-[")
class BracketB(_Curve):
"""An arrow with an outward square bracket at its end."""
arrow = "-["
def __init__(self, widthB=1., lengthB=0.2, angleB=0):
"""
Parameters
----------
widthB : float, default: 1.0
Width of the bracket.
lengthB : float, default: 0.2
Length of the bracket.
angleB : float, default: 0 degrees
Orientation of the bracket, as a counterclockwise angle.
0 degrees means perpendicular to the line.
"""
super().__init__(widthB=widthB, lengthB=lengthB, angleB=angleB)
@_register_style(_style_list, name="]-[")
class BracketAB(_Curve):
"""An arrow with outward square brackets at both ends."""
arrow = "]-["
def __init__(self,
widthA=1., lengthA=0.2, angleA=0,
widthB=1., lengthB=0.2, angleB=0):
"""
Parameters
----------
widthA, widthB : float, default: 1.0
Width of the bracket.
lengthA, lengthB : float, default: 0.2
Length of the bracket.
angleA, angleB : float, default: 0 degrees
Orientation of the bracket, as a counterclockwise angle.
0 degrees means perpendicular to the line.
"""
super().__init__(widthA=widthA, lengthA=lengthA, angleA=angleA,
widthB=widthB, lengthB=lengthB, angleB=angleB)
@_register_style(_style_list, name="|-|")
class BarAB(_Curve):
"""An arrow with vertical bars ``|`` at both ends."""
arrow = "|-|"
def __init__(self, widthA=1., angleA=0, widthB=1., angleB=0):
"""
Parameters
----------
widthA, widthB : float, default: 1.0
Width of the bracket.
angleA, angleB : float, default: 0 degrees
Orientation of the bracket, as a counterclockwise angle.
0 degrees means perpendicular to the line.
"""
super().__init__(widthA=widthA, lengthA=0, angleA=angleA,
widthB=widthB, lengthB=0, angleB=angleB)
@_register_style(_style_list, name=']->')
class BracketCurve(_Curve):
"""
An arrow with an outward square bracket at its start and a head at
the end.
"""
arrow = "]->"
def __init__(self, widthA=1., lengthA=0.2, angleA=None):
"""
Parameters
----------
widthA : float, default: 1.0
Width of the bracket.
lengthA : float, default: 0.2
Length of the bracket.
angleA : float, default: 0 degrees
Orientation of the bracket, as a counterclockwise angle.
0 degrees means perpendicular to the line.
"""
super().__init__(widthA=widthA, lengthA=lengthA, angleA=angleA)
@_register_style(_style_list, name='= 0 else bb.x1 + x
y = bb.y0 + y if y >= 0 else bb.y1 + y
return x, y
elif s == 'subfigure pixels':
# pixels from the lower left corner of the figure
bb = self.get_figure(root=False).bbox
x = bb.x0 + x if x >= 0 else bb.x1 + x
y = bb.y0 + y if y >= 0 else bb.y1 + y
return x, y
elif s == 'axes pixels':
# pixels from the lower left corner of the Axes
bb = axes.bbox
x = bb.x0 + x if x >= 0 else bb.x1 + x
y = bb.y0 + y if y >= 0 else bb.y1 + y
return x, y
elif isinstance(s, transforms.Transform):
return s.transform(xy)
else:
raise ValueError(f"{s0} is not a valid coordinate transformation")
def set_annotation_clip(self, b):
"""
Set the annotation's clipping behavior.
Parameters
----------
b : bool or None
- True: The annotation will be clipped when ``self.xy`` is
outside the Axes.
- False: The annotation will always be drawn.
- None: The annotation will be clipped when ``self.xy`` is
outside the Axes and ``self.xycoords == "data"``.
"""
self._annotation_clip = b
self.stale = True
def get_annotation_clip(self):
"""
Return the clipping behavior.
See `.set_annotation_clip` for the meaning of the return value.
"""
return self._annotation_clip
def _get_path_in_displaycoord(self):
"""Return the mutated path of the arrow in display coordinates."""
dpi_cor = self._dpi_cor
posA = self._get_xy(self.xy1, self.coords1, self.axesA)
posB = self._get_xy(self.xy2, self.coords2, self.axesB)
path = self.get_connectionstyle()(
posA, posB,
patchA=self.patchA, patchB=self.patchB,
shrinkA=self.shrinkA * dpi_cor, shrinkB=self.shrinkB * dpi_cor,
)
path, fillable = self.get_arrowstyle()(
path,
self.get_mutation_scale() * dpi_cor,
self.get_linewidth() * dpi_cor,
self.get_mutation_aspect()
)
return path, fillable
def _check_xy(self, renderer):
"""Check whether the annotation needs to be drawn."""
b = self.get_annotation_clip()
if b or (b is None and self.coords1 == "data"):
xy_pixel = self._get_xy(self.xy1, self.coords1, self.axesA)
if self.axesA is None:
axes = self.axes
else:
axes = self.axesA
if not axes.contains_point(xy_pixel):
return False
if b or (b is None and self.coords2 == "data"):
xy_pixel = self._get_xy(self.xy2, self.coords2, self.axesB)
if self.axesB is None:
axes = self.axes
else:
axes = self.axesB
if not axes.contains_point(xy_pixel):
return False
return True
def draw(self, renderer):
if not self.get_visible() or not self._check_xy(renderer):
return
super().draw(renderer)