hash
stringlengths 64
64
| content
stringlengths 0
1.51M
|
---|---|
2eae656b2ed9fd13111e2521b34bc3e7265631b0c343b8a14460b411397aad2c
|
"""
===================
The mplot3d Toolkit
===================
Generating 3D plots using the mplot3d toolkit.
.. currentmodule:: mpl_toolkits.mplot3d
.. contents::
:backlinks: none
.. _toolkit_mplot3d-tutorial:
Getting started
---------------
3D Axes (of class `Axes3D`) are created by passing the ``projection="3d"``
keyword argument to `Figure.add_subplot`::
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
.. versionchanged:: 1.0.0
Prior to Matplotlib 1.0.0, `Axes3D` needed to be directly instantiated with
``from mpl_toolkits.mplot3d import Axes3D; ax = Axes3D(fig)``.
.. versionchanged:: 3.2.0
Prior to Matplotlib 3.2.0, it was necessary to explicitly import the
:mod:`mpl_toolkits.mplot3d` module to make the '3d' projection to
`Figure.add_subplot`.
See the :ref:`toolkit_mplot3d-faq` for more information about the mplot3d
toolkit.
.. _plot3d:
Line plots
====================
.. automethod:: Axes3D.plot
.. figure:: ../../gallery/mplot3d/images/sphx_glr_lines3d_001.png
:target: ../../gallery/mplot3d/lines3d.html
:align: center
:scale: 50
Lines3d
.. _scatter3d:
Scatter plots
=============
.. automethod:: Axes3D.scatter
.. figure:: ../../gallery/mplot3d/images/sphx_glr_scatter3d_001.png
:target: ../../gallery/mplot3d/scatter3d.html
:align: center
:scale: 50
Scatter3d
.. _wireframe:
Wireframe plots
===============
.. automethod:: Axes3D.plot_wireframe
.. figure:: ../../gallery/mplot3d/images/sphx_glr_wire3d_001.png
:target: ../../gallery/mplot3d/wire3d.html
:align: center
:scale: 50
Wire3d
.. _surface:
Surface plots
=============
.. automethod:: Axes3D.plot_surface
.. figure:: ../../gallery/mplot3d/images/sphx_glr_surface3d_001.png
:target: ../../gallery/mplot3d/surface3d.html
:align: center
:scale: 50
Surface3d
Surface3d 2
Surface3d 3
.. _trisurface:
Tri-Surface plots
=================
.. automethod:: Axes3D.plot_trisurf
.. figure:: ../../gallery/mplot3d/images/sphx_glr_trisurf3d_001.png
:target: ../../gallery/mplot3d/trisurf3d.html
:align: center
:scale: 50
Trisurf3d
.. _contour3d:
Contour plots
=============
.. automethod:: Axes3D.contour
.. figure:: ../../gallery/mplot3d/images/sphx_glr_contour3d_001.png
:target: ../../gallery/mplot3d/contour3d.html
:align: center
:scale: 50
Contour3d
Contour3d 2
Contour3d 3
.. _contourf3d:
Filled contour plots
====================
.. automethod:: Axes3D.contourf
.. figure:: ../../gallery/mplot3d/images/sphx_glr_contourf3d_001.png
:target: ../../gallery/mplot3d/contourf3d.html
:align: center
:scale: 50
Contourf3d
Contourf3d 2
.. versionadded:: 1.1.0
The feature demoed in the second contourf3d example was enabled as a
result of a bugfix for version 1.1.0.
.. _polygon3d:
Polygon plots
====================
.. automethod:: Axes3D.add_collection3d
.. figure:: ../../gallery/mplot3d/images/sphx_glr_polys3d_001.png
:target: ../../gallery/mplot3d/polys3d.html
:align: center
:scale: 50
Polys3d
.. _bar3d:
Bar plots
====================
.. automethod:: Axes3D.bar
.. figure:: ../../gallery/mplot3d/images/sphx_glr_bars3d_001.png
:target: ../../gallery/mplot3d/bars3d.html
:align: center
:scale: 50
Bars3d
.. _quiver3d:
Quiver
====================
.. automethod:: Axes3D.quiver
.. figure:: ../../gallery/mplot3d/images/sphx_glr_quiver3d_001.png
:target: ../../gallery/mplot3d/quiver3d.html
:align: center
:scale: 50
Quiver3d
.. _2dcollections3d:
2D plots in 3D
====================
.. figure:: ../../gallery/mplot3d/images/sphx_glr_2dcollections3d_001.png
:target: ../../gallery/mplot3d/2dcollections3d.html
:align: center
:scale: 50
2dcollections3d
.. _text3d:
Text
====================
.. automethod:: Axes3D.text
.. figure:: ../../gallery/mplot3d/images/sphx_glr_text3d_001.png
:target: ../../gallery/mplot3d/text3d.html
:align: center
:scale: 50
Text3d
.. _3dsubplots:
Subplotting
====================
Having multiple 3D plots in a single figure is the same
as it is for 2D plots. Also, you can have both 2D and 3D plots
in the same figure.
.. versionadded:: 1.0.0
Subplotting 3D plots was added in v1.0.0. Earlier version can not
do this.
.. figure:: ../../gallery/mplot3d/images/sphx_glr_subplot3d_001.png
:target: ../../gallery/mplot3d/subplot3d.html
:align: center
:scale: 50
Subplot3d
Mixed Subplots
"""
|
93b6cfb60ba4319396857702e61859cabf1d8d604c74d2e1502721e92324d43e
|
"""
*****************
Specifying Colors
*****************
Matplotlib recognizes the following formats to specify a color:
* an RGB or RGBA (red, green, blue, alpha) tuple of float values in ``[0, 1]``
(e.g., ``(0.1, 0.2, 0.5)`` or ``(0.1, 0.2, 0.5, 0.3)``);
* a hex RGB or RGBA string (e.g., ``'#0f0f0f'`` or ``'#0f0f0f80'``;
case-insensitive);
* a string representation of a float value in ``[0, 1]`` inclusive for gray
level (e.g., ``'0.5'``);
* one of ``{'b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'}``;
* a X11/CSS4 color name (case-insensitive);
* a name from the `xkcd color survey`_, prefixed with ``'xkcd:'`` (e.g.,
``'xkcd:sky blue'``; case insensitive);
* one of the Tableau Colors from the 'T10' categorical palette (the default
color cycle): ``{'tab:blue', 'tab:orange', 'tab:green', 'tab:red',
'tab:purple', 'tab:brown', 'tab:pink', 'tab:gray', 'tab:olive', 'tab:cyan'}``
(case-insensitive);
* a "CN" color spec, i.e. `'C'` followed by a number, which is an index into
the default property cycle (``matplotlib.rcParams['axes.prop_cycle']``); the
indexing is intended to occur at rendering time, and defaults to black if the
cycle does not include color.
.. _xkcd color survey: https://xkcd.com/color/rgb/
"Red", "Green", and "Blue" are the intensities of those colors, the combination
of which span the colorspace.
How "Alpha" behaves depends on the ``zorder`` of the Artist. Higher
``zorder`` Artists are drawn on top of lower Artists, and "Alpha" determines
whether the lower artist is covered by the higher.
If the old RGB of a pixel is ``RGBold`` and the RGB of the
pixel of the Artist being added is ``RGBnew`` with Alpha ``alpha``,
then the RGB of the pixel is updated to:
``RGB = RGBOld * (1 - Alpha) + RGBnew * Alpha``. Alpha
of 1 means the old color is completely covered by the new Artist, Alpha of 0
means that pixel of the Artist is transparent.
For more information on colors in matplotlib see
* the :doc:`/gallery/color/color_demo` example;
* the `matplotlib.colors` API;
* the :doc:`/gallery/color/named_colors` example.
"CN" color selection
--------------------
"CN" colors are converted to RGBA as soon as the artist is created. For
example,
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
th = np.linspace(0, 2*np.pi, 128)
def demo(sty):
mpl.style.use(sty)
fig, ax = plt.subplots(figsize=(3, 3))
ax.set_title('style: {!r}'.format(sty), color='C0')
ax.plot(th, np.cos(th), 'C1', label='C1')
ax.plot(th, np.sin(th), 'C2', label='C2')
ax.legend()
demo('default')
demo('seaborn')
###############################################################################
# will use the first color for the title and then plot using the second
# and third colors of each style's ``mpl.rcParams['axes.prop_cycle']``.
#
#
# .. _xkcd-colors:
#
# xkcd v X11/CSS4
# ---------------
#
# The xkcd colors are derived from a user survey conducted by the
# webcomic xkcd. `Details of the survey are available on the xkcd blog
# <https://blog.xkcd.com/2010/05/03/color-survey-results/>`__.
#
# Out of 148 colors in the CSS color list, there are 95 name collisions
# between the X11/CSS4 names and the xkcd names, all but 3 of which have
# different hex values. For example ``'blue'`` maps to ``'#0000FF'``
# where as ``'xkcd:blue'`` maps to ``'#0343DF'``. Due to these name
# collisions all of the xkcd colors have ``'xkcd:'`` prefixed. As noted in
# the blog post, while it might be interesting to re-define the X11/CSS4 names
# based on such a survey, we do not do so unilaterally.
#
# The name collisions are shown in the table below; the color names
# where the hex values agree are shown in bold.
import matplotlib._color_data as mcd
import matplotlib.patches as mpatch
overlap = {name for name in mcd.CSS4_COLORS
if "xkcd:" + name in mcd.XKCD_COLORS}
fig = plt.figure(figsize=[4.8, 16])
ax = fig.add_axes([0, 0, 1, 1])
for j, n in enumerate(sorted(overlap, reverse=True)):
weight = None
cn = mcd.CSS4_COLORS[n]
xkcd = mcd.XKCD_COLORS["xkcd:" + n].upper()
if cn == xkcd:
weight = 'bold'
r1 = mpatch.Rectangle((0, j), 1, 1, color=cn)
r2 = mpatch.Rectangle((1, j), 1, 1, color=xkcd)
txt = ax.text(2, j+.5, ' ' + n, va='center', fontsize=10,
weight=weight)
ax.add_patch(r1)
ax.add_patch(r2)
ax.axhline(j, color='k')
ax.text(.5, j + 1.5, 'X11', ha='center', va='center')
ax.text(1.5, j + 1.5, 'xkcd', ha='center', va='center')
ax.set_xlim(0, 3)
ax.set_ylim(0, j + 2)
ax.axis('off')
|
b457049c7ea3e5508babe12c3af1ba92318a81cb3c8b1dca1d809b65974ad140
|
"""
=============================
Customized Colorbars Tutorial
=============================
This tutorial shows how to build colorbars without an attached plot.
Customized Colorbars
====================
`~matplotlib.colorbar.ColorbarBase` puts a colorbar in a specified axes,
and can make a colorbar for a given colormap; it does not need a mappable
object like an image. In this tutorial we will explore what can be done with
standalone colorbar.
Basic continuous colorbar
-------------------------
Set the colormap and norm to correspond to the data for which the colorbar
will be used. Then create the colorbar by calling
:class:`~matplotlib.colorbar.ColorbarBase` and specify axis, colormap, norm
and orientation as parameters. Here we create a basic continuous colorbar
with ticks and labels. For more information see the
:mod:`~matplotlib.colorbar` API.
"""
import matplotlib.pyplot as plt
import matplotlib as mpl
fig, ax = plt.subplots(figsize=(6, 1))
fig.subplots_adjust(bottom=0.5)
cmap = mpl.cm.cool
norm = mpl.colors.Normalize(vmin=5, vmax=10)
cb1 = mpl.colorbar.ColorbarBase(ax, cmap=cmap,
norm=norm,
orientation='horizontal')
cb1.set_label('Some Units')
fig.show()
###############################################################################
# Discrete intervals colorbar
# ---------------------------
#
# The second example illustrates the use of a
# :class:`~matplotlib.colors.ListedColormap` which generates a colormap from a
# set of listed colors, :func:`colors.BoundaryNorm` which generates a colormap
# index based on discrete intervals and extended ends to show the "over" and
# "under" value colors. Over and under are used to display data outside of the
# normalized [0,1] range. Here we pass colors as gray shades as a string
# encoding a float in the 0-1 range.
#
# If a :class:`~matplotlib.colors.ListedColormap` is used, the length of the
# bounds array must be one greater than the length of the color list. The
# bounds must be monotonically increasing.
#
# This time we pass some more arguments in addition to previous arguments to
# :class:`~matplotlib.colorbar.ColorbarBase`. For the out-of-range values to
# display on the colorbar, we have to use the *extend* keyword argument. To use
# *extend*, you must specify two extra boundaries. Finally spacing argument
# ensures that intervals are shown on colorbar proportionally.
fig, ax = plt.subplots(figsize=(6, 1))
fig.subplots_adjust(bottom=0.5)
cmap = mpl.colors.ListedColormap(['red', 'green', 'blue', 'cyan'])
cmap.set_over('0.25')
cmap.set_under('0.75')
bounds = [1, 2, 4, 7, 8]
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
cb2 = mpl.colorbar.ColorbarBase(ax, cmap=cmap,
norm=norm,
boundaries=[0] + bounds + [13],
extend='both',
ticks=bounds,
spacing='proportional',
orientation='horizontal')
cb2.set_label('Discrete intervals, some other units')
fig.show()
###############################################################################
# Colorbar with custom extension lengths
# --------------------------------------
#
# Here we illustrate the use of custom length colorbar extensions, used on a
# colorbar with discrete intervals. To make the length of each extension the
# same as the length of the interior colors, use ``extendfrac='auto'``.
fig, ax = plt.subplots(figsize=(6, 1))
fig.subplots_adjust(bottom=0.5)
cmap = mpl.colors.ListedColormap(['royalblue', 'cyan',
'yellow', 'orange'])
cmap.set_over('red')
cmap.set_under('blue')
bounds = [-1.0, -0.5, 0.0, 0.5, 1.0]
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
cb3 = mpl.colorbar.ColorbarBase(ax, cmap=cmap,
norm=norm,
boundaries=[-10] + bounds + [10],
extend='both',
extendfrac='auto',
ticks=bounds,
spacing='uniform',
orientation='horizontal')
cb3.set_label('Custom extension lengths, some other units')
fig.show()
|
1025ac7130e1a7526f34dfdf4f26dd5d9af610f53069e0b86ff4af03e5f42540
|
"""
Colormap Normalization
======================
Objects that use colormaps by default linearly map the colors in the
colormap from data values *vmin* to *vmax*. For example::
pcm = ax.pcolormesh(x, y, Z, vmin=-1., vmax=1., cmap='RdBu_r')
will map the data in *Z* linearly from -1 to +1, so *Z=0* will
give a color at the center of the colormap *RdBu_r* (white in this
case).
Matplotlib does this mapping in two steps, with a normalization from
[0,1] occurring first, and then mapping onto the indices in the
colormap. Normalizations are classes defined in the
:func:`matplotlib.colors` module. The default, linear normalization is
:func:`matplotlib.colors.Normalize`.
Artists that map data to color pass the arguments *vmin* and *vmax* to
construct a :func:`matplotlib.colors.Normalize` instance, then call it:
.. ipython::
In [1]: import matplotlib as mpl
In [2]: norm = mpl.colors.Normalize(vmin=-1.,vmax=1.)
In [3]: norm(0.)
Out[3]: 0.5
However, there are sometimes cases where it is useful to map data to
colormaps in a non-linear fashion.
Logarithmic
-----------
One of the most common transformations is to plot data by taking
its logarithm (to the base-10). This transformation is useful to
display changes across disparate scales. Using :func:`colors.LogNorm`
normalizes the data via :math:`log_{10}`. In the example below,
there are two bumps, one much smaller than the other. Using
:func:`colors.LogNorm`, the shape and location of each bump can clearly
be seen:
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cbook as cbook
N = 100
X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)]
# A low hump with a spike coming out of the top right. Needs to have
# z/colour axis on a log scale so we see both hump and spike. linear
# scale only shows the spike.
Z1 = np.exp(-(X)**2 - (Y)**2)
Z2 = np.exp(-(X * 10)**2 - (Y * 10)**2)
Z = Z1 + 50 * Z2
fig, ax = plt.subplots(2, 1)
pcm = ax[0].pcolor(X, Y, Z,
norm=colors.LogNorm(vmin=Z.min(), vmax=Z.max()),
cmap='PuBu_r')
fig.colorbar(pcm, ax=ax[0], extend='max')
pcm = ax[1].pcolor(X, Y, Z, cmap='PuBu_r')
fig.colorbar(pcm, ax=ax[1], extend='max')
plt.show()
###############################################################################
# Symmetric logarithmic
# ---------------------
#
# Similarly, it sometimes happens that there is data that is positive
# and negative, but we would still like a logarithmic scaling applied to
# both. In this case, the negative numbers are also scaled
# logarithmically, and mapped to smaller numbers; e.g., if `vmin=-vmax`,
# then they the negative numbers are mapped from 0 to 0.5 and the
# positive from 0.5 to 1.
#
# Since the logarithm of values close to zero tends toward infinity, a
# small range around zero needs to be mapped linearly. The parameter
# *linthresh* allows the user to specify the size of this range
# (-*linthresh*, *linthresh*). The size of this range in the colormap is
# set by *linscale*. When *linscale* == 1.0 (the default), the space used
# for the positive and negative halves of the linear range will be equal
# to one decade in the logarithmic range.
N = 100
X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)]
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (Z1 - Z2) * 2
fig, ax = plt.subplots(2, 1)
pcm = ax[0].pcolormesh(X, Y, Z,
norm=colors.SymLogNorm(linthresh=0.03, linscale=0.03,
vmin=-1.0, vmax=1.0),
cmap='RdBu_r')
fig.colorbar(pcm, ax=ax[0], extend='both')
pcm = ax[1].pcolormesh(X, Y, Z, cmap='RdBu_r', vmin=-np.max(Z))
fig.colorbar(pcm, ax=ax[1], extend='both')
plt.show()
###############################################################################
# Power-law
# ---------
#
# Sometimes it is useful to remap the colors onto a power-law
# relationship (i.e. :math:`y=x^{\gamma}`, where :math:`\gamma` is the
# power). For this we use the :func:`colors.PowerNorm`. It takes as an
# argument *gamma* (*gamma* == 1.0 will just yield the default linear
# normalization):
#
# .. note::
#
# There should probably be a good reason for plotting the data using
# this type of transformation. Technical viewers are used to linear
# and logarithmic axes and data transformations. Power laws are less
# common, and viewers should explicitly be made aware that they have
# been used.
N = 100
X, Y = np.mgrid[0:3:complex(0, N), 0:2:complex(0, N)]
Z1 = (1 + np.sin(Y * 10.)) * X**(2.)
fig, ax = plt.subplots(2, 1)
pcm = ax[0].pcolormesh(X, Y, Z1, norm=colors.PowerNorm(gamma=0.5),
cmap='PuBu_r')
fig.colorbar(pcm, ax=ax[0], extend='max')
pcm = ax[1].pcolormesh(X, Y, Z1, cmap='PuBu_r')
fig.colorbar(pcm, ax=ax[1], extend='max')
plt.show()
###############################################################################
# Discrete bounds
# ---------------
#
# Another normaization that comes with Matplotlib is
# :func:`colors.BoundaryNorm`. In addition to *vmin* and *vmax*, this
# takes as arguments boundaries between which data is to be mapped. The
# colors are then linearly distributed between these "bounds". For
# instance:
#
# .. ipython::
#
# In [2]: import matplotlib.colors as colors
#
# In [3]: bounds = np.array([-0.25, -0.125, 0, 0.5, 1])
#
# In [4]: norm = colors.BoundaryNorm(boundaries=bounds, ncolors=4)
#
# In [5]: print(norm([-0.2,-0.15,-0.02, 0.3, 0.8, 0.99]))
# [0 0 1 2 3 3]
#
# Note unlike the other norms, this norm returns values from 0 to *ncolors*-1.
N = 100
X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)]
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (Z1 - Z2) * 2
fig, ax = plt.subplots(3, 1, figsize=(8, 8))
ax = ax.flatten()
# even bounds gives a contour-like effect
bounds = np.linspace(-1, 1, 10)
norm = colors.BoundaryNorm(boundaries=bounds, ncolors=256)
pcm = ax[0].pcolormesh(X, Y, Z,
norm=norm,
cmap='RdBu_r')
fig.colorbar(pcm, ax=ax[0], extend='both', orientation='vertical')
# uneven bounds changes the colormapping:
bounds = np.array([-0.25, -0.125, 0, 0.5, 1])
norm = colors.BoundaryNorm(boundaries=bounds, ncolors=256)
pcm = ax[1].pcolormesh(X, Y, Z, norm=norm, cmap='RdBu_r')
fig.colorbar(pcm, ax=ax[1], extend='both', orientation='vertical')
pcm = ax[2].pcolormesh(X, Y, Z, cmap='RdBu_r', vmin=-np.max(Z))
fig.colorbar(pcm, ax=ax[2], extend='both', orientation='vertical')
plt.show()
###############################################################################
# DivergingNorm: Different mapping on either side of a center
# -----------------------------------------------------------
#
# Sometimes we want to have a different colormap on either side of a
# conceptual center point, and we want those two colormaps to have
# different linear scales. An example is a topographic map where the land
# and ocean have a center at zero, but land typically has a greater
# elevation range than the water has depth range, and they are often
# represented by a different colormap.
filename = cbook.get_sample_data('topobathy.npz', asfileobj=False)
with np.load(filename) as dem:
topo = dem['topo']
longitude = dem['longitude']
latitude = dem['latitude']
fig, ax = plt.subplots()
# make a colormap that has land and ocean clearly delineated and of the
# same length (256 + 256)
colors_undersea = plt.cm.terrain(np.linspace(0, 0.17, 256))
colors_land = plt.cm.terrain(np.linspace(0.25, 1, 256))
all_colors = np.vstack((colors_undersea, colors_land))
terrain_map = colors.LinearSegmentedColormap.from_list('terrain_map',
all_colors)
# make the norm: Note the center is offset so that the land has more
# dynamic range:
divnorm = colors.DivergingNorm(vmin=-500., vcenter=0, vmax=4000)
pcm = ax.pcolormesh(longitude, latitude, topo, rasterized=True, norm=divnorm,
cmap=terrain_map,)
# Simple geographic plot, set aspect ratio beecause distance between lines of
# longitude depends on latitude.
ax.set_aspect(1 / np.cos(np.deg2rad(49)))
fig.colorbar(pcm, shrink=0.6)
plt.show()
###############################################################################
# Custom normalization: Manually implement two linear ranges
# ----------------------------------------------------------
#
# The `.DivergingNorm` described above makes a useful example for
# defining your own norm.
class MidpointNormalize(colors.Normalize):
def __init__(self, vmin=None, vmax=None, vcenter=None, clip=False):
self.vcenter = vcenter
colors.Normalize.__init__(self, vmin, vmax, clip)
def __call__(self, value, clip=None):
# I'm ignoring masked values and all kinds of edge cases to make a
# simple example...
x, y = [self.vmin, self.vcenter, self.vmax], [0, 0.5, 1]
return np.ma.masked_array(np.interp(value, x, y))
fig, ax = plt.subplots()
midnorm = MidpointNormalize(vmin=-500., vcenter=0, vmax=4000)
pcm = ax.pcolormesh(longitude, latitude, topo, rasterized=True, norm=midnorm,
cmap=terrain_map)
ax.set_aspect(1 / np.cos(np.deg2rad(49)))
fig.colorbar(pcm, shrink=0.6, extend='both')
plt.show()
|
78557d034dfe53622129ed11c301cdab57ee55bc6d26519a8020ab7fb29bc091
|
"""
********************************
Choosing Colormaps in Matplotlib
********************************
Matplotlib has a number of built-in colormaps accessible via
`.matplotlib.cm.get_cmap`. There are also external libraries like
[palettable]_ that have many extra colormaps. Here we briefly discuss
how to choose between the many options. For help on creating your
own colormaps, see :doc:`/tutorials/colors/colormap-manipulation`.
Overview
========
The idea behind choosing a good colormap is to find a good representation in 3D
colorspace for your data set. The best colormap for any given data set depends
on many things including:
- Whether representing form or metric data ([Ware]_)
- Your knowledge of the data set (*e.g.*, is there a critical value
from which the other values deviate?)
- If there is an intuitive color scheme for the parameter you are plotting
- If there is a standard in the field the audience may be expecting
For many applications, a perceptually uniform colormap is the best
choice --- one in which equal steps in data are perceived as equal
steps in the color space. Researchers have found that the human brain
perceives changes in the lightness parameter as changes in the data
much better than, for example, changes in hue. Therefore, colormaps
which have monotonically increasing lightness through the colormap
will be better interpreted by the viewer. A wonderful example of
perceptually uniform colormaps is [colorcet]_.
Color can be represented in 3D space in various ways. One way to represent color
is using CIELAB. In CIELAB, color space is represented by lightness,
:math:`L^*`; red-green, :math:`a^*`; and yellow-blue, :math:`b^*`. The lightness
parameter :math:`L^*` can then be used to learn more about how the matplotlib
colormaps will be perceived by viewers.
An excellent starting resource for learning about human perception of colormaps
is from [IBM]_.
Classes of colormaps
====================
Colormaps are often split into several categories based on their function (see,
*e.g.*, [Moreland]_):
1. Sequential: change in lightness and often saturation of color
incrementally, often using a single hue; should be used for
representing information that has ordering.
2. Diverging: change in lightness and possibly saturation of two
different colors that meet in the middle at an unsaturated color;
should be used when the information being plotted has a critical
middle value, such as topography or when the data deviates around
zero.
3. Cyclic: change in lightness of two different colors that meet in
the middle and beginning/end at an unsaturated color; should be
used for values that wrap around at the endpoints, such as phase
angle, wind direction, or time of day.
4. Qualitative: often are miscellaneous colors; should be used to
represent information which does not have ordering or
relationships.
"""
# sphinx_gallery_thumbnail_number = 2
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib import cm
from colorspacious import cspace_converter
from collections import OrderedDict
cmaps = OrderedDict()
###############################################################################
# Sequential
# ----------
#
# For the Sequential plots, the lightness value increases monotonically through
# the colormaps. This is good. Some of the :math:`L^*` values in the colormaps
# span from 0 to 100 (binary and the other grayscale), and others start around
# :math:`L^*=20`. Those that have a smaller range of :math:`L^*` will accordingly
# have a smaller perceptual range. Note also that the :math:`L^*` function varies
# amongst the colormaps: some are approximately linear in :math:`L^*` and others
# are more curved.
cmaps['Perceptually Uniform Sequential'] = [
'viridis', 'plasma', 'inferno', 'magma', 'cividis']
cmaps['Sequential'] = [
'Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds',
'YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu',
'GnBu', 'PuBu', 'YlGnBu', 'PuBuGn', 'BuGn', 'YlGn']
###############################################################################
# Sequential2
# -----------
#
# Many of the :math:`L^*` values from the Sequential2 plots are monotonically
# increasing, but some (autumn, cool, spring, and winter) plateau or even go both
# up and down in :math:`L^*` space. Others (afmhot, copper, gist_heat, and hot)
# have kinks in the :math:`L^*` functions. Data that is being represented in a
# region of the colormap that is at a plateau or kink will lead to a perception of
# banding of the data in those values in the colormap (see [mycarta-banding]_ for
# an excellent example of this).
cmaps['Sequential (2)'] = [
'binary', 'gist_yarg', 'gist_gray', 'gray', 'bone', 'pink',
'spring', 'summer', 'autumn', 'winter', 'cool', 'Wistia',
'hot', 'afmhot', 'gist_heat', 'copper']
###############################################################################
# Diverging
# ---------
#
# For the Diverging maps, we want to have monotonically increasing :math:`L^*`
# values up to a maximum, which should be close to :math:`L^*=100`, followed by
# monotonically decreasing :math:`L^*` values. We are looking for approximately
# equal minimum :math:`L^*` values at opposite ends of the colormap. By these
# measures, BrBG and RdBu are good options. coolwarm is a good option, but it
# doesn't span a wide range of :math:`L^*` values (see grayscale section below).
cmaps['Diverging'] = [
'PiYG', 'PRGn', 'BrBG', 'PuOr', 'RdGy', 'RdBu',
'RdYlBu', 'RdYlGn', 'Spectral', 'coolwarm', 'bwr', 'seismic']
###############################################################################
# Cyclic
# ------
#
# For Cyclic maps, we want to start and end on the same color, and meet a
# symmetric center point in the middle. :math:`L^*` should change monotonically
# from start to middle, and inversely from middle to end. It should be symmetric
# on the increasing and decreasing side, and only differ in hue. At the ends and
# middle, :math:`L^*` will reverse direction, which should be smoothed in
# :math:`L^*` space to reduce artifacts. See [kovesi-colormaps]_ for more
# information on the design of cyclic maps.
#
# The often-used HSV colormap is included in this set of colormaps, although it
# is not symmetric to a center point. Additionally, the :math:`L^*` values vary
# widely throughout the colormap, making it a poor choice for representing data
# for viewers to see perceptually. See an extension on this idea at
# [mycarta-jet]_.
cmaps['Cyclic'] = ['twilight', 'twilight_shifted', 'hsv']
###############################################################################
# Qualitative
# -----------
#
# Qualitative colormaps are not aimed at being perceptual maps, but looking at the
# lightness parameter can verify that for us. The :math:`L^*` values move all over
# the place throughout the colormap, and are clearly not monotonically increasing.
# These would not be good options for use as perceptual colormaps.
cmaps['Qualitative'] = ['Pastel1', 'Pastel2', 'Paired', 'Accent',
'Dark2', 'Set1', 'Set2', 'Set3',
'tab10', 'tab20', 'tab20b', 'tab20c']
###############################################################################
# Miscellaneous
# -------------
#
# Some of the miscellaneous colormaps have particular uses for which
# they have been created. For example, gist_earth, ocean, and terrain
# all seem to be created for plotting topography (green/brown) and water
# depths (blue) together. We would expect to see a divergence in these
# colormaps, then, but multiple kinks may not be ideal, such as in
# gist_earth and terrain. CMRmap was created to convert well to
# grayscale, though it does appear to have some small kinks in
# :math:`L^*`. cubehelix was created to vary smoothly in both lightness
# and hue, but appears to have a small hump in the green hue area.
#
# The often-used jet colormap is included in this set of colormaps. We can see
# that the :math:`L^*` values vary widely throughout the colormap, making it a
# poor choice for representing data for viewers to see perceptually. See an
# extension on this idea at [mycarta-jet]_.
cmaps['Miscellaneous'] = [
'flag', 'prism', 'ocean', 'gist_earth', 'terrain', 'gist_stern',
'gnuplot', 'gnuplot2', 'CMRmap', 'cubehelix', 'brg',
'gist_rainbow', 'rainbow', 'jet', 'nipy_spectral', 'gist_ncar']
###############################################################################
# .. _color-colormaps_reference:
#
# First, we'll show the range of each colormap. Note that some seem
# to change more "quickly" than others.
nrows = max(len(cmap_list) for cmap_category, cmap_list in cmaps.items())
gradient = np.linspace(0, 1, 256)
gradient = np.vstack((gradient, gradient))
def plot_color_gradients(cmap_category, cmap_list, nrows):
fig, axes = plt.subplots(nrows=nrows)
fig.subplots_adjust(top=0.95, bottom=0.01, left=0.2, right=0.99)
axes[0].set_title(cmap_category + ' colormaps', fontsize=14)
for ax, name in zip(axes, cmap_list):
ax.imshow(gradient, aspect='auto', cmap=plt.get_cmap(name))
pos = list(ax.get_position().bounds)
x_text = pos[0] - 0.01
y_text = pos[1] + pos[3]/2.
fig.text(x_text, y_text, name, va='center', ha='right', fontsize=10)
# Turn off *all* ticks & spines, not just the ones with colormaps.
for ax in axes:
ax.set_axis_off()
for cmap_category, cmap_list in cmaps.items():
plot_color_gradients(cmap_category, cmap_list, nrows)
plt.show()
###############################################################################
# Lightness of matplotlib colormaps
# =================================
#
# Here we examine the lightness values of the matplotlib colormaps.
# Note that some documentation on the colormaps is available
# ([list-colormaps]_).
mpl.rcParams.update({'font.size': 12})
# Number of colormap per subplot for particular cmap categories
_DSUBS = {'Perceptually Uniform Sequential': 5, 'Sequential': 6,
'Sequential (2)': 6, 'Diverging': 6, 'Cyclic': 3,
'Qualitative': 4, 'Miscellaneous': 6}
# Spacing between the colormaps of a subplot
_DC = {'Perceptually Uniform Sequential': 1.4, 'Sequential': 0.7,
'Sequential (2)': 1.4, 'Diverging': 1.4, 'Cyclic': 1.4,
'Qualitative': 1.4, 'Miscellaneous': 1.4}
# Indices to step through colormap
x = np.linspace(0.0, 1.0, 100)
# Do plot
for cmap_category, cmap_list in cmaps.items():
# Do subplots so that colormaps have enough space.
# Default is 6 colormaps per subplot.
dsub = _DSUBS.get(cmap_category, 6)
nsubplots = int(np.ceil(len(cmap_list) / dsub))
# squeeze=False to handle similarly the case of a single subplot
fig, axes = plt.subplots(nrows=nsubplots, squeeze=False,
figsize=(7, 2.6*nsubplots))
for i, ax in enumerate(axes.flat):
locs = [] # locations for text labels
for j, cmap in enumerate(cmap_list[i*dsub:(i+1)*dsub]):
# Get RGB values for colormap and convert the colormap in
# CAM02-UCS colorspace. lab[0, :, 0] is the lightness.
rgb = cm.get_cmap(cmap)(x)[np.newaxis, :, :3]
lab = cspace_converter("sRGB1", "CAM02-UCS")(rgb)
# Plot colormap L values. Do separately for each category
# so each plot can be pretty. To make scatter markers change
# color along plot:
# http://stackoverflow.com/questions/8202605/
if cmap_category == 'Sequential':
# These colormaps all start at high lightness but we want them
# reversed to look nice in the plot, so reverse the order.
y_ = lab[0, ::-1, 0]
c_ = x[::-1]
else:
y_ = lab[0, :, 0]
c_ = x
dc = _DC.get(cmap_category, 1.4) # cmaps horizontal spacing
ax.scatter(x + j*dc, y_, c=c_, cmap=cmap, s=300, linewidths=0.0)
# Store locations for colormap labels
if cmap_category in ('Perceptually Uniform Sequential',
'Sequential'):
locs.append(x[-1] + j*dc)
elif cmap_category in ('Diverging', 'Qualitative', 'Cyclic',
'Miscellaneous', 'Sequential (2)'):
locs.append(x[int(x.size/2.)] + j*dc)
# Set up the axis limits:
# * the 1st subplot is used as a reference for the x-axis limits
# * lightness values goes from 0 to 100 (y-axis limits)
ax.set_xlim(axes[0, 0].get_xlim())
ax.set_ylim(0.0, 100.0)
# Set up labels for colormaps
ax.xaxis.set_ticks_position('top')
ticker = mpl.ticker.FixedLocator(locs)
ax.xaxis.set_major_locator(ticker)
formatter = mpl.ticker.FixedFormatter(cmap_list[i*dsub:(i+1)*dsub])
ax.xaxis.set_major_formatter(formatter)
ax.xaxis.set_tick_params(rotation=50)
ax.set_xlabel(cmap_category + ' colormaps', fontsize=14)
fig.text(0.0, 0.55, 'Lightness $L^*$', fontsize=12,
transform=fig.transFigure, rotation=90)
fig.tight_layout(h_pad=0.0, pad=1.5)
plt.show()
###############################################################################
# Grayscale conversion
# ====================
#
# It is important to pay attention to conversion to grayscale for color
# plots, since they may be printed on black and white printers. If not
# carefully considered, your readers may end up with indecipherable
# plots because the grayscale changes unpredictably through the
# colormap.
#
# Conversion to grayscale is done in many different ways [bw]_. Some of the
# better ones use a linear combination of the rgb values of a pixel, but
# weighted according to how we perceive color intensity. A nonlinear method of
# conversion to grayscale is to use the :math:`L^*` values of the pixels. In
# general, similar principles apply for this question as they do for presenting
# one's information perceptually; that is, if a colormap is chosen that is
# monotonically increasing in :math:`L^*` values, it will print in a reasonable
# manner to grayscale.
#
# With this in mind, we see that the Sequential colormaps have reasonable
# representations in grayscale. Some of the Sequential2 colormaps have decent
# enough grayscale representations, though some (autumn, spring, summer,
# winter) have very little grayscale change. If a colormap like this was used
# in a plot and then the plot was printed to grayscale, a lot of the
# information may map to the same gray values. The Diverging colormaps mostly
# vary from darker gray on the outer edges to white in the middle. Some
# (PuOr and seismic) have noticeably darker gray on one side than the other
# and therefore are not very symmetric. coolwarm has little range of gray scale
# and would print to a more uniform plot, losing a lot of detail. Note that
# overlaid, labeled contours could help differentiate between one side of the
# colormap vs. the other since color cannot be used once a plot is printed to
# grayscale. Many of the Qualitative and Miscellaneous colormaps, such as
# Accent, hsv, and jet, change from darker to lighter and back to darker gray
# throughout the colormap. This would make it impossible for a viewer to
# interpret the information in a plot once it is printed in grayscale.
mpl.rcParams.update({'font.size': 14})
# Indices to step through colormap.
x = np.linspace(0.0, 1.0, 100)
gradient = np.linspace(0, 1, 256)
gradient = np.vstack((gradient, gradient))
def plot_color_gradients(cmap_category, cmap_list):
fig, axes = plt.subplots(nrows=len(cmap_list), ncols=2)
fig.subplots_adjust(top=0.95, bottom=0.01, left=0.2, right=0.99,
wspace=0.05)
fig.suptitle(cmap_category + ' colormaps', fontsize=14, y=1.0, x=0.6)
for ax, name in zip(axes, cmap_list):
# Get RGB values for colormap.
rgb = cm.get_cmap(plt.get_cmap(name))(x)[np.newaxis, :, :3]
# Get colormap in CAM02-UCS colorspace. We want the lightness.
lab = cspace_converter("sRGB1", "CAM02-UCS")(rgb)
L = lab[0, :, 0]
L = np.float32(np.vstack((L, L, L)))
ax[0].imshow(gradient, aspect='auto', cmap=plt.get_cmap(name))
ax[1].imshow(L, aspect='auto', cmap='binary_r', vmin=0., vmax=100.)
pos = list(ax[0].get_position().bounds)
x_text = pos[0] - 0.01
y_text = pos[1] + pos[3]/2.
fig.text(x_text, y_text, name, va='center', ha='right', fontsize=10)
# Turn off *all* ticks & spines, not just the ones with colormaps.
for ax in axes.flat:
ax.set_axis_off()
plt.show()
for cmap_category, cmap_list in cmaps.items():
plot_color_gradients(cmap_category, cmap_list)
###############################################################################
# Color vision deficiencies
# =========================
#
# There is a lot of information available about color blindness (*e.g.*,
# [colorblindness]_). Additionally, there are tools available to convert images
# to how they look for different types of color vision deficiencies (*e.g.*,
# [vischeck]_).
#
# The most common form of color vision deficiency involves differentiating
# between red and green. Thus, avoiding colormaps with both red and green will
# avoid many problems in general.
#
#
# References
# ==========
#
# .. [colorcet] https://github.com/bokeh/colorcet
# .. [Ware] http://ccom.unh.edu/sites/default/files/publications/Ware_1988_CGA_Color_sequences_univariate_maps.pdf
# .. [Moreland] http://www.kennethmoreland.com/color-maps/ColorMapsExpanded.pdf
# .. [list-colormaps] https://gist.github.com/endolith/2719900#id7
# .. [mycarta-banding] https://mycarta.wordpress.com/2012/10/14/the-rainbow-is-deadlong-live-the-rainbow-part-4-cie-lab-heated-body/
# .. [mycarta-jet] https://mycarta.wordpress.com/2012/10/06/the-rainbow-is-deadlong-live-the-rainbow-part-3/
# .. [kovesi-colormaps] https://arxiv.org/abs/1509.03700
# .. [bw] http://www.tannerhelland.com/3643/grayscale-image-algorithm-vb6/
# .. [colorblindness] http://www.color-blindness.com/
# .. [vischeck] http://www.vischeck.com/vischeck/
# .. [IBM] https://doi.org/10.1109/VISUAL.1995.480803
# .. [palettable] https://jiffyclub.github.io/palettable/
|
0fe7837a262b1917cd7ada50129aae288b17277676b1e3748cbb2f4291a97422
|
"""
********************************
Creating Colormaps in Matplotlib
********************************
Matplotlib has a number of built-in colormaps accessible via
`.matplotlib.cm.get_cmap`. There are also external libraries like
palettable_ that have many extra colormaps.
.. _palettable: https://jiffyclub.github.io/palettable/
However, we often want to create or manipulate colormaps in Matplotlib.
This can be done using the class `.ListedColormap` and a Nx4 numpy array of
values between 0 and 1 to represent the RGBA values of the colormap. There
is also a `.LinearSegmentedColormap` class that allows colormaps to be
specified with a few anchor points defining segments, and linearly
interpolating between the anchor points.
Getting colormaps and accessing their values
============================================
First, getting a named colormap, most of which are listed in
:doc:`/tutorials/colors/colormaps` requires the use of
`.matplotlib.cm.get_cmap`, which returns a
:class:`.matplotlib.colors.ListedColormap` object. The second argument gives
the size of the list of colors used to define the colormap, and below we
use a modest value of 12 so there are not a lot of values to look at.
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.colors import ListedColormap, LinearSegmentedColormap
viridis = cm.get_cmap('viridis', 12)
print(viridis)
##############################################################################
# The object ``viridis`` is a callable, that when passed a float between
# 0 and 1 returns an RGBA value from the colormap:
print(viridis(0.56))
##############################################################################
# The list of colors that comprise the colormap can be directly accessed using
# the ``colors`` property,
# or it can be accessed indirectly by calling ``viridis`` with an array
# of values matching the length of the colormap. Note that the returned list
# is in the form of an RGBA Nx4 array, where N is the length of the colormap.
print('viridis.colors', viridis.colors)
print('viridis(range(12))', viridis(range(12)))
print('viridis(np.linspace(0, 1, 12))', viridis(np.linspace(0, 1, 12)))
##############################################################################
# The colormap is a lookup table, so "oversampling" the colormap returns
# nearest-neighbor interpolation (note the repeated colors in the list below)
print('viridis(np.linspace(0, 1, 15))', viridis(np.linspace(0, 1, 15)))
##############################################################################
# Creating listed colormaps
# =========================
#
# This is essential the inverse operation of the above where we supply a
# Nx4 numpy array with all values between 0 and 1,
# to `.ListedColormap` to make a new colormap. This means that
# any numpy operations that we can do on a Nx4 array make carpentry of
# new colormaps from existing colormaps quite straight forward.
#
# Suppose we want to make the first 25 entries of a 256-length "viridis"
# colormap pink for some reason:
viridis = cm.get_cmap('viridis', 256)
newcolors = viridis(np.linspace(0, 1, 256))
pink = np.array([248/256, 24/256, 148/256, 1])
newcolors[:25, :] = pink
newcmp = ListedColormap(newcolors)
def plot_examples(cms):
"""
helper function to plot two colormaps
"""
np.random.seed(19680801)
data = np.random.randn(30, 30)
fig, axs = plt.subplots(1, 2, figsize=(6, 3), constrained_layout=True)
for [ax, cmap] in zip(axs, cms):
psm = ax.pcolormesh(data, cmap=cmap, rasterized=True, vmin=-4, vmax=4)
fig.colorbar(psm, ax=ax)
plt.show()
plot_examples([viridis, newcmp])
##############################################################################
# We can easily reduce the dynamic range of a colormap; here we choose the
# middle 0.5 of the colormap. However, we need to interpolate from a larger
# colormap, otherwise the new colormap will have repeated values.
viridisBig = cm.get_cmap('viridis', 512)
newcmp = ListedColormap(viridisBig(np.linspace(0.25, 0.75, 256)))
plot_examples([viridis, newcmp])
##############################################################################
# and we can easily concatenate two colormaps:
top = cm.get_cmap('Oranges_r', 128)
bottom = cm.get_cmap('Blues', 128)
newcolors = np.vstack((top(np.linspace(0, 1, 128)),
bottom(np.linspace(0, 1, 128))))
newcmp = ListedColormap(newcolors, name='OrangeBlue')
plot_examples([viridis, newcmp])
##############################################################################
# Of course we need not start from a named colormap, we just need to create
# the Nx4 array to pass to `.ListedColormap`. Here we create a
# brown colormap that goes to white....
N = 256
vals = np.ones((N, 4))
vals[:, 0] = np.linspace(90/256, 1, N)
vals[:, 1] = np.linspace(39/256, 1, N)
vals[:, 2] = np.linspace(41/256, 1, N)
newcmp = ListedColormap(vals)
plot_examples([viridis, newcmp])
##############################################################################
# Creating linear segmented colormaps
# ===================================
#
# `.LinearSegmentedColormap` class specifies colormaps using anchor points
# between which RGB(A) values are interpolated.
#
# The format to specify these colormaps allows discontinuities at the anchor
# points. Each anchor point is specified as a row in a matrix of the
# form ``[x[i] yleft[i] yright[i]]``, where ``x[i]`` is the anchor, and
# ``yleft[i]`` and ``yright[i]`` are the values of the color on either
# side of the anchor point.
#
# If there are no discontinuities, then ``yleft[i]=yright[i]``:
cdict = {'red': [[0.0, 0.0, 0.0],
[0.5, 1.0, 1.0],
[1.0, 1.0, 1.0]],
'green': [[0.0, 0.0, 0.0],
[0.25, 0.0, 0.0],
[0.75, 1.0, 1.0],
[1.0, 1.0, 1.0]],
'blue': [[0.0, 0.0, 0.0],
[0.5, 0.0, 0.0],
[1.0, 1.0, 1.0]]}
def plot_linearmap(cdict):
newcmp = LinearSegmentedColormap('testCmap', segmentdata=cdict, N=256)
rgba = newcmp(np.linspace(0, 1, 256))
fig, ax = plt.subplots(figsize=(4, 3), constrained_layout=True)
col = ['r', 'g', 'b']
for xx in [0.25, 0.5, 0.75]:
ax.axvline(xx, color='0.7', linestyle='--')
for i in range(3):
ax.plot(np.arange(256)/256, rgba[:, i], color=col[i])
ax.set_xlabel('index')
ax.set_ylabel('RGB')
plt.show()
plot_linearmap(cdict)
#############################################################################
# In order to make a discontinuity at an anchor point, the third column is
# different than the second. The matrix for each of "red", "green", "blue",
# and optionally "alpha" is set up as::
#
# cdict['red'] = [...
# [x[i] yleft[i] yright[i]],
# [x[i+1] yleft[i+1] yright[i+1]],
# ...]
#
# and for values passed to the colormap between ``x[i]`` and ``x[i+1]``,
# the interpolation is between ``yright[i]`` and ``yleft[i+1]``.
#
# In the example below there is a discontinuity in red at 0.5. The
# interpolation between 0 and 0.5 goes from 0.3 to 1, and between 0.5 and 1
# it goes from 0.9 to 1. Note that red[0, 1], and red[2, 2] are both
# superfluous to the interpolation because red[0, 1] is the value to the
# left of 0, and red[2, 2] is the value to the right of 1.0.
cdict['red'] = [[0.0, 0.0, 0.3],
[0.5, 1.0, 0.9],
[1.0, 1.0, 1.0]]
plot_linearmap(cdict)
#############################################################################
#
# ------------
#
# References
# """"""""""
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
import matplotlib
matplotlib.axes.Axes.pcolormesh
matplotlib.figure.Figure.colorbar
matplotlib.colors
matplotlib.colors.LinearSegmentedColormap
matplotlib.colors.ListedColormap
matplotlib.cm
matplotlib.cm.get_cmap
|
df8218c43606b77b985d4c738ddeea534e656a45c0ad7645dd22f9ed0ebf2203
|
"""
***********
Usage Guide
***********
This tutorial covers some basic usage patterns and best-practices to
help you get started with Matplotlib.
.. _general_concepts:
General Concepts
================
:mod:`matplotlib` has an extensive codebase that can be daunting to many
new users. However, most of matplotlib can be understood with a fairly
simple conceptual framework and knowledge of a few important points.
Plotting requires action on a range of levels, from the most general
(e.g., 'contour this 2-D array') to the most specific (e.g., 'color
this screen pixel red'). The purpose of a plotting package is to assist
you in visualizing your data as easily as possible, with all the necessary
control -- that is, by using relatively high-level commands most of
the time, and still have the ability to use the low-level commands when
needed.
Therefore, everything in matplotlib is organized in a hierarchy. At the top
of the hierarchy is the matplotlib "state-machine environment" which is
provided by the :mod:`matplotlib.pyplot` module. At this level, simple
functions are used to add plot elements (lines, images, text, etc.) to
the current axes in the current figure.
.. note::
Pyplot's state-machine environment behaves similarly to MATLAB and
should be most familiar to users with MATLAB experience.
The next level down in the hierarchy is the first level of the object-oriented
interface, in which pyplot is used only for a few functions such as figure
creation, and the user explicitly creates and keeps track of the figure
and axes objects. At this level, the user uses pyplot to create figures,
and through those figures, one or more axes objects can be created. These
axes objects are then used for most plotting actions.
For even more control -- which is essential for things like embedding
matplotlib plots in GUI applications -- the pyplot level may be dropped
completely, leaving a purely object-oriented approach.
"""
# sphinx_gallery_thumbnail_number = 3
import matplotlib.pyplot as plt
import numpy as np
###############################################################################
# .. _figure_parts:
#
# Parts of a Figure
# =================
#
# .. image:: ../../_static/anatomy.png
#
#
# :class:`~matplotlib.figure.Figure`
# ----------------------------------
#
# The **whole** figure. The figure keeps
# track of all the child :class:`~matplotlib.axes.Axes`, a smattering of
# 'special' artists (titles, figure legends, etc), and the **canvas**.
# (Don't worry too much about the canvas, it is crucial as it is the
# object that actually does the drawing to get you your plot, but as the
# user it is more-or-less invisible to you). A figure can have any
# number of :class:`~matplotlib.axes.Axes`, but to be useful should have
# at least one.
#
# The easiest way to create a new figure is with pyplot:
fig = plt.figure() # an empty figure with no axes
fig.suptitle('No axes on this figure') # Add a title so we know which it is
fig, ax_lst = plt.subplots(2, 2) # a figure with a 2x2 grid of Axes
###############################################################################
# :class:`~matplotlib.axes.Axes`
# ------------------------------
#
# This is what you think of as 'a plot', it is the region of the image
# with the data space. A given figure
# can contain many Axes, but a given :class:`~matplotlib.axes.Axes`
# object can only be in one :class:`~matplotlib.figure.Figure`. The
# Axes contains two (or three in the case of 3D)
# :class:`~matplotlib.axis.Axis` objects (be aware of the difference
# between **Axes** and **Axis**) which take care of the data limits (the
# data limits can also be controlled via set via the
# :meth:`~matplotlib.axes.Axes.set_xlim` and
# :meth:`~matplotlib.axes.Axes.set_ylim` :class:`Axes` methods). Each
# :class:`Axes` has a title (set via
# :meth:`~matplotlib.axes.Axes.set_title`), an x-label (set via
# :meth:`~matplotlib.axes.Axes.set_xlabel`), and a y-label set via
# :meth:`~matplotlib.axes.Axes.set_ylabel`).
#
# The :class:`Axes` class and it's member functions are the primary entry
# point to working with the OO interface.
#
# :class:`~matplotlib.axis.Axis`
# ------------------------------
#
# These are the number-line-like objects. They take
# care of setting the graph limits and generating the ticks (the marks
# on the axis) and ticklabels (strings labeling the ticks). The
# location of the ticks is determined by a
# :class:`~matplotlib.ticker.Locator` object and the ticklabel strings
# are formatted by a :class:`~matplotlib.ticker.Formatter`. The
# combination of the correct :class:`Locator` and :class:`Formatter` gives
# very fine control over the tick locations and labels.
#
# :class:`~matplotlib.artist.Artist`
# ----------------------------------
#
# Basically everything you can see on the figure is an artist (even the
# :class:`Figure`, :class:`Axes`, and :class:`Axis` objects). This
# includes :class:`Text` objects, :class:`Line2D` objects,
# :class:`collection` objects, :class:`Patch` objects ... (you get the
# idea). When the figure is rendered, all of the artists are drawn to
# the **canvas**. Most Artists are tied to an Axes; such an Artist
# cannot be shared by multiple Axes, or moved from one to another.
#
# .. _input_types:
#
# Types of inputs to plotting functions
# =====================================
#
# All of plotting functions expect `np.array` or `np.ma.masked_array` as
# input. Classes that are 'array-like' such as `pandas` data objects
# and `np.matrix` may or may not work as intended. It is best to
# convert these to `np.array` objects prior to plotting.
#
# For example, to convert a `pandas.DataFrame` ::
#
# a = pandas.DataFrame(np.random.rand(4,5), columns = list('abcde'))
# a_asarray = a.values
#
# and to convert a `np.matrix` ::
#
# b = np.matrix([[1,2],[3,4]])
# b_asarray = np.asarray(b)
#
# .. _pylab:
#
# Matplotlib, pyplot and pylab: how are they related?
# ====================================================
#
# Matplotlib is the whole package; :mod:`matplotlib.pyplot`
# is a module in matplotlib; and :mod:`pylab` is a module
# that gets installed alongside :mod:`matplotlib`.
#
# Pyplot provides the state-machine interface to the underlying
# object-oriented plotting library. The state-machine implicitly and
# automatically creates figures and axes to achieve the desired
# plot. For example:
x = np.linspace(0, 2, 100)
plt.plot(x, x, label='linear')
plt.plot(x, x**2, label='quadratic')
plt.plot(x, x**3, label='cubic')
plt.xlabel('x label')
plt.ylabel('y label')
plt.title("Simple Plot")
plt.legend()
plt.show()
###############################################################################
# The first call to ``plt.plot`` will automatically create the necessary
# figure and axes to achieve the desired plot. Subsequent calls to
# ``plt.plot`` re-use the current axes and each add another line.
# Setting the title, legend, and axis labels also automatically use the
# current axes and set the title, create the legend, and label the axis
# respectively.
#
# :mod:`pylab` is a convenience module that bulk imports
# :mod:`matplotlib.pyplot` (for plotting) and :mod:`numpy`
# (for mathematics and working with arrays) in a single name space.
# pylab is deprecated and its use is strongly discouraged because
# of namespace pollution. Use pyplot instead.
#
# For non-interactive plotting it is suggested
# to use pyplot to create the figures and then the OO interface for
# plotting.
#
# .. _coding_styles:
#
# Coding Styles
# ==================
#
# When viewing this documentation and examples, you will find different
# coding styles and usage patterns. These styles are perfectly valid
# and have their pros and cons. Just about all of the examples can be
# converted into another style and achieve the same results.
# The only caveat is to avoid mixing the coding styles for your own code.
#
# .. note::
# Developers for matplotlib have to follow a specific style and guidelines.
# See :ref:`developers-guide-index`.
#
# Of the different styles, there are two that are officially supported.
# Therefore, these are the preferred ways to use matplotlib.
#
# For the pyplot style, the imports at the top of your
# scripts will typically be::
#
# import matplotlib.pyplot as plt
# import numpy as np
#
# Then one calls, for example, np.arange, np.zeros, np.pi, plt.figure,
# plt.plot, plt.show, etc. Use the pyplot interface
# for creating figures, and then use the object methods for the rest:
x = np.arange(0, 10, 0.2)
y = np.sin(x)
fig, ax = plt.subplots()
ax.plot(x, y)
plt.show()
###############################################################################
# So, why all the extra typing instead of the MATLAB-style (which relies
# on global state and a flat namespace)? For very simple things like
# this example, the only advantage is academic: the wordier styles are
# more explicit, more clear as to where things come from and what is
# going on. For more complicated applications, this explicitness and
# clarity becomes increasingly valuable, and the richer and more
# complete object-oriented interface will likely make the program easier
# to write and maintain.
#
#
# Typically one finds oneself making the same plots over and over
# again, but with different data sets, which leads to needing to write
# specialized functions to do the plotting. The recommended function
# signature is something like:
def my_plotter(ax, data1, data2, param_dict):
"""
A helper function to make a graph
Parameters
----------
ax : Axes
The axes to draw to
data1 : array
The x data
data2 : array
The y data
param_dict : dict
Dictionary of kwargs to pass to ax.plot
Returns
-------
out : list
list of artists added
"""
out = ax.plot(data1, data2, **param_dict)
return out
# which you would then use as:
data1, data2, data3, data4 = np.random.randn(4, 100)
fig, ax = plt.subplots(1, 1)
my_plotter(ax, data1, data2, {'marker': 'x'})
###############################################################################
# or if you wanted to have 2 sub-plots:
fig, (ax1, ax2) = plt.subplots(1, 2)
my_plotter(ax1, data1, data2, {'marker': 'x'})
my_plotter(ax2, data3, data4, {'marker': 'o'})
###############################################################################
# Again, for these simple examples this style seems like overkill, however
# once the graphs get slightly more complex it pays off.
#
#
# .. _backends:
#
# Backends
# ========
#
# .. _what-is-a-backend:
#
# What is a backend?
# ------------------
#
# A lot of documentation on the website and in the mailing lists refers
# to the "backend" and many new users are confused by this term.
# matplotlib targets many different use cases and output formats. Some
# people use matplotlib interactively from the python shell and have
# plotting windows pop up when they type commands. Some people run
# `Jupyter <https://jupyter.org>`_ notebooks and draw inline plots for
# quick data analysis. Others embed matplotlib into graphical user
# interfaces like wxpython or pygtk to build rich applications. Some
# people use matplotlib in batch scripts to generate postscript images
# from numerical simulations, and still others run web application
# servers to dynamically serve up graphs.
#
# To support all of these use cases, matplotlib can target different
# outputs, and each of these capabilities is called a backend; the
# "frontend" is the user facing code, i.e., the plotting code, whereas the
# "backend" does all the hard work behind-the-scenes to make the figure.
# There are two types of backends: user interface backends (for use in
# pygtk, wxpython, tkinter, qt4, or macosx; also referred to as
# "interactive backends") and hardcopy backends to make image files
# (PNG, SVG, PDF, PS; also referred to as "non-interactive backends").
#
# There are four ways to configure your backend. If they conflict each other,
# the method mentioned last in the following list will be used, e.g. calling
# :func:`~matplotlib.use()` will override the setting in your ``matplotlibrc``.
#
#
# #. The ``backend`` parameter in your ``matplotlibrc`` file (see
# :doc:`/tutorials/introductory/customizing`)::
#
# backend : WXAgg # use wxpython with antigrain (agg) rendering
#
# #. Setting the :envvar:`MPLBACKEND` environment variable, either for your
# current shell or for a single script. On Unix::
#
# > export MPLBACKEND=module://my_backend
# > python simple_plot.py
#
# > MPLBACKEND="module://my_backend" python simple_plot.py
#
# On Windows, only the former is possible::
#
# > set MPLBACKEND=module://my_backend
# > python simple_plot.py
#
# Setting this environment variable will override the ``backend`` parameter
# in *any* ``matplotlibrc``, even if there is a ``matplotlibrc`` in your
# current working directory. Therefore setting :envvar:`MPLBACKEND`
# globally, e.g. in your ``.bashrc`` or ``.profile``, is discouraged as it
# might lead to counter-intuitive behavior.
#
# #. If your script depends on a specific backend you can use the
# :func:`~matplotlib.use` function::
#
# import matplotlib
# matplotlib.use('PS') # generate postscript output by default
#
# If you use the :func:`~matplotlib.use` function, this must be done before
# importing :mod:`matplotlib.pyplot`. Calling :func:`~matplotlib.use` after
# pyplot has been imported will have no effect. Using
# :func:`~matplotlib.use` will require changes in your code if users want to
# use a different backend. Therefore, you should avoid explicitly calling
# :func:`~matplotlib.use` unless absolutely necessary.
#
# .. note::
# Backend name specifications are not case-sensitive; e.g., 'GTK3Agg'
# and 'gtk3agg' are equivalent.
#
# With a typical installation of matplotlib, such as from a
# binary installer or a linux distribution package, a good default
# backend will already be set, allowing both interactive work and
# plotting from scripts, with output to the screen and/or to
# a file, so at least initially you will not need to use any of the
# methods given above.
#
# If, however, you want to write graphical user interfaces, or a web
# application server (:ref:`howto-webapp`), or need a better
# understanding of what is going on, read on. To make things a little
# more customizable for graphical user interfaces, matplotlib separates
# the concept of the renderer (the thing that actually does the drawing)
# from the canvas (the place where the drawing goes). The canonical
# renderer for user interfaces is ``Agg`` which uses the `Anti-Grain
# Geometry`_ C++ library to make a raster (pixel) image of the figure.
# All of the user interfaces except ``macosx`` can be used with
# agg rendering, e.g., ``WXAgg``, ``GTK3Agg``, ``QT4Agg``, ``QT5Agg``,
# ``TkAgg``. In addition, some of the user interfaces support other rendering
# engines. For example, with GTK+ 3, you can also select Cairo rendering
# (backend ``GTK3Cairo``).
#
# For the rendering engines, one can also distinguish between `vector
# <https://en.wikipedia.org/wiki/Vector_graphics>`_ or `raster
# <https://en.wikipedia.org/wiki/Raster_graphics>`_ renderers. Vector
# graphics languages issue drawing commands like "draw a line from this
# point to this point" and hence are scale free, and raster backends
# generate a pixel representation of the line whose accuracy depends on a
# DPI setting.
#
# Here is a summary of the matplotlib renderers (there is an eponymous
# backend for each; these are *non-interactive backends*, capable of
# writing to a file):
#
# ============= ============ ================================================
# Renderer Filetypes Description
# ============= ============ ================================================
# :term:`AGG` :term:`png` :term:`raster graphics` -- high quality images
# using the `Anti-Grain Geometry`_ engine
# PS :term:`ps` :term:`vector graphics` -- Postscript_ output
# :term:`eps`
# PDF :term:`pdf` :term:`vector graphics` --
# `Portable Document Format`_
# SVG :term:`svg` :term:`vector graphics` --
# `Scalable Vector Graphics`_
# :term:`Cairo` :term:`png` :term:`raster graphics` and
# :term:`ps` :term:`vector graphics` -- using the
# :term:`pdf` `Cairo graphics`_ library
# :term:`svg`
# ============= ============ ================================================
#
# And here are the user interfaces and renderer combinations supported;
# these are *interactive backends*, capable of displaying to the screen
# and of using appropriate renderers from the table above to write to
# a file:
#
# ========= ================================================================
# Backend Description
# ========= ================================================================
# Qt5Agg Agg rendering in a :term:`Qt5` canvas (requires PyQt5_). This
# backend can be activated in IPython with ``%matplotlib qt5``.
# ipympl Agg rendering embedded in a Jupyter widget. (requires ipympl).
# This backend can be enabled in a Jupyter notebook with
# ``%matplotlib ipympl``.
# GTK3Agg Agg rendering to a :term:`GTK` 3.x canvas (requires PyGObject_,
# and pycairo_ or cairocffi_). This backend can be activated in
# IPython with ``%matplotlib gtk3``.
# macosx Agg rendering into a Cocoa canvas in OSX. This backend can be
# activated in IPython with ``%matplotlib osx``.
# TkAgg Agg rendering to a :term:`Tk` canvas (requires TkInter_). This
# backend can be activated in IPython with ``%matplotlib tk``.
# nbAgg Embed an interactive figure in a Jupyter classic notebook. This
# backend can be enabled in Jupyter notebooks via
# ``%matplotlib notebook``.
# WebAgg On ``show()`` will start a tornado server with an interactive
# figure.
# GTK3Cairo Cairo rendering to a :term:`GTK` 3.x canvas (requires PyGObject_,
# and pycairo_ or cairocffi_).
# Qt4Agg Agg rendering to a :term:`Qt4` canvas (requires PyQt4_ or
# ``pyside``). This backend can be activated in IPython with
# ``%matplotlib qt4``.
# WXAgg Agg rendering to a :term:`wxWidgets` canvas (requires wxPython_ 4).
# This backend can be activated in IPython with ``%matplotlib wx``.
# ========= ================================================================
#
# .. _`Anti-Grain Geometry`: http://antigrain.com/
# .. _Postscript: https://en.wikipedia.org/wiki/PostScript
# .. _`Portable Document Format`: https://en.wikipedia.org/wiki/Portable_Document_Format
# .. _`Scalable Vector Graphics`: https://en.wikipedia.org/wiki/Scalable_Vector_Graphics
# .. _`Cairo graphics`: https://wwW.cairographics.org
# .. _PyGObject: https://wiki.gnome.org/action/show/Projects/PyGObject
# .. _pycairo: https://www.cairographics.org/pycairo/
# .. _cairocffi: https://pythonhosted.org/cairocffi/
# .. _wxPython: https://www.wxpython.org/
# .. _TkInter: https://wiki.python.org/moin/TkInter
# .. _PyQt4: https://riverbankcomputing.com/software/pyqt/intro
# .. _PyQt5: https://riverbankcomputing.com/software/pyqt/intro
#
# ipympl
# ------
#
# The Jupyter widget ecosystem is moving too fast to support directly in
# Matplotlib. To install ipympl
#
# .. code-block:: bash
#
# pip install ipympl
# jupyter nbextension enable --py --sys-prefix ipympl
#
# or
#
# .. code-block:: bash
#
# conda install ipympl -c conda-forge
#
# See `jupyter-matplotlib <https://github.com/matplotlib/jupyter-matplotlib>`__
# for more details.
#
# GTK and Cairo
# -------------
#
# `GTK3` backends (*both* `GTK3Agg` and `GTK3Cairo`) depend on Cairo
# (pycairo>=1.11.0 or cairocffi).
#
# How do I select PyQt4 or PySide?
# --------------------------------
#
# The `QT_API` environment variable can be set to either `pyqt` or `pyside`
# to use `PyQt4` or `PySide`, respectively.
#
# Since the default value for the bindings to be used is `PyQt4`,
# :mod:`matplotlib` first tries to import it, if the import fails, it tries to
# import `PySide`.
#
# .. _interactive-mode:
#
# What is interactive mode?
# ===================================
#
# Use of an interactive backend (see :ref:`what-is-a-backend`)
# permits--but does not by itself require or ensure--plotting
# to the screen. Whether and when plotting to the screen occurs,
# and whether a script or shell session continues after a plot
# is drawn on the screen, depends on the functions and methods
# that are called, and on a state variable that determines whether
# matplotlib is in "interactive mode". The default Boolean value is set
# by the :file:`matplotlibrc` file, and may be customized like any other
# configuration parameter (see :doc:`/tutorials/introductory/customizing`). It
# may also be set via :func:`matplotlib.interactive`, and its
# value may be queried via :func:`matplotlib.is_interactive`. Turning
# interactive mode on and off in the middle of a stream of plotting
# commands, whether in a script or in a shell, is rarely needed
# and potentially confusing, so in the following we will assume all
# plotting is done with interactive mode either on or off.
#
# .. note::
# Major changes related to interactivity, and in particular the
# role and behavior of :func:`~matplotlib.pyplot.show`, were made in the
# transition to matplotlib version 1.0, and bugs were fixed in
# 1.0.1. Here we describe the version 1.0.1 behavior for the
# primary interactive backends, with the partial exception of
# *macosx*.
#
# Interactive mode may also be turned on via :func:`matplotlib.pyplot.ion`,
# and turned off via :func:`matplotlib.pyplot.ioff`.
#
# .. note::
# Interactive mode works with suitable backends in ipython and in
# the ordinary python shell, but it does *not* work in the IDLE IDE.
# If the default backend does not support interactivity, an interactive
# backend can be explicitly activated using any of the methods discussed in `What is a backend?`_.
#
#
# Interactive example
# --------------------
#
# From an ordinary python prompt, or after invoking ipython with no options,
# try this::
#
# import matplotlib.pyplot as plt
# plt.ion()
# plt.plot([1.6, 2.7])
#
# Assuming you are running version 1.0.1 or higher, and you have
# an interactive backend installed and selected by default, you should
# see a plot, and your terminal prompt should also be active; you
# can type additional commands such as::
#
# plt.title("interactive test")
# plt.xlabel("index")
#
# and you will see the plot being updated after each line. Since version 1.5,
# modifying the plot by other means *should* also automatically
# update the display on most backends. Get a reference to the :class:`~matplotlib.axes.Axes` instance,
# and call a method of that instance::
#
# ax = plt.gca()
# ax.plot([3.1, 2.2])
#
# If you are using certain backends (like `macosx`), or an older version
# of matplotlib, you may not see the new line added to the plot immediately.
# In this case, you need to explicitly call :func:`~matplotlib.pyplot.draw`
# in order to update the plot::
#
# plt.draw()
#
#
# Non-interactive example
# -----------------------
#
# Start a fresh session as in the previous example, but now
# turn interactive mode off::
#
# import matplotlib.pyplot as plt
# plt.ioff()
# plt.plot([1.6, 2.7])
#
# Nothing happened--or at least nothing has shown up on the
# screen (unless you are using *macosx* backend, which is
# anomalous). To make the plot appear, you need to do this::
#
# plt.show()
#
# Now you see the plot, but your terminal command line is
# unresponsive; the :func:`show()` command *blocks* the input
# of additional commands until you manually kill the plot
# window.
#
# What good is this--being forced to use a blocking function?
# Suppose you need a script that plots the contents of a file
# to the screen. You want to look at that plot, and then end
# the script. Without some blocking command such as show(), the
# script would flash up the plot and then end immediately,
# leaving nothing on the screen.
#
# In addition, non-interactive mode delays all drawing until
# show() is called; this is more efficient than redrawing
# the plot each time a line in the script adds a new feature.
#
# Prior to version 1.0, show() generally could not be called
# more than once in a single script (although sometimes one
# could get away with it); for version 1.0.1 and above, this
# restriction is lifted, so one can write a script like this::
#
# import numpy as np
# import matplotlib.pyplot as plt
#
# plt.ioff()
# for i in range(3):
# plt.plot(np.random.rand(10))
# plt.show()
#
# which makes three plots, one at a time. I.e. the second plot will show up,
# once the first plot is closed.
#
# Summary
# -------
#
# In interactive mode, pyplot functions automatically draw
# to the screen.
#
# When plotting interactively, if using
# object method calls in addition to pyplot functions, then
# call :func:`~matplotlib.pyplot.draw` whenever you want to
# refresh the plot.
#
# Use non-interactive mode in scripts in which you want to
# generate one or more figures and display them before ending
# or generating a new set of figures. In that case, use
# :func:`~matplotlib.pyplot.show` to display the figure(s) and
# to block execution until you have manually destroyed them.
#
# .. _performance:
#
# Performance
# ===========
#
# Whether exploring data in interactive mode or programmatically
# saving lots of plots, rendering performance can be a painful
# bottleneck in your pipeline. Matplotlib provides a couple
# ways to greatly reduce rendering time at the cost of a slight
# change (to a settable tolerance) in your plot's appearance.
# The methods available to reduce rendering time depend on the
# type of plot that is being created.
#
# Line segment simplification
# ---------------------------
#
# For plots that have line segments (e.g. typical line plots,
# outlines of polygons, etc.), rendering performance can be
# controlled by the ``path.simplify`` and
# ``path.simplify_threshold`` parameters in your
# ``matplotlibrc`` file (see
# :doc:`/tutorials/introductory/customizing` for
# more information about the ``matplotlibrc`` file).
# The ``path.simplify`` parameter is a boolean indicating whether
# or not line segments are simplified at all. The
# ``path.simplify_threshold`` parameter controls how much line
# segments are simplified; higher thresholds result in quicker
# rendering.
#
# The following script will first display the data without any
# simplification, and then display the same data with simplification.
# Try interacting with both of them::
#
# import numpy as np
# import matplotlib.pyplot as plt
# import matplotlib as mpl
#
# # Setup, and create the data to plot
# y = np.random.rand(100000)
# y[50000:] *= 2
# y[np.logspace(1, np.log10(50000), 400).astype(int)] = -1
# mpl.rcParams['path.simplify'] = True
#
# mpl.rcParams['path.simplify_threshold'] = 0.0
# plt.plot(y)
# plt.show()
#
# mpl.rcParams['path.simplify_threshold'] = 1.0
# plt.plot(y)
# plt.show()
#
# Matplotlib currently defaults to a conservative simplification
# threshold of ``1/9``. If you want to change your default settings
# to use a different value, you can change your ``matplotlibrc``
# file. Alternatively, you could create a new style for
# interactive plotting (with maximal simplification) and another
# style for publication quality plotting (with minimal
# simplification) and activate them as necessary. See
# :doc:`/tutorials/introductory/customizing` for
# instructions on how to perform these actions.
#
# The simplification works by iteratively merging line segments
# into a single vector until the next line segment's perpendicular
# distance to the vector (measured in display-coordinate space)
# is greater than the ``path.simplify_threshold`` parameter.
#
# .. note::
# Changes related to how line segments are simplified were made
# in version 2.1. Rendering time will still be improved by these
# parameters prior to 2.1, but rendering time for some kinds of
# data will be vastly improved in versions 2.1 and greater.
#
# Marker simplification
# ---------------------
#
# Markers can also be simplified, albeit less robustly than
# line segments. Marker simplification is only available
# to :class:`~matplotlib.lines.Line2D` objects (through the
# ``markevery`` property). Wherever
# :class:`~matplotlib.lines.Line2D` construction parameter
# are passed through, such as
# :func:`matplotlib.pyplot.plot` and
# :meth:`matplotlib.axes.Axes.plot`, the ``markevery``
# parameter can be used::
#
# plt.plot(x, y, markevery=10)
#
# The markevery argument allows for naive subsampling, or an
# attempt at evenly spaced (along the *x* axis) sampling. See the
# :doc:`/gallery/lines_bars_and_markers/markevery_demo`
# for more information.
#
# Splitting lines into smaller chunks
# -----------------------------------
#
# If you are using the Agg backend (see :ref:`what-is-a-backend`),
# then you can make use of the ``agg.path.chunksize`` rc parameter.
# This allows you to specify a chunk size, and any lines with
# greater than that many vertices will be split into multiple
# lines, each of which have no more than ``agg.path.chunksize``
# many vertices. (Unless ``agg.path.chunksize`` is zero, in
# which case there is no chunking.) For some kind of data,
# chunking the line up into reasonable sizes can greatly
# decrease rendering time.
#
# The following script will first display the data without any
# chunk size restriction, and then display the same data with
# a chunk size of 10,000. The difference can best be seen when
# the figures are large, try maximizing the GUI and then
# interacting with them::
#
# import numpy as np
# import matplotlib.pyplot as plt
# import matplotlib as mpl
# mpl.rcParams['path.simplify_threshold'] = 1.0
#
# # Setup, and create the data to plot
# y = np.random.rand(100000)
# y[50000:] *= 2
# y[np.logspace(1,np.log10(50000), 400).astype(int)] = -1
# mpl.rcParams['path.simplify'] = True
#
# mpl.rcParams['agg.path.chunksize'] = 0
# plt.plot(y)
# plt.show()
#
# mpl.rcParams['agg.path.chunksize'] = 10000
# plt.plot(y)
# plt.show()
#
# Legends
# -------
#
# The default legend behavior for axes attempts to find the location
# that covers the fewest data points (`loc='best'`). This can be a
# very expensive computation if there are lots of data points. In
# this case, you may want to provide a specific location.
#
# Using the *fast* style
# ----------------------
#
# The *fast* style can be used to automatically set
# simplification and chunking parameters to reasonable
# settings to speed up plotting large amounts of data.
# It can be used simply by running::
#
# import matplotlib.style as mplstyle
# mplstyle.use('fast')
#
# It is very light weight, so it plays nicely with other
# styles, just make sure the fast style is applied last
# so that other styles do not overwrite the settings::
#
# mplstyle.use(['dark_background', 'ggplot', 'fast'])
|
ae7cb0ca0bb477ebbd3a7f0516a5cfdf4414de26be2b9795cf05794b0314e85d
|
"""
==============
Image tutorial
==============
A short tutorial on plotting images with Matplotlib.
.. _imaging_startup:
Startup commands
===================
First, let's start IPython. It is a most excellent enhancement to the
standard Python prompt, and it ties in especially well with
Matplotlib. Start IPython either at a shell, or the IPython Notebook now.
With IPython started, we now need to connect to a GUI event loop. This
tells IPython where (and how) to display plots. To connect to a GUI
loop, execute the **%matplotlib** magic at your IPython prompt. There's more
detail on exactly what this does at `IPython's documentation on GUI
event loops
<http://ipython.org/ipython-doc/2/interactive/reference.html#gui-event-loop-support>`_.
If you're using IPython Notebook, the same commands are available, but
people commonly use a specific argument to the %matplotlib magic:
.. sourcecode:: ipython
In [1]: %matplotlib inline
This turns on inline plotting, where plot graphics will appear in your
notebook. This has important implications for interactivity. For inline plotting, commands in
cells below the cell that outputs a plot will not affect the plot. For example,
changing the color map is not possible from cells below the cell that creates a plot.
However, for other backends, such as Qt5, that open a separate window,
cells below those that create the plot will change the plot - it is a
live object in memory.
This tutorial will use matplotlib's imperative-style plotting
interface, pyplot. This interface maintains global state, and is very
useful for quickly and easily experimenting with various plot
settings. The alternative is the object-oriented interface, which is also
very powerful, and generally more suitable for large application
development. If you'd like to learn about the object-oriented
interface, a great place to start is our :doc:`Usage guide
</tutorials/introductory/usage>`. For now, let's get on
with the imperative-style approach:
"""
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
###############################################################################
# .. _importing_data:
#
# Importing image data into Numpy arrays
# ===============================================
#
# Loading image data is supported by the `Pillow
# <https://pillow.readthedocs.io/en/latest/>`_ library. Natively, Matplotlib
# only supports PNG images. The commands shown below fall back on Pillow if
# the native read fails.
#
# The image used in this example is a PNG file, but keep that Pillow
# requirement in mind for your own data.
#
# Here's the image we're going to play with:
#
# .. image:: ../../_static/stinkbug.png
#
# It's a 24-bit RGB PNG image (8 bits for each of R, G, B). Depending
# on where you get your data, the other kinds of image that you'll most
# likely encounter are RGBA images, which allow for transparency, or
# single-channel grayscale (luminosity) images. You can right click on
# it and choose "Save image as" to download it to your computer for the
# rest of this tutorial.
#
# And here we go...
img = mpimg.imread('../../doc/_static/stinkbug.png')
print(img)
###############################################################################
# Note the dtype there - float32. Matplotlib has rescaled the 8 bit
# data from each channel to floating point data between 0.0 and 1.0. As
# a side note, the only datatype that Pillow can work with is uint8.
# Matplotlib plotting can handle float32 and uint8, but image
# reading/writing for any format other than PNG is limited to uint8
# data. Why 8 bits? Most displays can only render 8 bits per channel
# worth of color gradation. Why can they only render 8 bits/channel?
# Because that's about all the human eye can see. More here (from a
# photography standpoint): `Luminous Landscape bit depth tutorial
# <https://luminous-landscape.com/bit-depth/>`_.
#
# Each inner list represents a pixel. Here, with an RGB image, there
# are 3 values. Since it's a black and white image, R, G, and B are all
# similar. An RGBA (where A is alpha, or transparency), has 4 values
# per inner list, and a simple luminance image just has one value (and
# is thus only a 2-D array, not a 3-D array). For RGB and RGBA images,
# matplotlib supports float32 and uint8 data types. For grayscale,
# matplotlib supports only float32. If your array data does not meet
# one of these descriptions, you need to rescale it.
#
# .. _plotting_data:
#
# Plotting numpy arrays as images
# ===================================
#
# So, you have your data in a numpy array (either by importing it, or by
# generating it). Let's render it. In Matplotlib, this is performed
# using the :func:`~matplotlib.pyplot.imshow` function. Here we'll grab
# the plot object. This object gives you an easy way to manipulate the
# plot from the prompt.
imgplot = plt.imshow(img)
###############################################################################
# You can also plot any numpy array.
#
# .. _Pseudocolor:
#
# Applying pseudocolor schemes to image plots
# -------------------------------------------------
#
# Pseudocolor can be a useful tool for enhancing contrast and
# visualizing your data more easily. This is especially useful when
# making presentations of your data using projectors - their contrast is
# typically quite poor.
#
# Pseudocolor is only relevant to single-channel, grayscale, luminosity
# images. We currently have an RGB image. Since R, G, and B are all
# similar (see for yourself above or in your data), we can just pick one
# channel of our data:
lum_img = img[:, :, 0]
# This is array slicing. You can read more in the `Numpy tutorial
# <https://docs.scipy.org/doc/numpy/user/quickstart.html>`_.
plt.imshow(lum_img)
###############################################################################
# Now, with a luminosity (2D, no color) image, the default colormap (aka lookup table,
# LUT), is applied. The default is called viridis. There are plenty of
# others to choose from.
plt.imshow(lum_img, cmap="hot")
###############################################################################
# Note that you can also change colormaps on existing plot objects using the
# :meth:`~matplotlib.image.Image.set_cmap` method:
imgplot = plt.imshow(lum_img)
imgplot.set_cmap('nipy_spectral')
###############################################################################
#
# .. note::
#
# However, remember that in the IPython notebook with the inline backend,
# you can't make changes to plots that have already been rendered. If you
# create imgplot here in one cell, you cannot call set_cmap() on it in a later
# cell and expect the earlier plot to change. Make sure that you enter these
# commands together in one cell. plt commands will not change plots from earlier
# cells.
#
# There are many other colormap schemes available. See the `list and
# images of the colormaps
# <../colors/colormaps.html>`_.
#
# .. _`Color Bars`:
#
# Color scale reference
# ------------------------
#
# It's helpful to have an idea of what value a color represents. We can
# do that by adding color bars.
imgplot = plt.imshow(lum_img)
plt.colorbar()
###############################################################################
# This adds a colorbar to your existing figure. This won't
# automatically change if you change you switch to a different
# colormap - you have to re-create your plot, and add in the colorbar
# again.
#
# .. _`Data ranges`:
#
# Examining a specific data range
# ---------------------------------
#
# Sometimes you want to enhance the contrast in your image, or expand
# the contrast in a particular region while sacrificing the detail in
# colors that don't vary much, or don't matter. A good tool to find
# interesting regions is the histogram. To create a histogram of our
# image data, we use the :func:`~matplotlib.pyplot.hist` function.
plt.hist(lum_img.ravel(), bins=256, range=(0.0, 1.0), fc='k', ec='k')
###############################################################################
# Most often, the "interesting" part of the image is around the peak,
# and you can get extra contrast by clipping the regions above and/or
# below the peak. In our histogram, it looks like there's not much
# useful information in the high end (not many white things in the
# image). Let's adjust the upper limit, so that we effectively "zoom in
# on" part of the histogram. We do this by passing the clim argument to
# imshow. You could also do this by calling the
# :meth:`~matplotlib.image.Image.set_clim` method of the image plot
# object, but make sure that you do so in the same cell as your plot
# command when working with the IPython Notebook - it will not change
# plots from earlier cells.
#
# You can specify the clim in the call to ``plot``.
imgplot = plt.imshow(lum_img, clim=(0.0, 0.7))
###############################################################################
# You can also specify the clim using the returned object
fig = plt.figure()
a = fig.add_subplot(1, 2, 1)
imgplot = plt.imshow(lum_img)
a.set_title('Before')
plt.colorbar(ticks=[0.1, 0.3, 0.5, 0.7], orientation='horizontal')
a = fig.add_subplot(1, 2, 2)
imgplot = plt.imshow(lum_img)
imgplot.set_clim(0.0, 0.7)
a.set_title('After')
plt.colorbar(ticks=[0.1, 0.3, 0.5, 0.7], orientation='horizontal')
###############################################################################
# .. _Interpolation:
#
# Array Interpolation schemes
# ---------------------------
#
# Interpolation calculates what the color or value of a pixel "should"
# be, according to different mathematical schemes. One common place
# that this happens is when you resize an image. The number of pixels
# change, but you want the same information. Since pixels are discrete,
# there's missing space. Interpolation is how you fill that space.
# This is why your images sometimes come out looking pixelated when you
# blow them up. The effect is more pronounced when the difference
# between the original image and the expanded image is greater. Let's
# take our image and shrink it. We're effectively discarding pixels,
# only keeping a select few. Now when we plot it, that data gets blown
# up to the size on your screen. The old pixels aren't there anymore,
# and the computer has to draw in pixels to fill that space.
#
# We'll use the Pillow library that we used to load the image also to resize
# the image.
from PIL import Image
img = Image.open('../../doc/_static/stinkbug.png')
img.thumbnail((64, 64), Image.ANTIALIAS) # resizes image in-place
imgplot = plt.imshow(img)
###############################################################################
# Here we have the default interpolation, bilinear, since we did not
# give :func:`~matplotlib.pyplot.imshow` any interpolation argument.
#
# Let's try some others. Here's "nearest", which does no interpolation.
imgplot = plt.imshow(img, interpolation="nearest")
###############################################################################
# and bicubic:
imgplot = plt.imshow(img, interpolation="bicubic")
###############################################################################
# Bicubic interpolation is often used when blowing up photos - people
# tend to prefer blurry over pixelated.
|
5b870c2748613e67321d086ce525677cdcd5ea82210d18b7ccb8cbd4e4634204
|
"""
==========================
Sample plots in Matplotlib
==========================
Here you'll find a host of example plots with the code that
generated them.
.. _matplotlibscreenshots:
Line Plot
=========
Here's how to create a line plot with text labels using
:func:`~matplotlib.pyplot.plot`.
.. figure:: ../../gallery/lines_bars_and_markers/images/sphx_glr_simple_plot_001.png
:target: ../../gallery/lines_bars_and_markers/simple_plot.html
:align: center
:scale: 50
Simple Plot
.. _screenshots_subplot_demo:
Multiple subplots in one figure
===============================
Multiple axes (i.e. subplots) are created with the
:func:`~matplotlib.pyplot.subplot` function:
.. figure:: ../../gallery/subplots_axes_and_figures/images/sphx_glr_subplot_001.png
:target: ../../gallery/subplots_axes_and_figures/subplot.html
:align: center
:scale: 50
Subplot
.. _screenshots_images_demo:
Images
======
Matplotlib can display images (assuming equally spaced
horizontal dimensions) using the :func:`~matplotlib.pyplot.imshow` function.
.. figure:: ../../gallery/images_contours_and_fields/images/sphx_glr_image_demo_003.png
:target: ../../gallery/images_contours_and_fields/image_demo.html
:align: center
:scale: 50
Example of using :func:`~matplotlib.pyplot.imshow` to display a CT scan
.. _screenshots_pcolormesh_demo:
Contouring and pseudocolor
==========================
The :func:`~matplotlib.pyplot.pcolormesh` function can make a colored
representation of a two-dimensional array, even if the horizontal dimensions
are unevenly spaced. The
:func:`~matplotlib.pyplot.contour` function is another way to represent
the same data:
.. figure:: ../../gallery/images_contours_and_fields/images/sphx_glr_pcolormesh_levels_001.png
:target: ../../gallery/images_contours_and_fields/pcolormesh_levels.html
:align: center
:scale: 50
Example comparing :func:`~matplotlib.pyplot.pcolormesh` and :func:`~matplotlib.pyplot.contour` for plotting two-dimensional data
.. _screenshots_histogram_demo:
Histograms
==========
The :func:`~matplotlib.pyplot.hist` function automatically generates
histograms and returns the bin counts or probabilities:
.. figure:: ../../gallery/statistics/images/sphx_glr_histogram_features_001.png
:target: ../../gallery/statistics/histogram_features.html
:align: center
:scale: 50
Histogram Features
.. _screenshots_path_demo:
Paths
=====
You can add arbitrary paths in Matplotlib using the
:mod:`matplotlib.path` module:
.. figure:: ../../gallery/shapes_and_collections/images/sphx_glr_path_patch_001.png
:target: ../../gallery/shapes_and_collections/path_patch.html
:align: center
:scale: 50
Path Patch
.. _screenshots_mplot3d_surface:
Three-dimensional plotting
==========================
The mplot3d toolkit (see :ref:`toolkit_mplot3d-tutorial` and
:ref:`mplot3d-examples-index`) has support for simple 3d graphs
including surface, wireframe, scatter, and bar charts.
.. figure:: ../../gallery/mplot3d/images/sphx_glr_surface3d_001.png
:target: ../../gallery/mplot3d/surface3d.html
:align: center
:scale: 50
Surface3d
Thanks to John Porter, Jonathon Taylor, Reinier Heeres, and Ben Root for
the `mplot3d` toolkit. This toolkit is included with all standard Matplotlib
installs.
.. _screenshots_ellipse_demo:
Streamplot
==========
The :meth:`~matplotlib.pyplot.streamplot` function plots the streamlines of
a vector field. In addition to simply plotting the streamlines, it allows you
to map the colors and/or line widths of streamlines to a separate parameter,
such as the speed or local intensity of the vector field.
.. figure:: ../../gallery/images_contours_and_fields/images/sphx_glr_plot_streamplot_001.png
:target: ../../gallery/images_contours_and_fields/plot_streamplot.html
:align: center
:scale: 50
Streamplot with various plotting options.
This feature complements the :meth:`~matplotlib.pyplot.quiver` function for
plotting vector fields. Thanks to Tom Flannaghan and Tony Yu for adding the
streamplot function.
Ellipses
========
In support of the `Phoenix <http://www.jpl.nasa.gov/news/phoenix/main.php>`_
mission to Mars (which used Matplotlib to display ground tracking of
spacecraft), Michael Droettboom built on work by Charlie Moad to provide
an extremely accurate 8-spline approximation to elliptical arcs (see
:class:`~matplotlib.patches.Arc`), which are insensitive to zoom level.
.. figure:: ../../gallery/shapes_and_collections/images/sphx_glr_ellipse_demo_001.png
:target: ../../gallery/shapes_and_collections/ellipse_demo.html
:align: center
:scale: 50
Ellipse Demo
.. _screenshots_barchart_demo:
Bar charts
==========
Use the :func:`~matplotlib.pyplot.bar` function to make bar charts, which
includes customizations such as error bars:
.. figure:: ../../gallery/statistics/images/sphx_glr_barchart_demo_001.png
:target: ../../gallery/statistics/barchart_demo.html
:align: center
:scale: 50
Barchart Demo
You can also create stacked bars
(`bar_stacked.py <../../gallery/lines_bars_and_markers/bar_stacked.html>`_),
or horizontal bar charts
(`barh.py <../../gallery/lines_bars_and_markers/barh.html>`_).
.. _screenshots_pie_demo:
Pie charts
==========
The :func:`~matplotlib.pyplot.pie` function allows you to create pie
charts. Optional features include auto-labeling the percentage of area,
exploding one or more wedges from the center of the pie, and a shadow effect.
Take a close look at the attached code, which generates this figure in just
a few lines of code.
.. figure:: ../../gallery/pie_and_polar_charts/images/sphx_glr_pie_features_001.png
:target: ../../gallery/pie_and_polar_charts/pie_features.html
:align: center
:scale: 50
Pie Features
.. _screenshots_table_demo:
Tables
======
The :func:`~matplotlib.pyplot.table` function adds a text table
to an axes.
.. figure:: ../../gallery/misc/images/sphx_glr_table_demo_001.png
:target: ../../gallery/misc/table_demo.html
:align: center
:scale: 50
Table Demo
.. _screenshots_scatter_demo:
Scatter plots
=============
The :func:`~matplotlib.pyplot.scatter` function makes a scatter plot
with (optional) size and color arguments. This example plots changes
in Google's stock price, with marker sizes reflecting the
trading volume and colors varying with time. Here, the
alpha attribute is used to make semitransparent circle markers.
.. figure:: ../../gallery/lines_bars_and_markers/images/sphx_glr_scatter_demo2_001.png
:target: ../../gallery/lines_bars_and_markers/scatter_demo2.html
:align: center
:scale: 50
Scatter Demo2
.. _screenshots_slider_demo:
GUI widgets
===========
Matplotlib has basic GUI widgets that are independent of the graphical
user interface you are using, allowing you to write cross GUI figures
and widgets. See :mod:`matplotlib.widgets` and the
`widget examples <../../gallery/index.html>`_.
.. figure:: ../../gallery/widgets/images/sphx_glr_slider_demo_001.png
:target: ../../gallery/widgets/slider_demo.html
:align: center
:scale: 50
Slider and radio-button GUI.
.. _screenshots_fill_demo:
Filled curves
=============
The :func:`~matplotlib.pyplot.fill` function lets you
plot filled curves and polygons:
.. figure:: ../../gallery/lines_bars_and_markers/images/sphx_glr_fill_001.png
:target: ../../gallery/lines_bars_and_markers/fill.html
:align: center
:scale: 50
Fill
Thanks to Andrew Straw for adding this function.
.. _screenshots_date_demo:
Date handling
=============
You can plot timeseries data with major and minor ticks and custom
tick formatters for both.
.. figure:: ../../gallery/text_labels_and_annotations/images/sphx_glr_date_001.png
:target: ../../gallery/text_labels_and_annotations/date.html
:align: center
:scale: 50
Date
See :mod:`matplotlib.ticker` and :mod:`matplotlib.dates` for details and usage.
.. _screenshots_log_demo:
Log plots
=========
The :func:`~matplotlib.pyplot.semilogx`,
:func:`~matplotlib.pyplot.semilogy` and
:func:`~matplotlib.pyplot.loglog` functions simplify the creation of
logarithmic plots.
.. figure:: ../../gallery/scales/images/sphx_glr_log_demo_001.png
:target: ../../gallery/scales/log_demo.html
:align: center
:scale: 50
Log Demo
Thanks to Andrew Straw, Darren Dale and Gregory Lielens for contributions
log-scaling infrastructure.
.. _screenshots_polar_demo:
Polar plots
===========
The :func:`~matplotlib.pyplot.polar` function generates polar plots.
.. figure:: ../../gallery/pie_and_polar_charts/images/sphx_glr_polar_demo_001.png
:target: ../../gallery/pie_and_polar_charts/polar_demo.html
:align: center
:scale: 50
Polar Demo
.. _screenshots_legend_demo:
Legends
=======
The :func:`~matplotlib.pyplot.legend` function automatically
generates figure legends, with MATLAB-compatible legend-placement
functions.
.. figure:: ../../gallery/text_labels_and_annotations/images/sphx_glr_legend_001.png
:target: ../../gallery/text_labels_and_annotations/legend.html
:align: center
:scale: 50
Legend
Thanks to Charles Twardy for input on the legend function.
.. _screenshots_mathtext_examples_demo:
TeX-notation for text objects
=============================
Below is a sampling of the many TeX expressions now supported by Matplotlib's
internal mathtext engine. The mathtext module provides TeX style mathematical
expressions using `FreeType <https://www.freetype.org/>`_
and the DejaVu, BaKoMa computer modern, or `STIX <http://www.stixfonts.org>`_
fonts. See the :mod:`matplotlib.mathtext` module for additional details.
.. figure:: ../../gallery/text_labels_and_annotations/images/sphx_glr_mathtext_examples_001.png
:target: ../../gallery/text_labels_and_annotations/mathtext_examples.html
:align: center
:scale: 50
Mathtext Examples
Matplotlib's mathtext infrastructure is an independent implementation and
does not require TeX or any external packages installed on your computer. See
the tutorial at :doc:`/tutorials/text/mathtext`.
.. _screenshots_tex_demo:
Native TeX rendering
====================
Although Matplotlib's internal math rendering engine is quite
powerful, sometimes you need TeX. Matplotlib supports external TeX
rendering of strings with the *usetex* option.
.. figure:: ../../gallery/text_labels_and_annotations/images/sphx_glr_tex_demo_001.png
:target: ../../gallery/text_labels_and_annotations/tex_demo.html
:align: center
:scale: 50
Tex Demo
.. _screenshots_eeg_demo:
EEG GUI
=======
You can embed Matplotlib into pygtk, wx, Tk, or Qt applications.
Here is a screenshot of an EEG viewer called `pbrain
<https://github.com/nipy/pbrain>`__.
.. image:: ../../_static/eeg_small.png
The lower axes uses :func:`~matplotlib.pyplot.specgram`
to plot the spectrogram of one of the EEG channels.
For examples of how to embed Matplotlib in different toolkits, see:
* :doc:`/gallery/user_interfaces/embedding_in_gtk3_sgskip`
* :doc:`/gallery/user_interfaces/embedding_in_wx2_sgskip`
* :doc:`/gallery/user_interfaces/mpl_with_glade3_sgskip`
* :doc:`/gallery/user_interfaces/embedding_in_qt_sgskip`
* :doc:`/gallery/user_interfaces/embedding_in_tk_sgskip`
XKCD-style sketch plots
=======================
Just for fun, Matplotlib supports plotting in the style of `xkcd
<http://www.xkcd.com/>`.
.. figure:: ../../gallery/showcase/images/sphx_glr_xkcd_001.png
:target: ../../gallery/showcase/xkcd.html
:align: center
:scale: 50
xkcd
Subplot example
===============
Many plot types can be combined in one figure to create
powerful and flexible representations of data.
"""
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(19680801)
data = np.random.randn(2, 100)
fig, axs = plt.subplots(2, 2, figsize=(5, 5))
axs[0, 0].hist(data[0])
axs[1, 0].scatter(data[0], data[1])
axs[0, 1].plot(data[0], data[1])
axs[1, 1].hist2d(data[0], data[1])
plt.show()
|
838e6043323bbf17215f2a82cbbb5a8cdd7a5950b38e48fc834114b691ae54ef
|
"""
=======================
The Lifecycle of a Plot
=======================
This tutorial aims to show the beginning, middle, and end of a single
visualization using Matplotlib. We'll begin with some raw data and
end by saving a figure of a customized visualization. Along the way we'll try
to highlight some neat features and best-practices using Matplotlib.
.. currentmodule:: matplotlib
.. note::
This tutorial is based off of
`this excellent blog post <http://pbpython.com/effective-matplotlib.html>`_
by Chris Moffitt. It was transformed into this tutorial by Chris Holdgraf.
A note on the Object-Oriented API vs Pyplot
===========================================
Matplotlib has two interfaces. The first is an object-oriented (OO)
interface. In this case, we utilize an instance of :class:`axes.Axes`
in order to render visualizations on an instance of :class:`figure.Figure`.
The second is based on MATLAB and uses a state-based interface. This is
encapsulated in the :mod:`pyplot` module. See the :doc:`pyplot tutorials
</tutorials/introductory/pyplot>` for a more in-depth look at the pyplot
interface.
Most of the terms are straightforward but the main thing to remember
is that:
* The Figure is the final image that may contain 1 or more Axes.
* The Axes represent an individual plot (don't confuse this with the word
"axis", which refers to the x/y axis of a plot).
We call methods that do the plotting directly from the Axes, which gives
us much more flexibility and power in customizing our plot.
.. note::
In general, try to use the object-oriented interface over the pyplot
interface.
Our data
========
We'll use the data from the post from which this tutorial was derived.
It contains sales information for a number of companies.
"""
# sphinx_gallery_thumbnail_number = 10
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
data = {'Barton LLC': 109438.50,
'Frami, Hills and Schmidt': 103569.59,
'Fritsch, Russel and Anderson': 112214.71,
'Jerde-Hilpert': 112591.43,
'Keeling LLC': 100934.30,
'Koepp Ltd': 103660.54,
'Kulas Inc': 137351.96,
'Trantow-Barrows': 123381.38,
'White-Trantow': 135841.99,
'Will LLC': 104437.60}
group_data = list(data.values())
group_names = list(data.keys())
group_mean = np.mean(group_data)
###############################################################################
# Getting started
# ===============
#
# This data is naturally visualized as a barplot, with one bar per
# group. To do this with the object-oriented approach, we'll first generate
# an instance of :class:`figure.Figure` and
# :class:`axes.Axes`. The Figure is like a canvas, and the Axes
# is a part of that canvas on which we will make a particular visualization.
#
# .. note::
#
# Figures can have multiple axes on them. For information on how to do this,
# see the :doc:`Tight Layout tutorial
# </tutorials/intermediate/tight_layout_guide>`.
fig, ax = plt.subplots()
###############################################################################
# Now that we have an Axes instance, we can plot on top of it.
fig, ax = plt.subplots()
ax.barh(group_names, group_data)
###############################################################################
# Controlling the style
# =====================
#
# There are many styles available in Matplotlib in order to let you tailor
# your visualization to your needs. To see a list of styles, we can use
# :mod:`pyplot.style`.
print(plt.style.available)
###############################################################################
# You can activate a style with the following:
plt.style.use('fivethirtyeight')
###############################################################################
# Now let's remake the above plot to see how it looks:
fig, ax = plt.subplots()
ax.barh(group_names, group_data)
###############################################################################
# The style controls many things, such as color, linewidths, backgrounds,
# etc.
#
# Customizing the plot
# ====================
#
# Now we've got a plot with the general look that we want, so let's fine-tune
# it so that it's ready for print. First let's rotate the labels on the x-axis
# so that they show up more clearly. We can gain access to these labels
# with the :meth:`axes.Axes.get_xticklabels` method:
fig, ax = plt.subplots()
ax.barh(group_names, group_data)
labels = ax.get_xticklabels()
###############################################################################
# If we'd like to set the property of many items at once, it's useful to use
# the :func:`pyplot.setp` function. This will take a list (or many lists) of
# Matplotlib objects, and attempt to set some style element of each one.
fig, ax = plt.subplots()
ax.barh(group_names, group_data)
labels = ax.get_xticklabels()
plt.setp(labels, rotation=45, horizontalalignment='right')
###############################################################################
# It looks like this cut off some of the labels on the bottom. We can
# tell Matplotlib to automatically make room for elements in the figures
# that we create. To do this we'll set the ``autolayout`` value of our
# rcParams. For more information on controlling the style, layout, and
# other features of plots with rcParams, see
# :doc:`/tutorials/introductory/customizing`.
plt.rcParams.update({'figure.autolayout': True})
fig, ax = plt.subplots()
ax.barh(group_names, group_data)
labels = ax.get_xticklabels()
plt.setp(labels, rotation=45, horizontalalignment='right')
###############################################################################
# Next, we'll add labels to the plot. To do this with the OO interface,
# we can use the :meth:`axes.Axes.set` method to set properties of this
# Axes object.
fig, ax = plt.subplots()
ax.barh(group_names, group_data)
labels = ax.get_xticklabels()
plt.setp(labels, rotation=45, horizontalalignment='right')
ax.set(xlim=[-10000, 140000], xlabel='Total Revenue', ylabel='Company',
title='Company Revenue')
###############################################################################
# We can also adjust the size of this plot using the :func:`pyplot.subplots`
# function. We can do this with the ``figsize`` kwarg.
#
# .. note::
#
# While indexing in NumPy follows the form (row, column), the figsize
# kwarg follows the form (width, height). This follows conventions in
# visualization, which unfortunately are different from those of linear
# algebra.
fig, ax = plt.subplots(figsize=(8, 4))
ax.barh(group_names, group_data)
labels = ax.get_xticklabels()
plt.setp(labels, rotation=45, horizontalalignment='right')
ax.set(xlim=[-10000, 140000], xlabel='Total Revenue', ylabel='Company',
title='Company Revenue')
###############################################################################
# For labels, we can specify custom formatting guidelines in the form of
# functions by using the :class:`ticker.FuncFormatter` class. Below we'll
# define a function that takes an integer as input, and returns a string
# as an output.
def currency(x, pos):
"""The two args are the value and tick position"""
if x >= 1e6:
s = '${:1.1f}M'.format(x*1e-6)
else:
s = '${:1.0f}K'.format(x*1e-3)
return s
formatter = FuncFormatter(currency)
###############################################################################
# We can then apply this formatter to the labels on our plot. To do this,
# we'll use the ``xaxis`` attribute of our axis. This lets you perform
# actions on a specific axis on our plot.
fig, ax = plt.subplots(figsize=(6, 8))
ax.barh(group_names, group_data)
labels = ax.get_xticklabels()
plt.setp(labels, rotation=45, horizontalalignment='right')
ax.set(xlim=[-10000, 140000], xlabel='Total Revenue', ylabel='Company',
title='Company Revenue')
ax.xaxis.set_major_formatter(formatter)
###############################################################################
# Combining multiple visualizations
# =================================
#
# It is possible to draw multiple plot elements on the same instance of
# :class:`axes.Axes`. To do this we simply need to call another one of
# the plot methods on that axes object.
fig, ax = plt.subplots(figsize=(8, 8))
ax.barh(group_names, group_data)
labels = ax.get_xticklabels()
plt.setp(labels, rotation=45, horizontalalignment='right')
# Add a vertical line, here we set the style in the function call
ax.axvline(group_mean, ls='--', color='r')
# Annotate new companies
for group in [3, 5, 8]:
ax.text(145000, group, "New Company", fontsize=10,
verticalalignment="center")
# Now we'll move our title up since it's getting a little cramped
ax.title.set(y=1.05)
ax.set(xlim=[-10000, 140000], xlabel='Total Revenue', ylabel='Company',
title='Company Revenue')
ax.xaxis.set_major_formatter(formatter)
ax.set_xticks([0, 25e3, 50e3, 75e3, 100e3, 125e3])
fig.subplots_adjust(right=.1)
plt.show()
###############################################################################
# Saving our plot
# ===============
#
# Now that we're happy with the outcome of our plot, we want to save it to
# disk. There are many file formats we can save to in Matplotlib. To see
# a list of available options, use:
print(fig.canvas.get_supported_filetypes())
###############################################################################
# We can then use the :meth:`figure.Figure.savefig` in order to save the figure
# to disk. Note that there are several useful flags we'll show below:
#
# * ``transparent=True`` makes the background of the saved figure transparent
# if the format supports it.
# * ``dpi=80`` controls the resolution (dots per square inch) of the output.
# * ``bbox_inches="tight"`` fits the bounds of the figure to our plot.
# Uncomment this line to save the figure.
# fig.savefig('sales.png', transparent=False, dpi=80, bbox_inches="tight")
|
bc64ab6e945b3eed0293bb1cef525fe3f44c857203cef0d21e60f61bdfeebcf2
|
"""
===============
Pyplot tutorial
===============
An introduction to the pyplot interface.
"""
###############################################################################
# Intro to pyplot
# ===============
#
# :mod:`matplotlib.pyplot` is a collection of command style functions
# that make matplotlib work like MATLAB.
# Each ``pyplot`` function makes
# some change to a figure: e.g., creates a figure, creates a plotting area
# in a figure, plots some lines in a plotting area, decorates the plot
# with labels, etc.
#
# In :mod:`matplotlib.pyplot` various states are preserved
# across function calls, so that it keeps track of things like
# the current figure and plotting area, and the plotting
# functions are directed to the current axes (please note that "axes" here
# and in most places in the documentation refers to the *axes*
# :ref:`part of a figure <figure_parts>`
# and not the strict mathematical term for more than one axis).
#
# .. note::
#
# the pyplot API is generally less-flexible than the object-oriented API.
# Most of the function calls you see here can also be called as methods
# from an ``Axes`` object. We recommend browsing the tutorials and
# examples to see how this works.
#
# Generating visualizations with pyplot is very quick:
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4])
plt.ylabel('some numbers')
plt.show()
###############################################################################
# You may be wondering why the x-axis ranges from 0-3 and the y-axis
# from 1-4. If you provide a single list or array to the
# :func:`~matplotlib.pyplot.plot` command, matplotlib assumes it is a
# sequence of y values, and automatically generates the x values for
# you. Since python ranges start with 0, the default x vector has the
# same length as y but starts with 0. Hence the x data are
# ``[0,1,2,3]``.
#
# :func:`~matplotlib.pyplot.plot` is a versatile command, and will take
# an arbitrary number of arguments. For example, to plot x versus y,
# you can issue the command:
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
###############################################################################
# Formatting the style of your plot
# ---------------------------------
#
# For every x, y pair of arguments, there is an optional third argument
# which is the format string that indicates the color and line type of
# the plot. The letters and symbols of the format string are from
# MATLAB, and you concatenate a color string with a line style string.
# The default format string is 'b-', which is a solid blue line. For
# example, to plot the above with red circles, you would issue
plt.plot([1, 2, 3, 4], [1, 4, 9, 16], 'ro')
plt.axis([0, 6, 0, 20])
plt.show()
###############################################################################
# See the :func:`~matplotlib.pyplot.plot` documentation for a complete
# list of line styles and format strings. The
# :func:`~matplotlib.pyplot.axis` command in the example above takes a
# list of ``[xmin, xmax, ymin, ymax]`` and specifies the viewport of the
# axes.
#
# If matplotlib were limited to working with lists, it would be fairly
# useless for numeric processing. Generally, you will use `numpy
# <http://www.numpy.org>`_ arrays. In fact, all sequences are
# converted to numpy arrays internally. The example below illustrates a
# plotting several lines with different format styles in one command
# using arrays.
import numpy as np
# evenly sampled time at 200ms intervals
t = np.arange(0., 5., 0.2)
# red dashes, blue squares and green triangles
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
plt.show()
###############################################################################
# .. _plotting-with-keywords:
#
# Plotting with keyword strings
# =============================
#
# There are some instances where you have data in a format that lets you
# access particular variables with strings. For example, with
# :class:`numpy.recarray` or :class:`pandas.DataFrame`.
#
# Matplotlib allows you provide such an object with
# the ``data`` keyword argument. If provided, then you may generate plots with
# the strings corresponding to these variables.
data = {'a': np.arange(50),
'c': np.random.randint(0, 50, 50),
'd': np.random.randn(50)}
data['b'] = data['a'] + 10 * np.random.randn(50)
data['d'] = np.abs(data['d']) * 100
plt.scatter('a', 'b', c='c', s='d', data=data)
plt.xlabel('entry a')
plt.ylabel('entry b')
plt.show()
###############################################################################
# .. _plotting-with-categorical-vars:
#
# Plotting with categorical variables
# ===================================
#
# It is also possible to create a plot using categorical variables.
# Matplotlib allows you to pass categorical variables directly to
# many plotting functions. For example:
names = ['group_a', 'group_b', 'group_c']
values = [1, 10, 100]
plt.figure(figsize=(9, 3))
plt.subplot(131)
plt.bar(names, values)
plt.subplot(132)
plt.scatter(names, values)
plt.subplot(133)
plt.plot(names, values)
plt.suptitle('Categorical Plotting')
plt.show()
###############################################################################
# .. _controlling-line-properties:
#
# Controlling line properties
# ===========================
#
# Lines have many attributes that you can set: linewidth, dash style,
# antialiased, etc; see :class:`matplotlib.lines.Line2D`. There are
# several ways to set line properties
#
# * Use keyword args::
#
# plt.plot(x, y, linewidth=2.0)
#
#
# * Use the setter methods of a ``Line2D`` instance. ``plot`` returns a list
# of ``Line2D`` objects; e.g., ``line1, line2 = plot(x1, y1, x2, y2)``. In the code
# below we will suppose that we have only
# one line so that the list returned is of length 1. We use tuple unpacking with
# ``line,`` to get the first element of that list::
#
# line, = plt.plot(x, y, '-')
# line.set_antialiased(False) # turn off antialiasing
#
# * Use the :func:`~matplotlib.pyplot.setp` command. The example below
# uses a MATLAB-style command to set multiple properties
# on a list of lines. ``setp`` works transparently with a list of objects
# or a single object. You can either use python keyword arguments or
# MATLAB-style string/value pairs::
#
# lines = plt.plot(x1, y1, x2, y2)
# # use keyword args
# plt.setp(lines, color='r', linewidth=2.0)
# # or MATLAB style string value pairs
# plt.setp(lines, 'color', 'r', 'linewidth', 2.0)
#
#
# Here are the available :class:`~matplotlib.lines.Line2D` properties.
#
# ====================== ==================================================
# Property Value Type
# ====================== ==================================================
# alpha float
# animated [True | False]
# antialiased or aa [True | False]
# clip_box a matplotlib.transform.Bbox instance
# clip_on [True | False]
# clip_path a Path instance and a Transform instance, a Patch
# color or c any matplotlib color
# contains the hit testing function
# dash_capstyle [``'butt'`` | ``'round'`` | ``'projecting'``]
# dash_joinstyle [``'miter'`` | ``'round'`` | ``'bevel'``]
# dashes sequence of on/off ink in points
# data (np.array xdata, np.array ydata)
# figure a matplotlib.figure.Figure instance
# label any string
# linestyle or ls [ ``'-'`` | ``'--'`` | ``'-.'`` | ``':'`` | ``'steps'`` | ...]
# linewidth or lw float value in points
# marker [ ``'+'`` | ``','`` | ``'.'`` | ``'1'`` | ``'2'`` | ``'3'`` | ``'4'`` ]
# markeredgecolor or mec any matplotlib color
# markeredgewidth or mew float value in points
# markerfacecolor or mfc any matplotlib color
# markersize or ms float
# markevery [ None | integer | (startind, stride) ]
# picker used in interactive line selection
# pickradius the line pick selection radius
# solid_capstyle [``'butt'`` | ``'round'`` | ``'projecting'``]
# solid_joinstyle [``'miter'`` | ``'round'`` | ``'bevel'``]
# transform a matplotlib.transforms.Transform instance
# visible [True | False]
# xdata np.array
# ydata np.array
# zorder any number
# ====================== ==================================================
#
# To get a list of settable line properties, call the
# :func:`~matplotlib.pyplot.setp` function with a line or lines
# as argument
#
# .. sourcecode:: ipython
#
# In [69]: lines = plt.plot([1, 2, 3])
#
# In [70]: plt.setp(lines)
# alpha: float
# animated: [True | False]
# antialiased or aa: [True | False]
# ...snip
#
# .. _multiple-figs-axes:
#
#
# Working with multiple figures and axes
# ======================================
#
# MATLAB, and :mod:`~matplotlib.pyplot`, have the concept of the current
# figure and the current axes. All plotting commands apply to the
# current axes. The function :func:`~matplotlib.pyplot.gca` returns the
# current axes (a :class:`matplotlib.axes.Axes` instance), and
# :func:`~matplotlib.pyplot.gcf` returns the current figure
# (:class:`matplotlib.figure.Figure` instance). Normally, you don't have
# to worry about this, because it is all taken care of behind the
# scenes. Below is a script to create two subplots.
def f(t):
return np.exp(-t) * np.cos(2*np.pi*t)
t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)
plt.figure()
plt.subplot(211)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')
plt.subplot(212)
plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
plt.show()
###############################################################################
# The :func:`~matplotlib.pyplot.figure` command here is optional because
# ``figure(1)`` will be created by default, just as a ``subplot(111)``
# will be created by default if you don't manually specify any axes. The
# :func:`~matplotlib.pyplot.subplot` command specifies ``numrows,
# numcols, plot_number`` where ``plot_number`` ranges from 1 to
# ``numrows*numcols``. The commas in the ``subplot`` command are
# optional if ``numrows*numcols<10``. So ``subplot(211)`` is identical
# to ``subplot(2, 1, 1)``.
#
# You can create an arbitrary number of subplots
# and axes. If you want to place an axes manually, i.e., not on a
# rectangular grid, use the :func:`~matplotlib.pyplot.axes` command,
# which allows you to specify the location as ``axes([left, bottom,
# width, height])`` where all values are in fractional (0 to 1)
# coordinates. See :doc:`/gallery/subplots_axes_and_figures/axes_demo` for an example of
# placing axes manually and :doc:`/gallery/subplots_axes_and_figures/subplot_demo` for an
# example with lots of subplots.
#
#
# You can create multiple figures by using multiple
# :func:`~matplotlib.pyplot.figure` calls with an increasing figure
# number. Of course, each figure can contain as many axes and subplots
# as your heart desires::
#
# import matplotlib.pyplot as plt
# plt.figure(1) # the first figure
# plt.subplot(211) # the first subplot in the first figure
# plt.plot([1, 2, 3])
# plt.subplot(212) # the second subplot in the first figure
# plt.plot([4, 5, 6])
#
#
# plt.figure(2) # a second figure
# plt.plot([4, 5, 6]) # creates a subplot(111) by default
#
# plt.figure(1) # figure 1 current; subplot(212) still current
# plt.subplot(211) # make subplot(211) in figure1 current
# plt.title('Easy as 1, 2, 3') # subplot 211 title
#
# You can clear the current figure with :func:`~matplotlib.pyplot.clf`
# and the current axes with :func:`~matplotlib.pyplot.cla`. If you find
# it annoying that states (specifically the current image, figure and axes)
# are being maintained for you behind the scenes, don't despair: this is just a thin
# stateful wrapper around an object oriented API, which you can use
# instead (see :doc:`/tutorials/intermediate/artists`)
#
# If you are making lots of figures, you need to be aware of one
# more thing: the memory required for a figure is not completely
# released until the figure is explicitly closed with
# :func:`~matplotlib.pyplot.close`. Deleting all references to the
# figure, and/or using the window manager to kill the window in which
# the figure appears on the screen, is not enough, because pyplot
# maintains internal references until :func:`~matplotlib.pyplot.close`
# is called.
#
# .. _working-with-text:
#
# Working with text
# =================
#
# The :func:`~matplotlib.pyplot.text` command can be used to add text in
# an arbitrary location, and the :func:`~matplotlib.pyplot.xlabel`,
# :func:`~matplotlib.pyplot.ylabel` and :func:`~matplotlib.pyplot.title`
# are used to add text in the indicated locations (see :doc:`/tutorials/text/text_intro`
# for a more detailed example)
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
# the histogram of the data
n, bins, patches = plt.hist(x, 50, density=1, facecolor='g', alpha=0.75)
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title('Histogram of IQ')
plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
plt.axis([40, 160, 0, 0.03])
plt.grid(True)
plt.show()
###############################################################################
# All of the :func:`~matplotlib.pyplot.text` commands return an
# :class:`matplotlib.text.Text` instance. Just as with with lines
# above, you can customize the properties by passing keyword arguments
# into the text functions or using :func:`~matplotlib.pyplot.setp`::
#
# t = plt.xlabel('my data', fontsize=14, color='red')
#
# These properties are covered in more detail in :doc:`/tutorials/text/text_props`.
#
#
# Using mathematical expressions in text
# --------------------------------------
#
# matplotlib accepts TeX equation expressions in any text expression.
# For example to write the expression :math:`\sigma_i=15` in the title,
# you can write a TeX expression surrounded by dollar signs::
#
# plt.title(r'$\sigma_i=15$')
#
# The ``r`` preceding the title string is important -- it signifies
# that the string is a *raw* string and not to treat backslashes as
# python escapes. matplotlib has a built-in TeX expression parser and
# layout engine, and ships its own math fonts -- for details see
# :doc:`/tutorials/text/mathtext`. Thus you can use mathematical text across platforms
# without requiring a TeX installation. For those who have LaTeX and
# dvipng installed, you can also use LaTeX to format your text and
# incorporate the output directly into your display figures or saved
# postscript -- see :doc:`/tutorials/text/usetex`.
#
#
# Annotating text
# ---------------
#
# The uses of the basic :func:`~matplotlib.pyplot.text` command above
# place text at an arbitrary position on the Axes. A common use for
# text is to annotate some feature of the plot, and the
# :func:`~matplotlib.pyplot.annotate` method provides helper
# functionality to make annotations easy. In an annotation, there are
# two points to consider: the location being annotated represented by
# the argument ``xy`` and the location of the text ``xytext``. Both of
# these arguments are ``(x,y)`` tuples.
ax = plt.subplot(111)
t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
line, = plt.plot(t, s, lw=2)
plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5),
arrowprops=dict(facecolor='black', shrink=0.05),
)
plt.ylim(-2, 2)
plt.show()
###############################################################################
# In this basic example, both the ``xy`` (arrow tip) and ``xytext``
# locations (text location) are in data coordinates. There are a
# variety of other coordinate systems one can choose -- see
# :ref:`annotations-tutorial` and :ref:`plotting-guide-annotation` for
# details. More examples can be found in
# :doc:`/gallery/text_labels_and_annotations/annotation_demo`.
#
#
# Logarithmic and other nonlinear axes
# ====================================
#
# :mod:`matplotlib.pyplot` supports not only linear axis scales, but also
# logarithmic and logit scales. This is commonly used if data spans many orders
# of magnitude. Changing the scale of an axis is easy:
#
# plt.xscale('log')
#
# An example of four plots with the same data and different scales for the y axis
# is shown below.
from matplotlib.ticker import NullFormatter # useful for `logit` scale
# Fixing random state for reproducibility
np.random.seed(19680801)
# make up some data in the interval ]0, 1[
y = np.random.normal(loc=0.5, scale=0.4, size=1000)
y = y[(y > 0) & (y < 1)]
y.sort()
x = np.arange(len(y))
# plot with various axes scales
plt.figure()
# linear
plt.subplot(221)
plt.plot(x, y)
plt.yscale('linear')
plt.title('linear')
plt.grid(True)
# log
plt.subplot(222)
plt.plot(x, y)
plt.yscale('log')
plt.title('log')
plt.grid(True)
# symmetric log
plt.subplot(223)
plt.plot(x, y - y.mean())
plt.yscale('symlog', linthreshy=0.01)
plt.title('symlog')
plt.grid(True)
# logit
plt.subplot(224)
plt.plot(x, y)
plt.yscale('logit')
plt.title('logit')
plt.grid(True)
# Format the minor tick labels of the y-axis into empty strings with
# `NullFormatter`, to avoid cumbering the axis with too many labels.
plt.gca().yaxis.set_minor_formatter(NullFormatter())
# Adjust the subplot layout, because the logit one may take more space
# than usual, due to y-tick labels like "1 - 10^{-3}"
plt.subplots_adjust(top=0.92, bottom=0.08, left=0.10, right=0.95, hspace=0.25,
wspace=0.35)
plt.show()
###############################################################################
# It is also possible to add your own scale, see :ref:`adding-new-scales` for
# details.
|
e6868b710c6d93b386ad7b2279fb48a4fb70a607f0d4121b0a9572500b33e5d9
|
"""
Customizing Matplotlib with style sheets and rcParams
=====================================================
Tips for customizing the properties and default styles of Matplotlib.
Using style sheets
------------------
The ``style`` package adds support for easy-to-switch plotting "styles" with
the same parameters as a
:ref:`matplotlib rc <customizing-with-matplotlibrc-files>` file (which is read
at startup to configure matplotlib).
There are a number of pre-defined styles `provided by Matplotlib`_. For
example, there's a pre-defined style called "ggplot", which emulates the
aesthetics of ggplot_ (a popular plotting package for R_). To use this style,
just add:
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
plt.style.use('ggplot')
data = np.random.randn(50)
###############################################################################
# To list all available styles, use:
print(plt.style.available)
###############################################################################
# Defining your own style
# -----------------------
#
# You can create custom styles and use them by calling ``style.use`` with the
# path or URL to the style sheet. Additionally, if you add your
# ``<style-name>.mplstyle`` file to ``mpl_configdir/stylelib``, you can reuse
# your custom style sheet with a call to ``style.use(<style-name>)``. By default
# ``mpl_configdir`` should be ``~/.config/matplotlib``, but you can check where
# yours is with ``matplotlib.get_configdir()``; you may need to create this
# directory. You also can change the directory where matplotlib looks for
# the stylelib/ folder by setting the MPLCONFIGDIR environment variable,
# see :ref:`locating-matplotlib-config-dir`.
#
# Note that a custom style sheet in ``mpl_configdir/stylelib`` will
# override a style sheet defined by matplotlib if the styles have the same name.
#
# For example, you might want to create
# ``mpl_configdir/stylelib/presentation.mplstyle`` with the following::
#
# axes.titlesize : 24
# axes.labelsize : 20
# lines.linewidth : 3
# lines.markersize : 10
# xtick.labelsize : 16
# ytick.labelsize : 16
#
# Then, when you want to adapt a plot designed for a paper to one that looks
# good in a presentation, you can just add::
#
# >>> import matplotlib.pyplot as plt
# >>> plt.style.use('presentation')
#
#
# Composing styles
# ----------------
#
# Style sheets are designed to be composed together. So you can have a style
# sheet that customizes colors and a separate style sheet that alters element
# sizes for presentations. These styles can easily be combined by passing
# a list of styles::
#
# >>> import matplotlib.pyplot as plt
# >>> plt.style.use(['dark_background', 'presentation'])
#
# Note that styles further to the right will overwrite values that are already
# defined by styles on the left.
#
#
# Temporary styling
# -----------------
#
# If you only want to use a style for a specific block of code but don't want
# to change the global styling, the style package provides a context manager
# for limiting your changes to a specific scope. To isolate your styling
# changes, you can write something like the following:
with plt.style.context('dark_background'):
plt.plot(np.sin(np.linspace(0, 2 * np.pi)), 'r-o')
plt.show()
###############################################################################
# .. _matplotlib-rcparams:
#
# matplotlib rcParams
# ===================
#
# .. _customizing-with-dynamic-rc-settings:
#
# Dynamic rc settings
# -------------------
#
# You can also dynamically change the default rc settings in a python script or
# interactively from the python shell. All of the rc settings are stored in a
# dictionary-like variable called :data:`matplotlib.rcParams`, which is global to
# the matplotlib package. rcParams can be modified directly, for example:
mpl.rcParams['lines.linewidth'] = 2
mpl.rcParams['lines.color'] = 'r'
plt.plot(data)
###############################################################################
# Matplotlib also provides a couple of convenience functions for modifying rc
# settings. The :func:`matplotlib.rc` command can be used to modify multiple
# settings in a single group at once, using keyword arguments:
mpl.rc('lines', linewidth=4, color='g')
plt.plot(data)
###############################################################################
# The :func:`matplotlib.rcdefaults` command will restore the standard matplotlib
# default settings.
#
# There is some degree of validation when setting the values of rcParams, see
# :mod:`matplotlib.rcsetup` for details.
#
# .. _customizing-with-matplotlibrc-files:
#
# The :file:`matplotlibrc` file
# -----------------------------
#
# matplotlib uses :file:`matplotlibrc` configuration files to customize all kinds
# of properties, which we call `rc settings` or `rc parameters`. You can control
# the defaults of almost every property in matplotlib: figure size and dpi, line
# width, color and style, axes, axis and grid properties, text and font
# properties and so on. matplotlib looks for :file:`matplotlibrc` in four
# locations, in the following order:
#
# 1. :file:`matplotlibrc` in the current working directory, usually used for
# specific customizations that you do not want to apply elsewhere.
#
# 2. :file:`$MATPLOTLIBRC` if it is a file, else :file:`$MATPLOTLIBRC/matplotlibrc`.
#
# 3. It next looks in a user-specific place, depending on your platform:
#
# - On Linux and FreeBSD, it looks in :file:`.config/matplotlib/matplotlibrc`
# (or `$XDG_CONFIG_HOME/matplotlib/matplotlibrc`) if you've customized
# your environment.
#
# - On other platforms, it looks in :file:`.matplotlib/matplotlibrc`.
#
# See :ref:`locating-matplotlib-config-dir`.
#
# 4. :file:`{INSTALL}/matplotlib/mpl-data/matplotlibrc`, where
# :file:`{INSTALL}` is something like
# :file:`/usr/lib/python3.7/site-packages` on Linux, and maybe
# :file:`C:\\Python37\\Lib\\site-packages` on Windows. Every time you
# install matplotlib, this file will be overwritten, so if you want
# your customizations to be saved, please move this file to your
# user-specific matplotlib directory.
#
# Once a :file:`matplotlibrc` file has been found, it will *not* search any of
# the other paths.
#
# To display where the currently active :file:`matplotlibrc` file was
# loaded from, one can do the following::
#
# >>> import matplotlib
# >>> matplotlib.matplotlib_fname()
# '/home/foo/.config/matplotlib/matplotlibrc'
#
# See below for a sample :ref:`matplotlibrc file<matplotlibrc-sample>`.
#
# .. _matplotlibrc-sample:
#
# A sample matplotlibrc file
# ~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# .. literalinclude:: ../../../matplotlibrc.template
#
#
# .. _ggplot: https://ggplot2.tidyverse.org/
# .. _R: https://www.r-project.org/
# .. _provided by Matplotlib: https://github.com/matplotlib/matplotlib/tree/master/lib/matplotlib/mpl-data/stylelib
|
81dd2a7c12276941947e5fe4d6e72c0525ebc25956cba4e9e7284f35e3d93eca
|
"""
============
Legend guide
============
Generating legends flexibly in Matplotlib.
.. currentmodule:: matplotlib.pyplot
This legend guide is an extension of the documentation available at
:func:`~matplotlib.pyplot.legend` - please ensure you are familiar with
contents of that documentation before proceeding with this guide.
This guide makes use of some common terms, which are documented here for clarity:
.. glossary::
legend entry
A legend is made up of one or more legend entries. An entry is made up of
exactly one key and one label.
legend key
The colored/patterned marker to the left of each legend label.
legend label
The text which describes the handle represented by the key.
legend handle
The original object which is used to generate an appropriate entry in
the legend.
Controlling the legend entries
==============================
Calling :func:`legend` with no arguments automatically fetches the legend
handles and their associated labels. This functionality is equivalent to::
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles, labels)
The :meth:`~matplotlib.axes.Axes.get_legend_handles_labels` function returns
a list of handles/artists which exist on the Axes which can be used to
generate entries for the resulting legend - it is worth noting however that
not all artists can be added to a legend, at which point a "proxy" will have
to be created (see :ref:`proxy_legend_handles` for further details).
For full control of what is being added to the legend, it is common to pass
the appropriate handles directly to :func:`legend`::
line_up, = plt.plot([1,2,3], label='Line 2')
line_down, = plt.plot([3,2,1], label='Line 1')
plt.legend(handles=[line_up, line_down])
In some cases, it is not possible to set the label of the handle, so it is
possible to pass through the list of labels to :func:`legend`::
line_up, = plt.plot([1,2,3], label='Line 2')
line_down, = plt.plot([3,2,1], label='Line 1')
plt.legend([line_up, line_down], ['Line Up', 'Line Down'])
.. _proxy_legend_handles:
Creating artists specifically for adding to the legend (aka. Proxy artists)
===========================================================================
Not all handles can be turned into legend entries automatically,
so it is often necessary to create an artist which *can*. Legend handles
don't have to exists on the Figure or Axes in order to be used.
Suppose we wanted to create a legend which has an entry for some data which
is represented by a red color:
"""
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
red_patch = mpatches.Patch(color='red', label='The red data')
plt.legend(handles=[red_patch])
plt.show()
###############################################################################
# There are many supported legend handles, instead of creating a patch of color
# we could have created a line with a marker:
import matplotlib.lines as mlines
blue_line = mlines.Line2D([], [], color='blue', marker='*',
markersize=15, label='Blue stars')
plt.legend(handles=[blue_line])
plt.show()
###############################################################################
# Legend location
# ===============
#
# The location of the legend can be specified by the keyword argument
# *loc*. Please see the documentation at :func:`legend` for more details.
#
# The ``bbox_to_anchor`` keyword gives a great degree of control for manual
# legend placement. For example, if you want your axes legend located at the
# figure's top right-hand corner instead of the axes' corner, simply specify
# the corner's location, and the coordinate system of that location::
#
# plt.legend(bbox_to_anchor=(1, 1),
# bbox_transform=plt.gcf().transFigure)
#
# More examples of custom legend placement:
plt.subplot(211)
plt.plot([1, 2, 3], label="test1")
plt.plot([3, 2, 1], label="test2")
# Place a legend above this subplot, expanding itself to
# fully use the given bounding box.
plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc='lower left',
ncol=2, mode="expand", borderaxespad=0.)
plt.subplot(223)
plt.plot([1, 2, 3], label="test1")
plt.plot([3, 2, 1], label="test2")
# Place a legend to the right of this smaller subplot.
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0.)
plt.show()
###############################################################################
# Multiple legends on the same Axes
# =================================
#
# Sometimes it is more clear to split legend entries across multiple
# legends. Whilst the instinctive approach to doing this might be to call
# the :func:`legend` function multiple times, you will find that only one
# legend ever exists on the Axes. This has been done so that it is possible
# to call :func:`legend` repeatedly to update the legend to the latest
# handles on the Axes, so to persist old legend instances, we must add them
# manually to the Axes:
line1, = plt.plot([1, 2, 3], label="Line 1", linestyle='--')
line2, = plt.plot([3, 2, 1], label="Line 2", linewidth=4)
# Create a legend for the first line.
first_legend = plt.legend(handles=[line1], loc='upper right')
# Add the legend manually to the current Axes.
ax = plt.gca().add_artist(first_legend)
# Create another legend for the second line.
plt.legend(handles=[line2], loc='lower right')
plt.show()
###############################################################################
# Legend Handlers
# ===============
#
# In order to create legend entries, handles are given as an argument to an
# appropriate :class:`~matplotlib.legend_handler.HandlerBase` subclass.
# The choice of handler subclass is determined by the following rules:
#
# 1. Update :func:`~matplotlib.legend.Legend.get_legend_handler_map`
# with the value in the ``handler_map`` keyword.
# 2. Check if the ``handle`` is in the newly created ``handler_map``.
# 3. Check if the type of ``handle`` is in the newly created
# ``handler_map``.
# 4. Check if any of the types in the ``handle``'s mro is in the newly
# created ``handler_map``.
#
# For completeness, this logic is mostly implemented in
# :func:`~matplotlib.legend.Legend.get_legend_handler`.
#
# All of this flexibility means that we have the necessary hooks to implement
# custom handlers for our own type of legend key.
#
# The simplest example of using custom handlers is to instantiate one of the
# existing :class:`~matplotlib.legend_handler.HandlerBase` subclasses. For the
# sake of simplicity, let's choose :class:`matplotlib.legend_handler.HandlerLine2D`
# which accepts a ``numpoints`` argument (note numpoints is a keyword
# on the :func:`legend` function for convenience). We can then pass the mapping
# of instance to Handler as a keyword to legend.
from matplotlib.legend_handler import HandlerLine2D
line1, = plt.plot([3, 2, 1], marker='o', label='Line 1')
line2, = plt.plot([1, 2, 3], marker='o', label='Line 2')
plt.legend(handler_map={line1: HandlerLine2D(numpoints=4)})
###############################################################################
# As you can see, "Line 1" now has 4 marker points, where "Line 2" has 2 (the
# default). Try the above code, only change the map's key from ``line1`` to
# ``type(line1)``. Notice how now both :class:`~matplotlib.lines.Line2D` instances
# get 4 markers.
#
# Along with handlers for complex plot types such as errorbars, stem plots
# and histograms, the default ``handler_map`` has a special ``tuple`` handler
# (:class:`~matplotlib.legend_handler.HandlerTuple`) which simply plots
# the handles on top of one another for each item in the given tuple. The
# following example demonstrates combining two legend keys on top of one another:
from numpy.random import randn
z = randn(10)
red_dot, = plt.plot(z, "ro", markersize=15)
# Put a white cross over some of the data.
white_cross, = plt.plot(z[:5], "w+", markeredgewidth=3, markersize=15)
plt.legend([red_dot, (red_dot, white_cross)], ["Attr A", "Attr A+B"])
###############################################################################
# The :class:`~matplotlib.legend_handler.HandlerTuple` class can also be used to
# assign several legend keys to the same entry:
from matplotlib.legend_handler import HandlerLine2D, HandlerTuple
p1, = plt.plot([1, 2.5, 3], 'r-d')
p2, = plt.plot([3, 2, 1], 'k-o')
l = plt.legend([(p1, p2)], ['Two keys'], numpoints=1,
handler_map={tuple: HandlerTuple(ndivide=None)})
###############################################################################
# Implementing a custom legend handler
# ------------------------------------
#
# A custom handler can be implemented to turn any handle into a legend key (handles
# don't necessarily need to be matplotlib artists).
# The handler must implement a "legend_artist" method which returns a
# single artist for the legend to use. Signature details about the "legend_artist"
# are documented at :meth:`~matplotlib.legend_handler.HandlerBase.legend_artist`.
import matplotlib.patches as mpatches
class AnyObject(object):
pass
class AnyObjectHandler(object):
def legend_artist(self, legend, orig_handle, fontsize, handlebox):
x0, y0 = handlebox.xdescent, handlebox.ydescent
width, height = handlebox.width, handlebox.height
patch = mpatches.Rectangle([x0, y0], width, height, facecolor='red',
edgecolor='black', hatch='xx', lw=3,
transform=handlebox.get_transform())
handlebox.add_artist(patch)
return patch
plt.legend([AnyObject()], ['My first handler'],
handler_map={AnyObject: AnyObjectHandler()})
###############################################################################
# Alternatively, had we wanted to globally accept ``AnyObject`` instances without
# needing to manually set the ``handler_map`` keyword all the time, we could have
# registered the new handler with::
#
# from matplotlib.legend import Legend
# Legend.update_default_handler_map({AnyObject: AnyObjectHandler()})
#
# Whilst the power here is clear, remember that there are already many handlers
# implemented and what you want to achieve may already be easily possible with
# existing classes. For example, to produce elliptical legend keys, rather than
# rectangular ones:
from matplotlib.legend_handler import HandlerPatch
class HandlerEllipse(HandlerPatch):
def create_artists(self, legend, orig_handle,
xdescent, ydescent, width, height, fontsize, trans):
center = 0.5 * width - 0.5 * xdescent, 0.5 * height - 0.5 * ydescent
p = mpatches.Ellipse(xy=center, width=width + xdescent,
height=height + ydescent)
self.update_prop(p, orig_handle, legend)
p.set_transform(trans)
return [p]
c = mpatches.Circle((0.5, 0.5), 0.25, facecolor="green",
edgecolor="red", linewidth=3)
plt.gca().add_patch(c)
plt.legend([c], ["An ellipse, not a rectangle"],
handler_map={mpatches.Circle: HandlerEllipse()})
|
2bc286518cc269b8059534ab6d0354bbb16c954c037c321c827aa9944a216d54
|
"""
=============================================================
Customizing Figure Layouts Using GridSpec and Other Functions
=============================================================
How to create grid-shaped combinations of axes.
:func:`~matplotlib.pyplot.subplots`
Perhaps the primary function used to create figures and axes.
It's also similar to :func:`.matplotlib.pyplot.subplot`,
but creates and places all axes on the figure at once. See also
`matplotlib.Figure.subplots`.
:class:`~matplotlib.gridspec.GridSpec`
Specifies the geometry of the grid that a subplot will be
placed. The number of rows and number of columns of the grid
need to be set. Optionally, the subplot layout parameters
(e.g., left, right, etc.) can be tuned.
:class:`~matplotlib.gridspec.SubplotSpec`
Specifies the location of the subplot in the given *GridSpec*.
:func:`~matplotlib.pyplot.subplot2grid`
A helper function that is similar to
:func:`~matplotlib.pyplot.subplot`,
but uses 0-based indexing and let subplot to occupy multiple cells.
This function is not covered in this tutorial.
"""
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
############################################################################
# Basic Quickstart Guide
# ======================
#
# These first two examples show how to create a basic 2-by-2 grid using
# both :func:`~matplotlib.pyplot.subplots` and :mod:`~matplotlib.gridspec`.
#
# Using :func:`~matplotlib.pyplot.subplots` is quite simple.
# It returns a :class:`~matplotlib.figure.Figure` instance and an array of
# :class:`~matplotlib.axes.Axes` objects.
fig1, f1_axes = plt.subplots(ncols=2, nrows=2, constrained_layout=True)
############################################################################
# For a simple use case such as this, :mod:`~matplotlib.gridspec` is
# perhaps overly verbose.
# You have to create the figure and :class:`~matplotlib.gridspec.GridSpec`
# instance separately, then pass elements of gridspec instance to the
# :func:`~matplotlib.figure.Figure.add_subplot` method to create the axes
# objects.
# The elements of the gridspec are accessed in generally the same manner as
# numpy arrays.
fig2 = plt.figure(constrained_layout=True)
spec2 = gridspec.GridSpec(ncols=2, nrows=2, figure=fig2)
f2_ax1 = fig2.add_subplot(spec2[0, 0])
f2_ax2 = fig2.add_subplot(spec2[0, 1])
f2_ax3 = fig2.add_subplot(spec2[1, 0])
f2_ax4 = fig2.add_subplot(spec2[1, 1])
#############################################################################
# The power of gridspec comes in being able to create subplots that span
# rows and columns. Note the
# `Numpy slice <https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html>`_
# syntax for selecting the part of the gridspec each subplot will occupy.
#
# Note that we have also used the convenience method `.Figure.add_gridspec`
# instead of `.gridspec.GridSpec`, potentially saving the user an import,
# and keeping the namespace cleaner.
fig3 = plt.figure(constrained_layout=True)
gs = fig3.add_gridspec(3, 3)
f3_ax1 = fig3.add_subplot(gs[0, :])
f3_ax1.set_title('gs[0, :]')
f3_ax2 = fig3.add_subplot(gs[1, :-1])
f3_ax2.set_title('gs[1, :-1]')
f3_ax3 = fig3.add_subplot(gs[1:, -1])
f3_ax3.set_title('gs[1:, -1]')
f3_ax4 = fig3.add_subplot(gs[-1, 0])
f3_ax4.set_title('gs[-1, 0]')
f3_ax5 = fig3.add_subplot(gs[-1, -2])
f3_ax5.set_title('gs[-1, -2]')
#############################################################################
# :mod:`~matplotlib.gridspec` is also indispensable for creating subplots
# of different widths via a couple of methods.
#
# The method shown here is similar to the one above and initializes a
# uniform grid specification,
# and then uses numpy indexing and slices to allocate multiple
# "cells" for a given subplot.
fig4 = plt.figure(constrained_layout=True)
spec4 = fig4.add_gridspec(ncols=2, nrows=2)
anno_opts = dict(xy=(0.5, 0.5), xycoords='axes fraction',
va='center', ha='center')
f4_ax1 = fig4.add_subplot(spec4[0, 0])
f4_ax1.annotate('GridSpec[0, 0]', **anno_opts)
fig4.add_subplot(spec4[0, 1]).annotate('GridSpec[0, 1:]', **anno_opts)
fig4.add_subplot(spec4[1, 0]).annotate('GridSpec[1:, 0]', **anno_opts)
fig4.add_subplot(spec4[1, 1]).annotate('GridSpec[1:, 1:]', **anno_opts)
############################################################################
# Another option is to use the ``width_ratios`` and ``height_ratios``
# parameters. These keyword arguments are lists of numbers.
# Note that absolute values are meaningless, only their relative ratios
# matter. That means that ``width_ratios=[2, 4, 8]`` is equivalent to
# ``width_ratios=[1, 2, 4]`` within equally wide figures.
# For the sake of demonstration, we'll blindly create the axes within
# ``for`` loops since we won't need them later.
fig5 = plt.figure(constrained_layout=True)
widths = [2, 3, 1.5]
heights = [1, 3, 2]
spec5 = fig5.add_gridspec(ncols=3, nrows=3, width_ratios=widths,
height_ratios=heights)
for row in range(3):
for col in range(3):
ax = fig5.add_subplot(spec5[row, col])
label = 'Width: {}\nHeight: {}'.format(widths[col], heights[row])
ax.annotate(label, (0.1, 0.5), xycoords='axes fraction', va='center')
############################################################################
# Learning to use ``width_ratios`` and ``height_ratios`` is particularly
# useful since the top-level function :func:`~matplotlib.pyplot.subplots`
# accepts them within the ``gridspec_kw`` parameter.
# For that matter, any parameter accepted by
# :class:`~matplotlib.gridspec.GridSpec` can be passed to
# :func:`~matplotlib.pyplot.subplots` via the ``gridspec_kw`` parameter.
# This example recreates the previous figure without directly using a
# gridspec instance.
gs_kw = dict(width_ratios=widths, height_ratios=heights)
fig6, f6_axes = plt.subplots(ncols=3, nrows=3, constrained_layout=True,
gridspec_kw=gs_kw)
for r, row in enumerate(f6_axes):
for c, ax in enumerate(row):
label = 'Width: {}\nHeight: {}'.format(widths[c], heights[r])
ax.annotate(label, (0.1, 0.5), xycoords='axes fraction', va='center')
############################################################################
# The ``subplots`` and ``gridspec`` methods can be combined since it is
# sometimes more convenient to make most of the subplots using ``subplots``
# and then remove some and combine them. Here we create a layout with
# the bottom two axes in the last column combined.
fig7, f7_axs = plt.subplots(ncols=3, nrows=3)
gs = f7_axs[1, 2].get_gridspec()
# remove the underlying axes
for ax in f7_axs[1:, -1]:
ax.remove()
axbig = fig7.add_subplot(gs[1:, -1])
axbig.annotate('Big Axes \nGridSpec[1:, -1]', (0.1, 0.5),
xycoords='axes fraction', va='center')
fig7.tight_layout()
###############################################################################
# Fine Adjustments to a Gridspec Layout
# =====================================
#
# When a GridSpec is explicitly used, you can adjust the layout
# parameters of subplots that are created from the GridSpec. Note this
# option is not compatible with ``constrained_layout`` or
# `.Figure.tight_layout` which both adjust subplot sizes to fill the
# figure.
fig8 = plt.figure(constrained_layout=False)
gs1 = fig8.add_gridspec(nrows=3, ncols=3, left=0.05, right=0.48, wspace=0.05)
f8_ax1 = fig8.add_subplot(gs1[:-1, :])
f8_ax2 = fig8.add_subplot(gs1[-1, :-1])
f8_ax3 = fig8.add_subplot(gs1[-1, -1])
###############################################################################
# This is similar to :func:`~matplotlib.pyplot.subplots_adjust`, but it only
# affects the subplots that are created from the given GridSpec.
#
# For example, compare the left and right sides of this figure:
fig9 = plt.figure(constrained_layout=False)
gs1 = fig9.add_gridspec(nrows=3, ncols=3, left=0.05, right=0.48,
wspace=0.05)
f9_ax1 = fig9.add_subplot(gs1[:-1, :])
f9_ax2 = fig9.add_subplot(gs1[-1, :-1])
f9_ax3 = fig9.add_subplot(gs1[-1, -1])
gs2 = fig9.add_gridspec(nrows=3, ncols=3, left=0.55, right=0.98,
hspace=0.05)
f9_ax4 = fig9.add_subplot(gs2[:, :-1])
f9_ax5 = fig9.add_subplot(gs2[:-1, -1])
f9_ax6 = fig9.add_subplot(gs2[-1, -1])
###############################################################################
# GridSpec using SubplotSpec
# ==========================
#
# You can create GridSpec from the :class:`~matplotlib.gridspec.SubplotSpec`,
# in which case its layout parameters are set to that of the location of
# the given SubplotSpec.
#
# Note this is also available from the more verbose
# `.gridspec.GridSpecFromSubplotSpec`.
fig10 = plt.figure(constrained_layout=True)
gs0 = fig10.add_gridspec(1, 2)
gs00 = gs0[0].subgridspec(2, 3)
gs01 = gs0[1].subgridspec(3, 2)
for a in range(2):
for b in range(3):
fig10.add_subplot(gs00[a, b])
fig10.add_subplot(gs01[b, a])
###############################################################################
# A Complex Nested GridSpec using SubplotSpec
# ===========================================
#
# Here's a more sophisticated example of nested GridSpec where we put
# a box around each cell of the outer 4x4 grid, by hiding appropriate
# spines in each of the inner 3x3 grids.
import numpy as np
from itertools import product
def squiggle_xy(a, b, c, d, i=np.arange(0.0, 2*np.pi, 0.05)):
return np.sin(i*a)*np.cos(i*b), np.sin(i*c)*np.cos(i*d)
fig11 = plt.figure(figsize=(8, 8), constrained_layout=False)
# gridspec inside gridspec
outer_grid = fig11.add_gridspec(4, 4, wspace=0.0, hspace=0.0)
for i in range(16):
inner_grid = outer_grid[i].subgridspec(3, 3, wspace=0.0, hspace=0.0)
a, b = int(i/4)+1, i % 4+1
for j, (c, d) in enumerate(product(range(1, 4), repeat=2)):
ax = fig11.add_subplot(inner_grid[j])
ax.plot(*squiggle_xy(a, b, c, d))
ax.set_xticks([])
ax.set_yticks([])
fig11.add_subplot(ax)
all_axes = fig11.get_axes()
# show only the outside spines
for ax in all_axes:
for sp in ax.spines.values():
sp.set_visible(False)
if ax.is_first_row():
ax.spines['top'].set_visible(True)
if ax.is_last_row():
ax.spines['bottom'].set_visible(True)
if ax.is_first_col():
ax.spines['left'].set_visible(True)
if ax.is_last_col():
ax.spines['right'].set_visible(True)
plt.show()
#############################################################################
#
# ------------
#
# References
# """"""""""
#
# The usage of the following functions and methods is shown in this example:
matplotlib.pyplot.subplots
matplotlib.figure.Figure.add_gridspec
matplotlib.figure.Figure.add_subplot
matplotlib.gridspec.GridSpec
matplotlib.gridspec.SubplotSpec.subgridspec
matplotlib.gridspec.GridSpecFromSubplotSpec
|
306176fb5cb00cabb9aff5f03de0547e799e34fef15f9600e16ef63b1a3b2295
|
"""
================================
Constrained Layout Guide
================================
How to use constrained-layout to fit plots within your figure cleanly.
*constrained_layout* automatically adjusts subplots and decorations like
legends and colorbars so that they fit in the figure window while still
preserving, as best they can, the logical layout requested by the user.
*constrained_layout* is similar to
:doc:`tight_layout</tutorials/intermediate/tight_layout_guide>`,
but uses a constraint solver to determine the size of axes that allows
them to fit.
*constrained_layout* needs to be activated before any axes are added to
a figure. Two ways of doing so are
* using the respective argument to :func:`~.pyplot.subplots` or
:func:`~.pyplot.figure`, e.g.::
plt.subplots(constrained_layout=True)
* activate it via :ref:`rcParams<matplotlib-rcparams>`, like::
plt.rcParams['figure.constrained_layout.use'] = True
Those are described in detail throughout the following sections.
.. warning::
Currently Constrained Layout is **experimental**. The
behaviour and API are subject to change, or the whole functionality
may be removed without a deprecation period. If you *require* your
plots to be absolutely reproducible, get the Axes positions after
running Constrained Layout and use ``ax.set_position()`` in your code
with ``constrained_layout=False``.
Simple Example
==============
In Matplotlib, the location of axes (including subplots) are specified in
normalized figure coordinates. It can happen that your axis labels or
titles (or sometimes even ticklabels) go outside the figure area, and are thus
clipped.
"""
# sphinx_gallery_thumbnail_number = 18
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import matplotlib.gridspec as gridspec
import numpy as np
plt.rcParams['savefig.facecolor'] = "0.8"
plt.rcParams['figure.figsize'] = 4.5, 4.
def example_plot(ax, fontsize=12, nodec=False):
ax.plot([1, 2])
ax.locator_params(nbins=3)
if not nodec:
ax.set_xlabel('x-label', fontsize=fontsize)
ax.set_ylabel('y-label', fontsize=fontsize)
ax.set_title('Title', fontsize=fontsize)
else:
ax.set_xticklabels('')
ax.set_yticklabels('')
fig, ax = plt.subplots(constrained_layout=False)
example_plot(ax, fontsize=24)
###############################################################################
# To prevent this, the location of axes needs to be adjusted. For
# subplots, this can be done by adjusting the subplot params
# (:ref:`howto-subplots-adjust`). However, specifying your figure with the
# ``constrained_layout=True`` kwarg will do the adjusting automatically.
fig, ax = plt.subplots(constrained_layout=True)
example_plot(ax, fontsize=24)
###############################################################################
# When you have multiple subplots, often you see labels of different
# axes overlapping each other.
fig, axs = plt.subplots(2, 2, constrained_layout=False)
for ax in axs.flatten():
example_plot(ax)
###############################################################################
# Specifying ``constrained_layout=True`` in the call to ``plt.subplots``
# causes the layout to be properly constrained.
fig, axs = plt.subplots(2, 2, constrained_layout=True)
for ax in axs.flatten():
example_plot(ax)
###############################################################################
# Colorbars
# =========
#
# If you create a colorbar with the :func:`~matplotlib.pyplot.colorbar`
# command you need to make room for it. ``constrained_layout`` does this
# automatically. Note that if you specify ``use_gridspec=True`` it will be
# ignored because this option is made for improving the layout via
# ``tight_layout``.
#
# .. note::
#
# For the `~.axes.Axes.pcolormesh` kwargs (``pc_kwargs``) we use a
# dictionary. Below we will assign one colorbar to a number of axes each
# containing a `~.cm.ScalarMappable`; specifying the norm and colormap
# ensures the colorbar is accurate for all the axes.
arr = np.arange(100).reshape((10, 10))
norm = mcolors.Normalize(vmin=0., vmax=100.)
# see note above: this makes all pcolormesh calls consistent:
pc_kwargs = {'rasterized': True, 'cmap': 'viridis', 'norm': norm}
fig, ax = plt.subplots(figsize=(4, 4), constrained_layout=True)
im = ax.pcolormesh(arr, **pc_kwargs)
fig.colorbar(im, ax=ax, shrink=0.6)
############################################################################
# If you specify a list of axes (or other iterable container) to the
# ``ax`` argument of ``colorbar``, constrained_layout will take space from
# the specified axes.
fig, axs = plt.subplots(2, 2, figsize=(4, 4), constrained_layout=True)
for ax in axs.flatten():
im = ax.pcolormesh(arr, **pc_kwargs)
fig.colorbar(im, ax=axs, shrink=0.6)
############################################################################
# If you specify a list of axes from inside a grid of axes, the colorbar
# will steal space appropriately, and leave a gap, but all subplots will
# still be the same size.
fig, axs = plt.subplots(3, 3, figsize=(4, 4), constrained_layout=True)
for ax in axs.flatten():
im = ax.pcolormesh(arr, **pc_kwargs)
fig.colorbar(im, ax=axs[1:, ][:, 1], shrink=0.8)
fig.colorbar(im, ax=axs[:, -1], shrink=0.6)
############################################################################
# Note that there is a bit of a subtlety when specifying a single axes
# as the parent. In the following, it might be desirable and expected
# for the colorbars to line up, but they don't because the colorbar paired
# with the bottom axes is tied to the subplotspec of the axes, and hence
# shrinks when the gridspec-level colorbar is added.
fig, axs = plt.subplots(3, 1, figsize=(4, 4), constrained_layout=True)
for ax in axs[:2]:
im = ax.pcolormesh(arr, **pc_kwargs)
fig.colorbar(im, ax=axs[:2], shrink=0.6)
im = axs[2].pcolormesh(arr, **pc_kwargs)
fig.colorbar(im, ax=axs[2], shrink=0.6)
############################################################################
# The API to make a single-axes behave like a list of axes is to specify
# it as a list (or other iterable container), as below:
fig, axs = plt.subplots(3, 1, figsize=(4, 4), constrained_layout=True)
for ax in axs[:2]:
im = ax.pcolormesh(arr, **pc_kwargs)
fig.colorbar(im, ax=axs[:2], shrink=0.6)
im = axs[2].pcolormesh(arr, **pc_kwargs)
fig.colorbar(im, ax=[axs[2]], shrink=0.6)
####################################################
# Suptitle
# =========
#
# ``constrained_layout`` can also make room for `~.figure.Figure.suptitle`.
fig, axs = plt.subplots(2, 2, figsize=(4, 4), constrained_layout=True)
for ax in axs.flatten():
im = ax.pcolormesh(arr, **pc_kwargs)
fig.colorbar(im, ax=axs, shrink=0.6)
fig.suptitle('Big Suptitle')
####################################################
# Legends
# =======
#
# Legends can be placed outside of their parent axis.
# Constrained-layout is designed to handle this for :meth:`.Axes.legend`.
# However, constrained-layout does *not* handle legends being created via
# :meth:`.Figure.legend` (yet).
fig, ax = plt.subplots(constrained_layout=True)
ax.plot(np.arange(10), label='This is a plot')
ax.legend(loc='center left', bbox_to_anchor=(0.8, 0.5))
#############################################
# However, this will steal space from a subplot layout:
fig, axs = plt.subplots(1, 2, figsize=(4, 2), constrained_layout=True)
axs[0].plot(np.arange(10))
axs[1].plot(np.arange(10), label='This is a plot')
axs[1].legend(loc='center left', bbox_to_anchor=(0.8, 0.5))
#############################################
# In order for a legend or other artist to *not* steal space
# from the subplot layout, we can ``leg.set_in_layout(False)``.
# Of course this can mean the legend ends up
# cropped, but can be useful if the plot is subsequently called
# with ``fig.savefig('outname.png', bbox_inches='tight')``. Note,
# however, that the legend's ``get_in_layout`` status will have to be
# toggled again to make the saved file work, and we must manually
# trigger a draw if we want constrained_layout to adjust the size
# of the axes before printing.
fig, axs = plt.subplots(1, 2, figsize=(4, 2), constrained_layout=True)
axs[0].plot(np.arange(10))
axs[1].plot(np.arange(10), label='This is a plot')
leg = axs[1].legend(loc='center left', bbox_to_anchor=(0.8, 0.5))
leg.set_in_layout(False)
# trigger a draw so that constrained_layout is executed once
# before we turn it off when printing....
fig.canvas.draw()
# we want the legend included in the bbox_inches='tight' calcs.
leg.set_in_layout(True)
# we don't want the layout to change at this point.
fig.set_constrained_layout(False)
fig.savefig('CL01.png', bbox_inches='tight', dpi=100)
#############################################
# The saved file looks like:
#
# .. image:: /_static/constrained_layout/CL01.png
# :align: center
#
# A better way to get around this awkwardness is to simply
# use the legend method provided by `.Figure.legend`:
fig, axs = plt.subplots(1, 2, figsize=(4, 2), constrained_layout=True)
axs[0].plot(np.arange(10))
lines = axs[1].plot(np.arange(10), label='This is a plot')
labels = [l.get_label() for l in lines]
leg = fig.legend(lines, labels, loc='center left',
bbox_to_anchor=(0.8, 0.5), bbox_transform=axs[1].transAxes)
fig.savefig('CL02.png', bbox_inches='tight', dpi=100)
#############################################
# The saved file looks like:
#
# .. image:: /_static/constrained_layout/CL02.png
# :align: center
#
###############################################################################
# Padding and Spacing
# ===================
#
# For constrained_layout, we have implemented a padding around the edge of
# each axes. This padding sets the distance from the edge of the plot,
# and the minimum distance between adjacent plots. It is specified in
# inches by the keyword arguments ``w_pad`` and ``h_pad`` to the function
# `~.figure.Figure.set_constrained_layout_pads`:
fig, axs = plt.subplots(2, 2, constrained_layout=True)
for ax in axs.flatten():
example_plot(ax, nodec=True)
ax.set_xticklabels('')
ax.set_yticklabels('')
fig.set_constrained_layout_pads(w_pad=4./72., h_pad=4./72.,
hspace=0., wspace=0.)
fig, axs = plt.subplots(2, 2, constrained_layout=True)
for ax in axs.flatten():
example_plot(ax, nodec=True)
ax.set_xticklabels('')
ax.set_yticklabels('')
fig.set_constrained_layout_pads(w_pad=2./72., h_pad=2./72.,
hspace=0., wspace=0.)
##########################################
# Spacing between subplots is set by ``wspace`` and ``hspace``. There are
# specified as a fraction of the size of the subplot group as a whole.
# If the size of the figure is changed, then these spaces change in
# proportion. Note in the blow how the space at the edges doesn't change from
# the above, but the space between subplots does.
fig, axs = plt.subplots(2, 2, constrained_layout=True)
for ax in axs.flatten():
example_plot(ax, nodec=True)
ax.set_xticklabels('')
ax.set_yticklabels('')
fig.set_constrained_layout_pads(w_pad=2./72., h_pad=2./72.,
hspace=0.2, wspace=0.2)
##########################################
# Spacing with colorbars
# -----------------------
#
# Colorbars will be placed ``wspace`` and ``hsapce`` apart from other
# subplots. The padding between the colorbar and the axis it is
# attached to will never be less than ``w_pad`` (for a vertical colorbar)
# or ``h_pad`` (for a horizontal colorbar). Note the use of the ``pad`` kwarg
# here in the ``colorbar`` call. It defaults to 0.02 of the size
# of the axis it is attached to.
fig, axs = plt.subplots(2, 2, constrained_layout=True)
for ax in axs.flatten():
pc = ax.pcolormesh(arr, **pc_kwargs)
fig.colorbar(pc, ax=ax, shrink=0.6, pad=0)
ax.set_xticklabels('')
ax.set_yticklabels('')
fig.set_constrained_layout_pads(w_pad=2./72., h_pad=2./72.,
hspace=0.2, wspace=0.2)
##########################################
# In the above example, the colorbar will not ever be closer than 2 pts to
# the plot, but if we want it a bit further away, we can specify its value
# for ``pad`` to be non-zero.
fig, axs = plt.subplots(2, 2, constrained_layout=True)
for ax in axs.flatten():
pc = ax.pcolormesh(arr, **pc_kwargs)
fig.colorbar(im, ax=ax, shrink=0.6, pad=0.05)
ax.set_xticklabels('')
ax.set_yticklabels('')
fig.set_constrained_layout_pads(w_pad=2./72., h_pad=2./72.,
hspace=0.2, wspace=0.2)
##########################################
# rcParams
# ========
#
# There are five :ref:`rcParams<matplotlib-rcparams>` that can be set,
# either in a script or in the `matplotlibrc` file.
# They all have the prefix ``figure.constrained_layout``:
#
# - ``use``: Whether to use constrained_layout. Default is False
# - ``w_pad``, ``h_pad``: Padding around axes objects.
# Float representing inches. Default is 3./72. inches (3 pts)
# - ``wspace``, ``hspace``: Space between subplot groups.
# Float representing a fraction of the subplot widths being separated.
# Default is 0.02.
plt.rcParams['figure.constrained_layout.use'] = True
fig, axs = plt.subplots(2, 2, figsize=(3, 3))
for ax in axs.flatten():
example_plot(ax)
#############################
# Use with GridSpec
# =================
#
# constrained_layout is meant to be used
# with :func:`~matplotlib.figure.Figure.subplots` or
# :func:`~matplotlib.gridspec.GridSpec` and
# :func:`~matplotlib.figure.Figure.add_subplot`.
#
# Note that in what follows ``constrained_layout=True``
fig = plt.figure()
gs1 = gridspec.GridSpec(2, 1, figure=fig)
ax1 = fig.add_subplot(gs1[0])
ax2 = fig.add_subplot(gs1[1])
example_plot(ax1)
example_plot(ax2)
###############################################################################
# More complicated gridspec layouts are possible. Note here we use the
# convenience functions ``add_gridspec`` and ``subgridspec``.
fig = plt.figure()
gs0 = fig.add_gridspec(1, 2)
gs1 = gs0[0].subgridspec(2, 1)
ax1 = fig.add_subplot(gs1[0])
ax2 = fig.add_subplot(gs1[1])
example_plot(ax1)
example_plot(ax2)
gs2 = gs0[1].subgridspec(3, 1)
for ss in gs2:
ax = fig.add_subplot(ss)
example_plot(ax)
ax.set_title("")
ax.set_xlabel("")
ax.set_xlabel("x-label", fontsize=12)
############################################################################
# Note that in the above the left and columns don't have the same vertical
# extent. If we want the top and bottom of the two grids to line up then
# they need to be in the same gridspec:
fig = plt.figure()
gs0 = fig.add_gridspec(6, 2)
ax1 = fig.add_subplot(gs0[:3, 0])
ax2 = fig.add_subplot(gs0[3:, 0])
example_plot(ax1)
example_plot(ax2)
ax = fig.add_subplot(gs0[0:2, 1])
example_plot(ax)
ax = fig.add_subplot(gs0[2:4, 1])
example_plot(ax)
ax = fig.add_subplot(gs0[4:, 1])
example_plot(ax)
############################################################################
# This example uses two gridspecs to have the colorbar only pertain to
# one set of pcolors. Note how the left column is wider than the
# two right-hand columns because of this. Of course, if you wanted the
# subplots to be the same size you only needed one gridspec.
def docomplicated(suptitle=None):
fig = plt.figure()
gs0 = fig.add_gridspec(1, 2, figure=fig, width_ratios=[1., 2.])
gsl = gs0[0].subgridspec(2, 1)
gsr = gs0[1].subgridspec(2, 2)
for gs in gsl:
ax = fig.add_subplot(gs)
example_plot(ax)
axs = []
for gs in gsr:
ax = fig.add_subplot(gs)
pcm = ax.pcolormesh(arr, **pc_kwargs)
ax.set_xlabel('x-label')
ax.set_ylabel('y-label')
ax.set_title('title')
axs += [ax]
fig.colorbar(pcm, ax=axs)
if suptitle is not None:
fig.suptitle(suptitle)
docomplicated()
###############################################################################
# Manually setting axes positions
# ================================
#
# There can be good reasons to manually set an axes position. A manual call
# to `~.axes.Axes.set_position` will set the axes so constrained_layout has
# no effect on it anymore. (Note that constrained_layout still leaves the
# space for the axes that is moved).
fig, axs = plt.subplots(1, 2)
example_plot(axs[0], fontsize=12)
axs[1].set_position([0.2, 0.2, 0.4, 0.4])
###############################################################################
# If you want an inset axes in data-space, you need to manually execute the
# layout using ``fig.execute_constrained_layout()`` call. The inset figure
# will then be properly positioned. However, it will not be properly
# positioned if the size of the figure is subsequently changed. Similarly,
# if the figure is printed to another backend, there may be slight changes
# of location due to small differences in how the backends render fonts.
from matplotlib.transforms import Bbox
fig, axs = plt.subplots(1, 2)
example_plot(axs[0], fontsize=12)
fig.execute_constrained_layout()
# put into data-space:
bb_data_ax2 = Bbox.from_bounds(0.5, 1., 0.2, 0.4)
disp_coords = axs[0].transData.transform(bb_data_ax2)
fig_coords_ax2 = fig.transFigure.inverted().transform(disp_coords)
bb_ax2 = Bbox(fig_coords_ax2)
ax2 = fig.add_axes(bb_ax2)
###############################################################################
# Manually turning off ``constrained_layout``
# ===========================================
#
# ``constrained_layout`` usually adjusts the axes positions on each draw
# of the figure. If you want to get the spacing provided by
# ``constrained_layout`` but not have it update, then do the initial
# draw and then call ``fig.set_constrained_layout(False)``.
# This is potentially useful for animations where the tick labels may
# change length.
#
# Note that ``constrained_layout`` is turned off for ``ZOOM`` and ``PAN``
# GUI events for the backends that use the toolbar. This prevents the
# axes from changing position during zooming and panning.
#
#
# Limitations
# ========================
#
# Incompatible functions
# ----------------------
#
# ``constrained_layout`` will not work on subplots
# created via the `subplot` command. The reason is that each of these
# commands creates a separate `GridSpec` instance and ``constrained_layout``
# uses (nested) gridspecs to carry out the layout. So the following fails
# to yield a nice layout:
fig = plt.figure()
ax1 = plt.subplot(221)
ax2 = plt.subplot(223)
ax3 = plt.subplot(122)
example_plot(ax1)
example_plot(ax2)
example_plot(ax3)
###############################################################################
# Of course that layout is possible using a gridspec:
fig = plt.figure()
gs = fig.add_gridspec(2, 2)
ax1 = fig.add_subplot(gs[0, 0])
ax2 = fig.add_subplot(gs[1, 0])
ax3 = fig.add_subplot(gs[:, 1])
example_plot(ax1)
example_plot(ax2)
example_plot(ax3)
###############################################################################
# Similarly,
# :func:`~matplotlib.pyplot.subplot2grid` doesn't work for the same reason:
# each call creates a different parent gridspec.
fig = plt.figure()
ax1 = plt.subplot2grid((3, 3), (0, 0))
ax2 = plt.subplot2grid((3, 3), (0, 1), colspan=2)
ax3 = plt.subplot2grid((3, 3), (1, 0), colspan=2, rowspan=2)
ax4 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)
example_plot(ax1)
example_plot(ax2)
example_plot(ax3)
example_plot(ax4)
###############################################################################
# The way to make this plot compatible with ``constrained_layout`` is again
# to use ``gridspec`` directly
fig = plt.figure()
gs = fig.add_gridspec(3, 3)
ax1 = fig.add_subplot(gs[0, 0])
ax2 = fig.add_subplot(gs[0, 1:])
ax3 = fig.add_subplot(gs[1:, 0:2])
ax4 = fig.add_subplot(gs[1:, -1])
example_plot(ax1)
example_plot(ax2)
example_plot(ax3)
example_plot(ax4)
###############################################################################
# Other Caveats
# -------------
#
# * ``constrained_layout`` only considers ticklabels, axis labels, titles, and
# legends. Thus, other artists may be clipped and also may overlap.
#
# * It assumes that the extra space needed for ticklabels, axis labels,
# and titles is independent of original location of axes. This is
# often true, but there are rare cases where it is not.
#
# * There are small differences in how the backends handle rendering fonts,
# so the results will not be pixel-identical.
###########################################################
# Debugging
# =========
#
# Constrained-layout can fail in somewhat unexpected ways. Because it uses
# a constraint solver the solver can find solutions that are mathematically
# correct, but that aren't at all what the user wants. The usual failure
# mode is for all sizes to collapse to their smallest allowable value. If
# this happens, it is for one of two reasons:
#
# 1. There was not enough room for the elements you were requesting to draw.
# 2. There is a bug - in which case open an issue at
# https://github.com/matplotlib/matplotlib/issues.
#
# If there is a bug, please report with a self-contained example that does
# not require outside data or dependencies (other than numpy).
###########################################################
# Notes on the algorithm
# ======================
#
# The algorithm for the constraint is relatively straightforward, but
# has some complexity due to the complex ways we can layout a figure.
#
# Figure layout
# -------------
#
# Figures are laid out in a hierarchy:
#
# 1. Figure: ``fig = plt.figure()``
#
# a. Gridspec ``gs0 = gridspec.GridSpec(1, 2, figure=fig)``
#
# i. Subplotspec: ``ss = gs[0, 0]``
#
# 1. Axes: ``ax0 = fig.add_subplot(ss)``
#
# ii. Subplotspec: ``ss = gs[0, 1]``
#
# 1. Gridspec: ``gsR = gridspec.GridSpecFromSubplotSpec(2, 1, ss)``
#
# - Subplotspec: ``ss = gsR[0, 0]``
#
# - Axes: ``axR0 = fig.add_subplot(ss)``
#
# - Subplotspec: ``ss = gsR[1, 0]``
#
# - Axes: ``axR1 = fig.add_subplot(ss)``
#
# Each item has a layoutbox associated with it. The nesting of gridspecs
# created with `.GridSpecFromSubplotSpec` can be arbitrarily deep.
#
# Each `~matplotlib.axes.Axes` has *two* layoutboxes. The first one,
# ``ax._layoutbox`` represents the outside of the Axes and all its
# decorations (i.e. ticklabels,axis labels, etc.).
# The second layoutbox corresponds to the Axes' ``ax.position``, which sets
# where in the figure the spines are placed.
#
# Why so many stacked containers? Ideally, all that would be needed are the
# Axes layout boxes. For the Gridspec case, a container is
# needed if the Gridspec is nested via `.GridSpecFromSubplotSpec`. At the
# top level, it is desirable for symmetry, but it also makes room for
# `~.Figure.suptitle`.
#
# For the Subplotspec/Axes case, Axes often have colorbars or other
# annotations that need to be packaged inside the Subplotspec, hence the
# need for the outer layer.
#
#
# Simple case: one Axes
# ---------------------
#
# For a single Axes the layout is straight forward. The Figure and
# outer Gridspec layoutboxes coincide. The Subplotspec and Axes
# boxes also coincide because the Axes has no colorbar. Note
# the difference between the red ``pos`` box and the green ``ax`` box
# is set by the size of the decorations around the Axes.
#
# In the code, this is accomplished by the entries in
# ``do_constrained_layout()`` like::
#
# ax._poslayoutbox.edit_left_margin_min(-bbox.x0 + pos.x0 + w_padt)
#
from matplotlib._layoutbox import plot_children
fig, ax = plt.subplots(constrained_layout=True)
example_plot(ax, fontsize=24)
plot_children(fig, fig._layoutbox, printit=False)
#######################################################################
# Simple case: two Axes
# ---------------------
# For this case, the Axes layoutboxes and the Subplotspec boxes still
# co-incide. However, because the decorations in the right-hand plot are so
# much smaller than the left-hand, so the right-hand layoutboxes are smaller.
#
# The Subplotspec boxes are laid out in the code in the subroutine
# ``arange_subplotspecs()``, which simply checks the subplotspecs in the code
# against one another and stacks them appropriately.
#
# The two ``pos`` axes are lined up. Because they have the same
# minimum row, they are lined up at the top. Because
# they have the same maximum row they are lined up at the bottom. In the
# code this is accomplished via the calls to ``layoutbox.align``. If
# there was more than one row, then the same horizontal alignment would
# occur between the rows.
#
# The two ``pos`` axes are given the same width because the subplotspecs
# occupy the same number of columns. This is accomplished in the code where
# ``dcols0`` is compared to ``dcolsC``. If they are equal, then their widths
# are constrained to be equal.
#
# While it is a bit subtle in this case, note that the division between the
# Subplotspecs is *not* centered, but has been moved to the right to make
# space for the larger labels on the left-hand plot.
fig, ax = plt.subplots(1, 2, constrained_layout=True)
example_plot(ax[0], fontsize=32)
example_plot(ax[1], fontsize=8)
plot_children(fig, fig._layoutbox, printit=False)
#######################################################################
# Two Axes and colorbar
# ---------------------
#
# Adding a colorbar makes it clear why the Subplotspec layoutboxes must
# be different from the axes layoutboxes. Here we see the left-hand
# subplotspec has more room to accommodate the `~.Figure.colorbar`, and
# that there are two green ``ax`` boxes inside the ``ss`` box.
#
# Note that the width of the ``pos`` boxes is still the same because of the
# constraint on their widths because their subplotspecs occupy the same
# number of columns (one in this example).
#
# The colorbar layout logic is contained in `~matplotlib.colorbar.make_axes`
# which calls ``_constrained_layout.layoutcolorbarsingle()``
# for cbars attached to a single axes, and
# ``_constrained_layout.layoutcolorbargridspec()`` if the colorbar is
# associated with a gridspec.
fig, ax = plt.subplots(1, 2, constrained_layout=True)
im = ax[0].pcolormesh(arr, **pc_kwargs)
fig.colorbar(im, ax=ax[0], shrink=0.6)
im = ax[1].pcolormesh(arr, **pc_kwargs)
plot_children(fig, fig._layoutbox, printit=False)
#######################################################################
# Colorbar associated with a Gridspec
# -----------------------------------
#
# This example shows the Subplotspec layoutboxes being made smaller by
# a colorbar layoutbox. The size of the colorbar layoutbox is
# set to be ``shrink`` smaller than the vertical extent of the ``pos``
# layoutboxes in the gridspec, and it is made to be centered between
# those two points.
fig, ax = plt.subplots(2, 2, constrained_layout=True)
for a in ax.flatten():
im = a.pcolormesh(arr, **pc_kwargs)
fig.colorbar(im, ax=ax, shrink=0.6)
plot_children(fig, fig._layoutbox, printit=False)
#######################################################################
# Uneven sized Axes
# -----------------
#
# There are two ways to make axes have an uneven size in a
# Gridspec layout, either by specifying them to cross Gridspecs rows
# or columns, or by specifying width and height ratios.
#
# The first method is used here. The constraint that makes the heights
# be correct is in the code where ``drowsC < drows0`` which in
# this case would be 1 is less than 2. So we constrain the
# height of the 1-row Axes to be less than half the height of the
# 2-row Axes.
#
# .. note::
#
# This algorithm can be wrong if the decorations attached to the smaller
# axes are very large, so there is an unaccounted-for edge case.
fig = plt.figure(constrained_layout=True)
gs = gridspec.GridSpec(2, 2, figure=fig)
ax = fig.add_subplot(gs[:, 0])
im = ax.pcolormesh(arr, **pc_kwargs)
ax = fig.add_subplot(gs[0, 1])
im = ax.pcolormesh(arr, **pc_kwargs)
ax = fig.add_subplot(gs[1, 1])
im = ax.pcolormesh(arr, **pc_kwargs)
plot_children(fig, fig._layoutbox, printit=False)
#######################################################################
# Height and width ratios are accommodated with the same part of
# the code with the smaller axes always constrained to be less in size
# than the larger.
fig = plt.figure(constrained_layout=True)
gs = gridspec.GridSpec(3, 2, figure=fig,
height_ratios=[1., 0.5, 1.5],
width_ratios=[1.2, 0.8])
ax = fig.add_subplot(gs[:2, 0])
im = ax.pcolormesh(arr, **pc_kwargs)
ax = fig.add_subplot(gs[2, 0])
im = ax.pcolormesh(arr, **pc_kwargs)
ax = fig.add_subplot(gs[0, 1])
im = ax.pcolormesh(arr, **pc_kwargs)
ax = fig.add_subplot(gs[1:, 1])
im = ax.pcolormesh(arr, **pc_kwargs)
plot_children(fig, fig._layoutbox, printit=False)
########################################################################
# Empty gridspec slots
# --------------------
#
# The final piece of the code that has not been explained is what happens if
# there is an empty gridspec opening. In that case a fake invisible axes is
# added and we proceed as before. The empty gridspec has no decorations, but
# the axes position in made the same size as the occupied Axes positions.
#
# This is done at the start of
# ``_constrained_layout.do_constrained_layout()`` (``hassubplotspec``).
fig = plt.figure(constrained_layout=True)
gs = gridspec.GridSpec(1, 3, figure=fig)
ax = fig.add_subplot(gs[0])
im = ax.pcolormesh(arr, **pc_kwargs)
ax = fig.add_subplot(gs[-1])
im = ax.pcolormesh(arr, **pc_kwargs)
plot_children(fig, fig._layoutbox, printit=False)
plt.show()
########################################################################
# Other notes
# -----------
#
# The layout is called only once. This is OK if the original layout was
# pretty close (which it should be in most cases). However, if the layout
# changes a lot from the default layout then the decorators can change size.
# In particular the x and ytick labels can change. If this happens, then
# we should probably call the whole routine twice.
|
f14ca760ff0a41f6426ee88b9b60b024a7047320a32d26d2977840f0e109dee8
|
"""
===============
Artist tutorial
===============
Using Artist objects to render on the canvas.
There are three layers to the matplotlib API.
* the :class:`matplotlib.backend_bases.FigureCanvas` is the area onto which
the figure is drawn
* the :class:`matplotlib.backend_bases.Renderer` is
the object which knows how to draw on the
:class:`~matplotlib.backend_bases.FigureCanvas`
* and the :class:`matplotlib.artist.Artist` is the object that knows how to use
a renderer to paint onto the canvas.
The :class:`~matplotlib.backend_bases.FigureCanvas` and
:class:`~matplotlib.backend_bases.Renderer` handle all the details of
talking to user interface toolkits like `wxPython
<https://www.wxpython.org>`_ or drawing languages like PostScript®, and
the ``Artist`` handles all the high level constructs like representing
and laying out the figure, text, and lines. The typical user will
spend 95% of their time working with the ``Artists``.
There are two types of ``Artists``: primitives and containers. The primitives
represent the standard graphical objects we want to paint onto our canvas:
:class:`~matplotlib.lines.Line2D`, :class:`~matplotlib.patches.Rectangle`,
:class:`~matplotlib.text.Text`, :class:`~matplotlib.image.AxesImage`, etc., and
the containers are places to put them (:class:`~matplotlib.axis.Axis`,
:class:`~matplotlib.axes.Axes` and :class:`~matplotlib.figure.Figure`). The
standard use is to create a :class:`~matplotlib.figure.Figure` instance, use
the ``Figure`` to create one or more :class:`~matplotlib.axes.Axes` or
:class:`~matplotlib.axes.Subplot` instances, and use the ``Axes`` instance
helper methods to create the primitives. In the example below, we create a
``Figure`` instance using :func:`matplotlib.pyplot.figure`, which is a
convenience method for instantiating ``Figure`` instances and connecting them
with your user interface or drawing toolkit ``FigureCanvas``. As we will
discuss below, this is not necessary -- you can work directly with PostScript,
PDF Gtk+, or wxPython ``FigureCanvas`` instances, instantiate your ``Figures``
directly and connect them yourselves -- but since we are focusing here on the
``Artist`` API we'll let :mod:`~matplotlib.pyplot` handle some of those details
for us::
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(2, 1, 1) # two rows, one column, first plot
The :class:`~matplotlib.axes.Axes` is probably the most important
class in the matplotlib API, and the one you will be working with most
of the time. This is because the ``Axes`` is the plotting area into
which most of the objects go, and the ``Axes`` has many special helper
methods (:meth:`~matplotlib.axes.Axes.plot`,
:meth:`~matplotlib.axes.Axes.text`,
:meth:`~matplotlib.axes.Axes.hist`,
:meth:`~matplotlib.axes.Axes.imshow`) to create the most common
graphics primitives (:class:`~matplotlib.lines.Line2D`,
:class:`~matplotlib.text.Text`,
:class:`~matplotlib.patches.Rectangle`,
:class:`~matplotlib.image.Image`, respectively). These helper methods
will take your data (e.g., ``numpy`` arrays and strings) and create
primitive ``Artist`` instances as needed (e.g., ``Line2D``), add them to
the relevant containers, and draw them when requested. Most of you
are probably familiar with the :class:`~matplotlib.axes.Subplot`,
which is just a special case of an ``Axes`` that lives on a regular
rows by columns grid of ``Subplot`` instances. If you want to create
an ``Axes`` at an arbitrary location, simply use the
:meth:`~matplotlib.figure.Figure.add_axes` method which takes a list
of ``[left, bottom, width, height]`` values in 0-1 relative figure
coordinates::
fig2 = plt.figure()
ax2 = fig2.add_axes([0.15, 0.1, 0.7, 0.3])
Continuing with our example::
import numpy as np
t = np.arange(0.0, 1.0, 0.01)
s = np.sin(2*np.pi*t)
line, = ax.plot(t, s, color='blue', lw=2)
In this example, ``ax`` is the ``Axes`` instance created by the
``fig.add_subplot`` call above (remember ``Subplot`` is just a
subclass of ``Axes``) and when you call ``ax.plot``, it creates a
``Line2D`` instance and adds it to the :attr:`Axes.lines
<matplotlib.axes.Axes.lines>` list. In the interactive `ipython
<http://ipython.org/>`_ session below, you can see that the
``Axes.lines`` list is length one and contains the same line that was
returned by the ``line, = ax.plot...`` call:
.. sourcecode:: ipython
In [101]: ax.lines[0]
Out[101]: <matplotlib.lines.Line2D instance at 0x19a95710>
In [102]: line
Out[102]: <matplotlib.lines.Line2D instance at 0x19a95710>
If you make subsequent calls to ``ax.plot`` (and the hold state is "on"
which is the default) then additional lines will be added to the list.
You can remove lines later simply by calling the list methods; either
of these will work::
del ax.lines[0]
ax.lines.remove(line) # one or the other, not both!
The Axes also has helper methods to configure and decorate the x-axis
and y-axis tick, tick labels and axis labels::
xtext = ax.set_xlabel('my xdata') # returns a Text instance
ytext = ax.set_ylabel('my ydata')
When you call :meth:`ax.set_xlabel <matplotlib.axes.Axes.set_xlabel>`,
it passes the information on the :class:`~matplotlib.text.Text`
instance of the :class:`~matplotlib.axis.XAxis`. Each ``Axes``
instance contains an :class:`~matplotlib.axis.XAxis` and a
:class:`~matplotlib.axis.YAxis` instance, which handle the layout and
drawing of the ticks, tick labels and axis labels.
Try creating the figure below.
"""
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
fig.subplots_adjust(top=0.8)
ax1 = fig.add_subplot(211)
ax1.set_ylabel('volts')
ax1.set_title('a sine wave')
t = np.arange(0.0, 1.0, 0.01)
s = np.sin(2*np.pi*t)
line, = ax1.plot(t, s, color='blue', lw=2)
# Fixing random state for reproducibility
np.random.seed(19680801)
ax2 = fig.add_axes([0.15, 0.1, 0.7, 0.3])
n, bins, patches = ax2.hist(np.random.randn(1000), 50,
facecolor='yellow', edgecolor='yellow')
ax2.set_xlabel('time (s)')
plt.show()
###############################################################################
# .. _customizing-artists:
#
# Customizing your objects
# ========================
#
# Every element in the figure is represented by a matplotlib
# :class:`~matplotlib.artist.Artist`, and each has an extensive list of
# properties to configure its appearance. The figure itself contains a
# :class:`~matplotlib.patches.Rectangle` exactly the size of the figure,
# which you can use to set the background color and transparency of the
# figures. Likewise, each :class:`~matplotlib.axes.Axes` bounding box
# (the standard white box with black edges in the typical matplotlib
# plot, has a ``Rectangle`` instance that determines the color,
# transparency, and other properties of the Axes. These instances are
# stored as member variables :attr:`Figure.patch
# <matplotlib.figure.Figure.patch>` and :attr:`Axes.patch
# <matplotlib.axes.Axes.patch>` ("Patch" is a name inherited from
# MATLAB, and is a 2D "patch" of color on the figure, e.g., rectangles,
# circles and polygons). Every matplotlib ``Artist`` has the following
# properties
#
# ========== ================================================================================
# Property Description
# ========== ================================================================================
# alpha The transparency - a scalar from 0-1
# animated A boolean that is used to facilitate animated drawing
# axes The axes that the Artist lives in, possibly None
# clip_box The bounding box that clips the Artist
# clip_on Whether clipping is enabled
# clip_path The path the artist is clipped to
# contains A picking function to test whether the artist contains the pick point
# figure The figure instance the artist lives in, possibly None
# label A text label (e.g., for auto-labeling)
# picker A python object that controls object picking
# transform The transformation
# visible A boolean whether the artist should be drawn
# zorder A number which determines the drawing order
# rasterized Boolean; Turns vectors into raster graphics (for compression & eps transparency)
# ========== ================================================================================
#
# Each of the properties is accessed with an old-fashioned setter or
# getter (yes we know this irritates Pythonistas and we plan to support
# direct access via properties or traits but it hasn't been done yet).
# For example, to multiply the current alpha by a half::
#
# a = o.get_alpha()
# o.set_alpha(0.5*a)
#
# If you want to set a number of properties at once, you can also use
# the ``set`` method with keyword arguments. For example::
#
# o.set(alpha=0.5, zorder=2)
#
# If you are working interactively at the python shell, a handy way to
# inspect the ``Artist`` properties is to use the
# :func:`matplotlib.artist.getp` function (simply
# :func:`~matplotlib.pyplot.getp` in pyplot), which lists the properties
# and their values. This works for classes derived from ``Artist`` as
# well, e.g., ``Figure`` and ``Rectangle``. Here are the ``Figure`` rectangle
# properties mentioned above:
#
# .. sourcecode:: ipython
#
# In [149]: matplotlib.artist.getp(fig.patch)
# alpha = 1.0
# animated = False
# antialiased or aa = True
# axes = None
# clip_box = None
# clip_on = False
# clip_path = None
# contains = None
# edgecolor or ec = w
# facecolor or fc = 0.75
# figure = Figure(8.125x6.125)
# fill = 1
# hatch = None
# height = 1
# label =
# linewidth or lw = 1.0
# picker = None
# transform = <Affine object at 0x134cca84>
# verts = ((0, 0), (0, 1), (1, 1), (1, 0))
# visible = True
# width = 1
# window_extent = <Bbox object at 0x134acbcc>
# x = 0
# y = 0
# zorder = 1
#
# The docstrings for all of the classes also contain the ``Artist``
# properties, so you can consult the interactive "help" or the
# :ref:`artist-api` for a listing of properties for a given object.
#
# .. _object-containers:
#
# Object containers
# =================
#
#
# Now that we know how to inspect and set the properties of a given
# object we want to configure, we need to know how to get at that object.
# As mentioned in the introduction, there are two kinds of objects:
# primitives and containers. The primitives are usually the things you
# want to configure (the font of a :class:`~matplotlib.text.Text`
# instance, the width of a :class:`~matplotlib.lines.Line2D`) although
# the containers also have some properties as well -- for example the
# :class:`~matplotlib.axes.Axes` :class:`~matplotlib.artist.Artist` is a
# container that contains many of the primitives in your plot, but it
# also has properties like the ``xscale`` to control whether the xaxis
# is 'linear' or 'log'. In this section we'll review where the various
# container objects store the ``Artists`` that you want to get at.
#
# .. _figure-container:
#
# Figure container
# ----------------
#
# The top level container ``Artist`` is the
# :class:`matplotlib.figure.Figure`, and it contains everything in the
# figure. The background of the figure is a
# :class:`~matplotlib.patches.Rectangle` which is stored in
# :attr:`Figure.patch <matplotlib.figure.Figure.patch>`. As
# you add subplots (:meth:`~matplotlib.figure.Figure.add_subplot`) and
# axes (:meth:`~matplotlib.figure.Figure.add_axes`) to the figure
# these will be appended to the :attr:`Figure.axes
# <matplotlib.figure.Figure.axes>`. These are also returned by the
# methods that create them:
#
# .. sourcecode:: ipython
#
# In [156]: fig = plt.figure()
#
# In [157]: ax1 = fig.add_subplot(211)
#
# In [158]: ax2 = fig.add_axes([0.1, 0.1, 0.7, 0.3])
#
# In [159]: ax1
# Out[159]: <matplotlib.axes.Subplot instance at 0xd54b26c>
#
# In [160]: print(fig.axes)
# [<matplotlib.axes.Subplot instance at 0xd54b26c>, <matplotlib.axes.Axes instance at 0xd3f0b2c>]
#
# Because the figure maintains the concept of the "current axes" (see
# :meth:`Figure.gca <matplotlib.figure.Figure.gca>` and
# :meth:`Figure.sca <matplotlib.figure.Figure.sca>`) to support the
# pylab/pyplot state machine, you should not insert or remove axes
# directly from the axes list, but rather use the
# :meth:`~matplotlib.figure.Figure.add_subplot` and
# :meth:`~matplotlib.figure.Figure.add_axes` methods to insert, and the
# :meth:`~matplotlib.figure.Figure.delaxes` method to delete. You are
# free however, to iterate over the list of axes or index into it to get
# access to ``Axes`` instances you want to customize. Here is an
# example which turns all the axes grids on::
#
# for ax in fig.axes:
# ax.grid(True)
#
#
# The figure also has its own text, lines, patches and images, which you
# can use to add primitives directly. The default coordinate system for
# the ``Figure`` will simply be in pixels (which is not usually what you
# want) but you can control this by setting the transform property of
# the ``Artist`` you are adding to the figure.
#
# .. TODO: Is that still true?
#
# More useful is "figure coordinates" where (0, 0) is the bottom-left of
# the figure and (1, 1) is the top-right of the figure which you can
# obtain by setting the ``Artist`` transform to :attr:`fig.transFigure
# <matplotlib.figure.Figure.transFigure>`:
import matplotlib.lines as lines
fig = plt.figure()
l1 = lines.Line2D([0, 1], [0, 1], transform=fig.transFigure, figure=fig)
l2 = lines.Line2D([0, 1], [1, 0], transform=fig.transFigure, figure=fig)
fig.lines.extend([l1, l2])
plt.show()
###############################################################################
# Here is a summary of the Artists the figure contains
#
# .. TODO: Add xrefs to this table
#
# ================ ===============================================================
# Figure attribute Description
# ================ ===============================================================
# axes A list of Axes instances (includes Subplot)
# patch The Rectangle background
# images A list of FigureImages patches - useful for raw pixel display
# legends A list of Figure Legend instances (different from Axes.legends)
# lines A list of Figure Line2D instances (rarely used, see Axes.lines)
# patches A list of Figure patches (rarely used, see Axes.patches)
# texts A list Figure Text instances
# ================ ===============================================================
#
# .. _axes-container:
#
# Axes container
# --------------
#
# The :class:`matplotlib.axes.Axes` is the center of the matplotlib
# universe -- it contains the vast majority of all the ``Artists`` used
# in a figure with many helper methods to create and add these
# ``Artists`` to itself, as well as helper methods to access and
# customize the ``Artists`` it contains. Like the
# :class:`~matplotlib.figure.Figure`, it contains a
# :class:`~matplotlib.patches.Patch`
# :attr:`~matplotlib.axes.Axes.patch` which is a
# :class:`~matplotlib.patches.Rectangle` for Cartesian coordinates and a
# :class:`~matplotlib.patches.Circle` for polar coordinates; this patch
# determines the shape, background and border of the plotting region::
#
# ax = fig.add_subplot(111)
# rect = ax.patch # a Rectangle instance
# rect.set_facecolor('green')
#
# When you call a plotting method, e.g., the canonical
# :meth:`~matplotlib.axes.Axes.plot` and pass in arrays or lists of
# values, the method will create a :meth:`matplotlib.lines.Line2D`
# instance, update the line with all the ``Line2D`` properties passed as
# keyword arguments, add the line to the :attr:`Axes.lines
# <matplotlib.axes.Axes.lines>` container, and returns it to you:
#
# .. sourcecode:: ipython
#
# In [213]: x, y = np.random.rand(2, 100)
#
# In [214]: line, = ax.plot(x, y, '-', color='blue', linewidth=2)
#
# ``plot`` returns a list of lines because you can pass in multiple x, y
# pairs to plot, and we are unpacking the first element of the length
# one list into the line variable. The line has been added to the
# ``Axes.lines`` list:
#
# .. sourcecode:: ipython
#
# In [229]: print(ax.lines)
# [<matplotlib.lines.Line2D instance at 0xd378b0c>]
#
# Similarly, methods that create patches, like
# :meth:`~matplotlib.axes.Axes.bar` creates a list of rectangles, will
# add the patches to the :attr:`Axes.patches
# <matplotlib.axes.Axes.patches>` list:
#
# .. sourcecode:: ipython
#
# In [233]: n, bins, rectangles = ax.hist(np.random.randn(1000), 50, facecolor='yellow')
#
# In [234]: rectangles
# Out[234]: <a list of 50 Patch objects>
#
# In [235]: print(len(ax.patches))
#
# You should not add objects directly to the ``Axes.lines`` or
# ``Axes.patches`` lists unless you know exactly what you are doing,
# because the ``Axes`` needs to do a few things when it creates and adds
# an object. It sets the figure and axes property of the ``Artist``, as
# well as the default ``Axes`` transformation (unless a transformation
# is set). It also inspects the data contained in the ``Artist`` to
# update the data structures controlling auto-scaling, so that the view
# limits can be adjusted to contain the plotted data. You can,
# nonetheless, create objects yourself and add them directly to the
# ``Axes`` using helper methods like
# :meth:`~matplotlib.axes.Axes.add_line` and
# :meth:`~matplotlib.axes.Axes.add_patch`. Here is an annotated
# interactive session illustrating what is going on:
#
# .. sourcecode:: ipython
#
# In [262]: fig, ax = plt.subplots()
#
# # create a rectangle instance
# In [263]: rect = matplotlib.patches.Rectangle( (1,1), width=5, height=12)
#
# # by default the axes instance is None
# In [264]: print(rect.get_axes())
# None
#
# # and the transformation instance is set to the "identity transform"
# In [265]: print(rect.get_transform())
# <Affine object at 0x13695544>
#
# # now we add the Rectangle to the Axes
# In [266]: ax.add_patch(rect)
#
# # and notice that the ax.add_patch method has set the axes
# # instance
# In [267]: print(rect.get_axes())
# Axes(0.125,0.1;0.775x0.8)
#
# # and the transformation has been set too
# In [268]: print(rect.get_transform())
# <Affine object at 0x15009ca4>
#
# # the default axes transformation is ax.transData
# In [269]: print(ax.transData)
# <Affine object at 0x15009ca4>
#
# # notice that the xlimits of the Axes have not been changed
# In [270]: print(ax.get_xlim())
# (0.0, 1.0)
#
# # but the data limits have been updated to encompass the rectangle
# In [271]: print(ax.dataLim.bounds)
# (1.0, 1.0, 5.0, 12.0)
#
# # we can manually invoke the auto-scaling machinery
# In [272]: ax.autoscale_view()
#
# # and now the xlim are updated to encompass the rectangle
# In [273]: print(ax.get_xlim())
# (1.0, 6.0)
#
# # we have to manually force a figure draw
# In [274]: ax.figure.canvas.draw()
#
#
# There are many, many ``Axes`` helper methods for creating primitive
# ``Artists`` and adding them to their respective containers. The table
# below summarizes a small sampling of them, the kinds of ``Artist`` they
# create, and where they store them
#
# ============================== ==================== =======================
# Helper method Artist Container
# ============================== ==================== =======================
# ax.annotate - text annotations Annotate ax.texts
# ax.bar - bar charts Rectangle ax.patches
# ax.errorbar - error bar plots Line2D and Rectangle ax.lines and ax.patches
# ax.fill - shared area Polygon ax.patches
# ax.hist - histograms Rectangle ax.patches
# ax.imshow - image data AxesImage ax.images
# ax.legend - axes legends Legend ax.legends
# ax.plot - xy plots Line2D ax.lines
# ax.scatter - scatter charts PolygonCollection ax.collections
# ax.text - text Text ax.texts
# ============================== ==================== =======================
#
#
# In addition to all of these ``Artists``, the ``Axes`` contains two
# important ``Artist`` containers: the :class:`~matplotlib.axis.XAxis`
# and :class:`~matplotlib.axis.YAxis`, which handle the drawing of the
# ticks and labels. These are stored as instance variables
# :attr:`~matplotlib.axes.Axes.xaxis` and
# :attr:`~matplotlib.axes.Axes.yaxis`. The ``XAxis`` and ``YAxis``
# containers will be detailed below, but note that the ``Axes`` contains
# many helper methods which forward calls on to the
# :class:`~matplotlib.axis.Axis` instances so you often do not need to
# work with them directly unless you want to. For example, you can set
# the font color of the ``XAxis`` ticklabels using the ``Axes`` helper
# method::
#
# for label in ax.get_xticklabels():
# label.set_color('orange')
#
# Below is a summary of the Artists that the Axes contains
#
# ============== ======================================
# Axes attribute Description
# ============== ======================================
# artists A list of Artist instances
# patch Rectangle instance for Axes background
# collections A list of Collection instances
# images A list of AxesImage
# legends A list of Legend instances
# lines A list of Line2D instances
# patches A list of Patch instances
# texts A list of Text instances
# xaxis matplotlib.axis.XAxis instance
# yaxis matplotlib.axis.YAxis instance
# ============== ======================================
#
# .. _axis-container:
#
# Axis containers
# ---------------
#
# The :class:`matplotlib.axis.Axis` instances handle the drawing of the
# tick lines, the grid lines, the tick labels and the axis label. You
# can configure the left and right ticks separately for the y-axis, and
# the upper and lower ticks separately for the x-axis. The ``Axis``
# also stores the data and view intervals used in auto-scaling, panning
# and zooming, as well as the :class:`~matplotlib.ticker.Locator` and
# :class:`~matplotlib.ticker.Formatter` instances which control where
# the ticks are placed and how they are represented as strings.
#
# Each ``Axis`` object contains a :attr:`~matplotlib.axis.Axis.label` attribute
# (this is what :mod:`~matplotlib.pyplot` modifies in calls to
# :func:`~matplotlib.pyplot.xlabel` and :func:`~matplotlib.pyplot.ylabel`) as
# well as a list of major and minor ticks. The ticks are
# :class:`~matplotlib.axis.XTick` and :class:`~matplotlib.axis.YTick` instances,
# which contain the actual line and text primitives that render the ticks and
# ticklabels. Because the ticks are dynamically created as needed (e.g., when
# panning and zooming), you should access the lists of major and minor ticks
# through their accessor methods :meth:`~matplotlib.axis.Axis.get_major_ticks`
# and :meth:`~matplotlib.axis.Axis.get_minor_ticks`. Although the ticks contain
# all the primitives and will be covered below, ``Axis`` instances have accessor
# methods that return the tick lines, tick labels, tick locations etc.:
fig, ax = plt.subplots()
axis = ax.xaxis
axis.get_ticklocs()
###############################################################################
axis.get_ticklabels()
###############################################################################
# note there are twice as many ticklines as labels because by
# default there are tick lines at the top and bottom but only tick
# labels below the xaxis; this can be customized
axis.get_ticklines()
###############################################################################
# by default you get the major ticks back
axis.get_ticklines()
###############################################################################
# but you can also ask for the minor ticks
axis.get_ticklines(minor=True)
# Here is a summary of some of the useful accessor methods of the ``Axis``
# (these have corresponding setters where useful, such as
# set_major_formatter)
#
# ====================== =========================================================
# Accessor method Description
# ====================== =========================================================
# get_scale The scale of the axis, e.g., 'log' or 'linear'
# get_view_interval The interval instance of the axis view limits
# get_data_interval The interval instance of the axis data limits
# get_gridlines A list of grid lines for the Axis
# get_label The axis label - a Text instance
# get_ticklabels A list of Text instances - keyword minor=True|False
# get_ticklines A list of Line2D instances - keyword minor=True|False
# get_ticklocs A list of Tick locations - keyword minor=True|False
# get_major_locator The matplotlib.ticker.Locator instance for major ticks
# get_major_formatter The matplotlib.ticker.Formatter instance for major ticks
# get_minor_locator The matplotlib.ticker.Locator instance for minor ticks
# get_minor_formatter The matplotlib.ticker.Formatter instance for minor ticks
# get_major_ticks A list of Tick instances for major ticks
# get_minor_ticks A list of Tick instances for minor ticks
# grid Turn the grid on or off for the major or minor ticks
# ====================== =========================================================
#
# Here is an example, not recommended for its beauty, which customizes
# the axes and tick properties
# plt.figure creates a matplotlib.figure.Figure instance
fig = plt.figure()
rect = fig.patch # a rectangle instance
rect.set_facecolor('lightgoldenrodyellow')
ax1 = fig.add_axes([0.1, 0.3, 0.4, 0.4])
rect = ax1.patch
rect.set_facecolor('lightslategray')
for label in ax1.xaxis.get_ticklabels():
# label is a Text instance
label.set_color('red')
label.set_rotation(45)
label.set_fontsize(16)
for line in ax1.yaxis.get_ticklines():
# line is a Line2D instance
line.set_color('green')
line.set_markersize(25)
line.set_markeredgewidth(3)
plt.show()
###############################################################################
# .. _tick-container:
#
# Tick containers
# ---------------
#
# The :class:`matplotlib.axis.Tick` is the final container object in our
# descent from the :class:`~matplotlib.figure.Figure` to the
# :class:`~matplotlib.axes.Axes` to the :class:`~matplotlib.axis.Axis`
# to the :class:`~matplotlib.axis.Tick`. The ``Tick`` contains the tick
# and grid line instances, as well as the label instances for the upper
# and lower ticks. Each of these is accessible directly as an attribute
# of the ``Tick``.
#
# ============== ==========================================================
# Tick attribute Description
# ============== ==========================================================
# tick1line Line2D instance
# tick2line Line2D instance
# gridline Line2D instance
# label1 Text instance
# label2 Text instance
# ============== ==========================================================
#
# Here is an example which sets the formatter for the right side ticks with
# dollar signs and colors them green on the right side of the yaxis
import matplotlib.ticker as ticker
# Fixing random state for reproducibility
np.random.seed(19680801)
fig, ax = plt.subplots()
ax.plot(100*np.random.rand(20))
formatter = ticker.FormatStrFormatter('$%1.2f')
ax.yaxis.set_major_formatter(formatter)
for tick in ax.yaxis.get_major_ticks():
tick.label1.set_visible(False)
tick.label2.set_visible(True)
tick.label2.set_color('green')
plt.show()
|
3c6449746d390e3a459527e7d7c728da825eedc38d5bb1e21bd0319f90f95874
|
"""
===================
Styling with cycler
===================
Demo of custom property-cycle settings to control colors and other style
properties for multi-line plots.
.. note::
More complete documentation of the ``cycler`` API can be found
`here <http://matplotlib.org/cycler/>`_.
This example demonstrates two different APIs:
1. Setting the default rc parameter specifying the property cycle.
This affects all subsequent axes (but not axes already created).
2. Setting the property cycle for a single pair of axes.
"""
from cycler import cycler
import numpy as np
import matplotlib.pyplot as plt
###############################################################################
# First we'll generate some sample data, in this case, four offset sine
# curves.
x = np.linspace(0, 2 * np.pi, 50)
offsets = np.linspace(0, 2 * np.pi, 4, endpoint=False)
yy = np.transpose([np.sin(x + phi) for phi in offsets])
###############################################################################
# Now ``yy`` has shape
print(yy.shape)
###############################################################################
# So ``yy[:, i]`` will give you the ``i``-th offset sine curve. Let's set the
# default prop_cycle using :func:`matplotlib.pyplot.rc`. We'll combine a color
# cycler and a linestyle cycler by adding (``+``) two ``cycler``'s together.
# See the bottom of this tutorial for more information about combining
# different cyclers.
default_cycler = (cycler(color=['r', 'g', 'b', 'y']) +
cycler(linestyle=['-', '--', ':', '-.']))
plt.rc('lines', linewidth=4)
plt.rc('axes', prop_cycle=default_cycler)
###############################################################################
# Now we'll generate a figure with two axes, one on top of the other. On the
# first axis, we'll plot with the default cycler. On the second axis, we'll
# set the prop_cycler using :func:`matplotlib.axes.Axes.set_prop_cycle`
# which will only set the ``prop_cycle`` for this :mod:`matplotlib.axes.Axes`
# instance. We'll use a second ``cycler`` that combines a color cycler and a
# linewidth cycler.
custom_cycler = (cycler(color=['c', 'm', 'y', 'k']) +
cycler(lw=[1, 2, 3, 4]))
fig, (ax0, ax1) = plt.subplots(nrows=2)
ax0.plot(yy)
ax0.set_title('Set default color cycle to rgby')
ax1.set_prop_cycle(custom_cycler)
ax1.plot(yy)
ax1.set_title('Set axes color cycle to cmyk')
# Add a bit more space between the two plots.
fig.subplots_adjust(hspace=0.3)
plt.show()
###############################################################################
# Setting ``prop_cycler`` in the ``matplotlibrc`` file or style files
# -------------------------------------------------------------------
#
# Remember, if you want to set a custom ``prop_cycler`` in your
# ``.matplotlibrc`` file or a style file (``style.mplstyle``), you can set the
# ``axes.prop_cycle`` property:
#
# .. code-block:: python
#
# axes.prop_cycle : cycler(color='bgrcmyk')
#
# Cycling through multiple properties
# -----------------------------------
#
# You can add cyclers:
#
# .. code-block:: python
#
# from cycler import cycler
# cc = (cycler(color=list('rgb')) +
# cycler(linestyle=['-', '--', '-.']))
# for d in cc:
# print(d)
#
# Results in:
#
# .. code-block:: python
#
# {'color': 'r', 'linestyle': '-'}
# {'color': 'g', 'linestyle': '--'}
# {'color': 'b', 'linestyle': '-.'}
#
#
# You can multiply cyclers:
#
# .. code-block:: python
#
# from cycler import cycler
# cc = (cycler(color=list('rgb')) *
# cycler(linestyle=['-', '--', '-.']))
# for d in cc:
# print(d)
#
# Results in:
#
# .. code-block:: python
#
# {'color': 'r', 'linestyle': '-'}
# {'color': 'r', 'linestyle': '--'}
# {'color': 'r', 'linestyle': '-.'}
# {'color': 'g', 'linestyle': '-'}
# {'color': 'g', 'linestyle': '--'}
# {'color': 'g', 'linestyle': '-.'}
# {'color': 'b', 'linestyle': '-'}
# {'color': 'b', 'linestyle': '--'}
# {'color': 'b', 'linestyle': '-.'}
|
02f486f13d85a052cf6c7abbf06eee3b8bc5ed389734c508da6cba0a1d7a7bc8
|
"""
*origin* and *extent* in `~.Axes.imshow`
========================================
:meth:`~.Axes.imshow` allows you to render an image (either a 2D array
which will be color-mapped (based on *norm* and *cmap*) or and 3D RGB(A)
array which will be used as-is) to a rectangular region in dataspace.
The orientation of the image in the final rendering is controlled by
the *origin* and *extent* kwargs (and attributes on the resulting
`~.AxesImage` instance) and the data limits of the axes.
The *extent* kwarg controls the bounding box in data coordinates that
the image will fill specified as ``(left, right, bottom, top)`` in
**data coordinates**, the *origin* kwarg controls how the image fills
that bounding box, and the orientation in the final rendered image is
also affected by the axes limits.
.. hint:: Most of the code below is used for adding labels and informative
text to the plots. The described effects of *origin* and *extent* can be
seen in the plots without the need to follow all code details.
For a quick understanding, you may want to skip the code details below and
directly continue with the discussion of the results.
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
def index_to_coordinate(index, extent, origin):
"""Return the pixel center of an index."""
left, right, bottom, top = extent
hshift = 0.5 * np.sign(right - left)
left, right = left + hshift, right - hshift
vshift = 0.5 * np.sign(top - bottom)
bottom, top = bottom + vshift, top - vshift
if origin == 'upper':
bottom, top = top, bottom
return {
"[0, 0]": (left, bottom),
"[M', 0]": (left, top),
"[0, N']": (right, bottom),
"[M', N']": (right, top),
}[index]
def get_index_label_pos(index, extent, origin, inverted_xindex):
"""
Return the desired position and horizontal alignment of an index label.
"""
if extent is None:
extent = lookup_extent(origin)
left, right, bottom, top = extent
x, y = index_to_coordinate(index, extent, origin)
is_x0 = index[-2:] == "0]"
halign = 'left' if is_x0 ^ inverted_xindex else 'right'
hshift = 0.5 * np.sign(left - right)
x += hshift * (1 if is_x0 else -1)
return x, y, halign
def get_color(index, data, cmap):
"""Return the data color of an index."""
val = {
"[0, 0]": data[0, 0],
"[0, N']": data[0, -1],
"[M', 0]": data[-1, 0],
"[M', N']": data[-1, -1],
}[index]
return cmap(val / data.max())
def lookup_extent(origin):
"""Return extent for label positioning when not given explicitly."""
if origin == 'lower':
return (-0.5, 6.5, -0.5, 5.5)
else:
return (-0.5, 6.5, 5.5, -0.5)
def set_extent_None_text(ax):
ax.text(3, 2.5, 'equals\nextent=None', size='large',
ha='center', va='center', color='w')
def plot_imshow_with_labels(ax, data, extent, origin, xlim, ylim):
"""Actually run ``imshow()`` and add extent and index labels."""
im = ax.imshow(data, origin=origin, extent=extent)
# extent labels (left, right, bottom, top)
left, right, bottom, top = im.get_extent()
if xlim is None or top > bottom:
upper_string, lower_string = 'top', 'bottom'
else:
upper_string, lower_string = 'bottom', 'top'
if ylim is None or left < right:
port_string, starboard_string = 'left', 'right'
inverted_xindex = False
else:
port_string, starboard_string = 'right', 'left'
inverted_xindex = True
bbox_kwargs = {'fc': 'w', 'alpha': .75, 'boxstyle': "round4"}
ann_kwargs = {'xycoords': 'axes fraction',
'textcoords': 'offset points',
'bbox': bbox_kwargs}
ax.annotate(upper_string, xy=(.5, 1), xytext=(0, -1),
ha='center', va='top', **ann_kwargs)
ax.annotate(lower_string, xy=(.5, 0), xytext=(0, 1),
ha='center', va='bottom', **ann_kwargs)
ax.annotate(port_string, xy=(0, .5), xytext=(1, 0),
ha='left', va='center', rotation=90,
**ann_kwargs)
ax.annotate(starboard_string, xy=(1, .5), xytext=(-1, 0),
ha='right', va='center', rotation=-90,
**ann_kwargs)
ax.set_title('origin: {origin}'.format(origin=origin))
# index labels
for index in ["[0, 0]", "[0, N']", "[M', 0]", "[M', N']"]:
tx, ty, halign = get_index_label_pos(index, extent, origin,
inverted_xindex)
facecolor = get_color(index, data, im.get_cmap())
ax.text(tx, ty, index, color='white', ha=halign, va='center',
bbox={'boxstyle': 'square', 'facecolor': facecolor})
if xlim:
ax.set_xlim(*xlim)
if ylim:
ax.set_ylim(*ylim)
def generate_imshow_demo_grid(extents, xlim=None, ylim=None):
N = len(extents)
fig = plt.figure(tight_layout=True)
fig.set_size_inches(6, N * (11.25) / 5)
gs = GridSpec(N, 5, figure=fig)
columns = {'label': [fig.add_subplot(gs[j, 0]) for j in range(N)],
'upper': [fig.add_subplot(gs[j, 1:3]) for j in range(N)],
'lower': [fig.add_subplot(gs[j, 3:5]) for j in range(N)]}
x, y = np.ogrid[0:6, 0:7]
data = x + y
for origin in ['upper', 'lower']:
for ax, extent in zip(columns[origin], extents):
plot_imshow_with_labels(ax, data, extent, origin, xlim, ylim)
for ax, extent in zip(columns['label'], extents):
text_kwargs = {'ha': 'right',
'va': 'center',
'xycoords': 'axes fraction',
'xy': (1, .5)}
if extent is None:
ax.annotate('None', **text_kwargs)
ax.set_title('extent=')
else:
left, right, bottom, top = extent
text = ('left: {left:0.1f}\nright: {right:0.1f}\n' +
'bottom: {bottom:0.1f}\ntop: {top:0.1f}\n').format(
left=left, right=right, bottom=bottom, top=top)
ax.annotate(text, **text_kwargs)
ax.axis('off')
return columns
###############################################################################
#
# Default extent
# --------------
#
# First, let's have a look at the default `extent=None`
generate_imshow_demo_grid(extents=[None])
###############################################################################
#
# Generally, for an array of shape (M, N), the first index runs along the
# vertical, the second index runs along the horizontal.
# The pixel centers are at integer positions ranging from 0 to ``N' = N - 1``
# horizontally and from 0 to ``M' = M - 1`` vertically.
# *origin* determines how to the data is filled in the bounding box.
#
# For ``origin='lower'``:
#
# - [0, 0] is at (left, bottom)
# - [M', 0] is at (left, top)
# - [0, N'] is at (right, bottom)
# - [M', N'] is at (right, top)
#
# ``origin='upper'`` reverses the vertical axes direction and filling:
#
# - [0, 0] is at (left, top)
# - [M', 0] is at (left, bottom)
# - [0, N'] is at (right, top)
# - [M', N'] is at (right, bottom)
#
# In summary, the position of the [0, 0] index as well as the extent are
# influenced by *origin*:
#
# ====== =============== ==========================================
# origin [0, 0] position extent
# ====== =============== ==========================================
# upper top left ``(-0.5, numcols-0.5, numrows-0.5, -0.5)``
# lower bottom left ``(-0.5, numcols-0.5, -0.5, numrows-0.5)``
# ====== =============== ==========================================
#
# The default value of *origin* is set by :rc:`image.origin` which defaults
# to ``'upper'`` to match the matrix indexing conventions in math and
# computer graphics image indexing conventions.
#
#
# Explicit extent
# ---------------
#
# By setting *extent* we define the coordinates of the image area. The
# underlying image data is interpolated/resampled to fill that area.
#
# If the axes is set to autoscale, then the view limits of the axes are set
# to match the *extent* which ensures that the coordinate set by
# ``(left, bottom)`` is at the bottom left of the axes! However, this
# may invert the axis so they do not increase in the 'natural' direction.
#
extents = [(-0.5, 6.5, -0.5, 5.5),
(-0.5, 6.5, 5.5, -0.5),
(6.5, -0.5, -0.5, 5.5),
(6.5, -0.5, 5.5, -0.5)]
columns = generate_imshow_demo_grid(extents)
set_extent_None_text(columns['upper'][1])
set_extent_None_text(columns['lower'][0])
###############################################################################
#
# Explicit extent and axes limits
# -------------------------------
#
# If we fix the axes limits by explicitly setting `set_xlim` / `set_ylim`, we
# force a certain size and orientation of the axes.
# This can decouple the 'left-right' and 'top-bottom' sense of the image from
# the orientation on the screen.
#
# In the example below we have chosen the limits slightly larger than the
# extent (note the white areas within the Axes).
#
# While we keep the extents as in the examples before, the coordinate (0, 0)
# is now explicitly put at the bottom left and values increase to up and to
# the right (from the viewer point of view).
# We can see that:
#
# - The coordinate ``(left, bottom)`` anchors the image which then fills the
# box going towards the ``(right, top)`` point in data space.
# - The first column is always closest to the 'left'.
# - *origin* controls if the first row is closest to 'top' or 'bottom'.
# - The image may be inverted along either direction.
# - The 'left-right' and 'top-bottom' sense of the image may be uncoupled from
# the orientation on the screen.
generate_imshow_demo_grid(extents=[None] + extents,
xlim=(-2, 8), ylim=(-1, 6))
|
657dddf4f5a2b4b180e187bc2a5e9d31805e2f57f957ee5006a50d17ad72eb1e
|
"""
==================
Tight Layout guide
==================
How to use tight-layout to fit plots within your figure cleanly.
*tight_layout* automatically adjusts subplot params so that the
subplot(s) fits in to the figure area. This is an experimental
feature and may not work for some cases. It only checks the extents
of ticklabels, axis labels, and titles.
An alternative to *tight_layout* is :doc:`constrained_layout
</tutorials/intermediate/constrainedlayout_guide>`.
Simple Example
==============
In matplotlib, the location of axes (including subplots) are specified in
normalized figure coordinates. It can happen that your axis labels or
titles (or sometimes even ticklabels) go outside the figure area, and are thus
clipped.
"""
# sphinx_gallery_thumbnail_number = 7
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['savefig.facecolor'] = "0.8"
def example_plot(ax, fontsize=12):
ax.plot([1, 2])
ax.locator_params(nbins=3)
ax.set_xlabel('x-label', fontsize=fontsize)
ax.set_ylabel('y-label', fontsize=fontsize)
ax.set_title('Title', fontsize=fontsize)
plt.close('all')
fig, ax = plt.subplots()
example_plot(ax, fontsize=24)
###############################################################################
# To prevent this, the location of axes needs to be adjusted. For
# subplots, this can be done by adjusting the subplot params
# (:ref:`howto-subplots-adjust`). Matplotlib v1.1 introduces a new
# command :func:`~matplotlib.pyplot.tight_layout` that does this
# automatically for you.
fig, ax = plt.subplots()
example_plot(ax, fontsize=24)
plt.tight_layout()
###############################################################################
# Note that :func:`matplotlib.pyplot.tight_layout` will only adjust the
# subplot params when it is called. In order to perform this adjustment each
# time the figure is redrawn, you can call ``fig.set_tight_layout(True)``, or,
# equivalently, set the ``figure.autolayout`` rcParam to ``True``.
#
# When you have multiple subplots, often you see labels of different
# axes overlapping each other.
plt.close('all')
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2)
example_plot(ax1)
example_plot(ax2)
example_plot(ax3)
example_plot(ax4)
###############################################################################
# :func:`~matplotlib.pyplot.tight_layout` will also adjust spacing between
# subplots to minimize the overlaps.
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2)
example_plot(ax1)
example_plot(ax2)
example_plot(ax3)
example_plot(ax4)
plt.tight_layout()
###############################################################################
# :func:`~matplotlib.pyplot.tight_layout` can take keyword arguments of
# *pad*, *w_pad* and *h_pad*. These control the extra padding around the
# figure border and between subplots. The pads are specified in fraction
# of fontsize.
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2)
example_plot(ax1)
example_plot(ax2)
example_plot(ax3)
example_plot(ax4)
plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0)
###############################################################################
# :func:`~matplotlib.pyplot.tight_layout` will work even if the sizes of
# subplots are different as far as their grid specification is
# compatible. In the example below, *ax1* and *ax2* are subplots of a 2x2
# grid, while *ax3* is of a 1x2 grid.
plt.close('all')
fig = plt.figure()
ax1 = plt.subplot(221)
ax2 = plt.subplot(223)
ax3 = plt.subplot(122)
example_plot(ax1)
example_plot(ax2)
example_plot(ax3)
plt.tight_layout()
###############################################################################
# It works with subplots created with
# :func:`~matplotlib.pyplot.subplot2grid`. In general, subplots created
# from the gridspec (:doc:`/tutorials/intermediate/gridspec`) will work.
plt.close('all')
fig = plt.figure()
ax1 = plt.subplot2grid((3, 3), (0, 0))
ax2 = plt.subplot2grid((3, 3), (0, 1), colspan=2)
ax3 = plt.subplot2grid((3, 3), (1, 0), colspan=2, rowspan=2)
ax4 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)
example_plot(ax1)
example_plot(ax2)
example_plot(ax3)
example_plot(ax4)
plt.tight_layout()
###############################################################################
# Although not thoroughly tested, it seems to work for subplots with
# aspect != "auto" (e.g., axes with images).
arr = np.arange(100).reshape((10, 10))
plt.close('all')
fig = plt.figure(figsize=(5, 4))
ax = plt.subplot(111)
im = ax.imshow(arr, interpolation="none")
plt.tight_layout()
###############################################################################
# Caveats
# =======
#
# * :func:`~matplotlib.pyplot.tight_layout` only considers ticklabels, axis
# labels, and titles. Thus, other artists may be clipped and also may
# overlap.
#
# * It assumes that the extra space needed for ticklabels, axis labels,
# and titles is independent of original location of axes. This is
# often true, but there are rare cases where it is not.
#
# * pad=0 clips some of the texts by a few pixels. This may be a bug or
# a limitation of the current algorithm and it is not clear why it
# happens. Meanwhile, use of pad at least larger than 0.3 is
# recommended.
#
# Use with GridSpec
# =================
#
# GridSpec has its own :func:`~matplotlib.gridspec.GridSpec.tight_layout` method
# (the pyplot api :func:`~matplotlib.pyplot.tight_layout` also works).
import matplotlib.gridspec as gridspec
plt.close('all')
fig = plt.figure()
gs1 = gridspec.GridSpec(2, 1)
ax1 = fig.add_subplot(gs1[0])
ax2 = fig.add_subplot(gs1[1])
example_plot(ax1)
example_plot(ax2)
gs1.tight_layout(fig)
###############################################################################
# You may provide an optional *rect* parameter, which specifies the bounding box
# that the subplots will be fit inside. The coordinates must be in normalized
# figure coordinates and the default is (0, 0, 1, 1).
fig = plt.figure()
gs1 = gridspec.GridSpec(2, 1)
ax1 = fig.add_subplot(gs1[0])
ax2 = fig.add_subplot(gs1[1])
example_plot(ax1)
example_plot(ax2)
gs1.tight_layout(fig, rect=[0, 0, 0.5, 1])
###############################################################################
# For example, this can be used for a figure with multiple gridspecs.
fig = plt.figure()
gs1 = gridspec.GridSpec(2, 1)
ax1 = fig.add_subplot(gs1[0])
ax2 = fig.add_subplot(gs1[1])
example_plot(ax1)
example_plot(ax2)
gs1.tight_layout(fig, rect=[0, 0, 0.5, 1])
gs2 = gridspec.GridSpec(3, 1)
for ss in gs2:
ax = fig.add_subplot(ss)
example_plot(ax)
ax.set_title("")
ax.set_xlabel("")
ax.set_xlabel("x-label", fontsize=12)
gs2.tight_layout(fig, rect=[0.5, 0, 1, 1], h_pad=0.5)
# We may try to match the top and bottom of two grids ::
top = min(gs1.top, gs2.top)
bottom = max(gs1.bottom, gs2.bottom)
gs1.update(top=top, bottom=bottom)
gs2.update(top=top, bottom=bottom)
plt.show()
###############################################################################
# While this should be mostly good enough, adjusting top and bottom
# may require adjustment of hspace also. To update hspace & vspace, we
# call :func:`~matplotlib.gridspec.GridSpec.tight_layout` again with updated
# rect argument. Note that the rect argument specifies the area including the
# ticklabels, etc. Thus, we will increase the bottom (which is 0 for the normal
# case) by the difference between the *bottom* from above and the bottom of each
# gridspec. Same thing for the top.
fig = plt.gcf()
gs1 = gridspec.GridSpec(2, 1)
ax1 = fig.add_subplot(gs1[0])
ax2 = fig.add_subplot(gs1[1])
example_plot(ax1)
example_plot(ax2)
gs1.tight_layout(fig, rect=[0, 0, 0.5, 1])
gs2 = gridspec.GridSpec(3, 1)
for ss in gs2:
ax = fig.add_subplot(ss)
example_plot(ax)
ax.set_title("")
ax.set_xlabel("")
ax.set_xlabel("x-label", fontsize=12)
gs2.tight_layout(fig, rect=[0.5, 0, 1, 1], h_pad=0.5)
top = min(gs1.top, gs2.top)
bottom = max(gs1.bottom, gs2.bottom)
gs1.update(top=top, bottom=bottom)
gs2.update(top=top, bottom=bottom)
top = min(gs1.top, gs2.top)
bottom = max(gs1.bottom, gs2.bottom)
gs1.tight_layout(fig, rect=[None, 0 + (bottom-gs1.bottom),
0.5, 1 - (gs1.top-top)])
gs2.tight_layout(fig, rect=[0.5, 0 + (bottom-gs2.bottom),
None, 1 - (gs2.top-top)],
h_pad=0.5)
###############################################################################
# Legends and Annotations
# =======================
#
# Pre Matplotlib 2.2, legends and annotations were excluded from the bounding
# box calculations that decide the layout. Subsequently these artists were
# added to the calculation, but sometimes it is undesirable to include them.
# For instance in this case it might be good to have the axes shring a bit
# to make room for the legend:
fig, ax = plt.subplots(figsize=(4, 3))
lines = ax.plot(range(10), label='A simple plot')
ax.legend(bbox_to_anchor=(0.7, 0.5), loc='center left',)
fig.tight_layout()
plt.show()
###############################################################################
# However, sometimes this is not desired (quite often when using
# ``fig.savefig('outname.png', bbox_inches='tight')``). In order to
# remove the legend from the bounding box calculation, we simply set its
# bounding ``leg.set_in_layout(False)`` and the legend will be ignored.
fig, ax = plt.subplots(figsize=(4, 3))
lines = ax.plot(range(10), label='B simple plot')
leg = ax.legend(bbox_to_anchor=(0.7, 0.5), loc='center left',)
leg.set_in_layout(False)
fig.tight_layout()
plt.show()
###############################################################################
# Use with AxesGrid1
# ==================
#
# While limited, the axes_grid1 toolkit is also supported.
from mpl_toolkits.axes_grid1 import Grid
plt.close('all')
fig = plt.figure()
grid = Grid(fig, rect=111, nrows_ncols=(2, 2),
axes_pad=0.25, label_mode='L',
)
for ax in grid:
example_plot(ax)
ax.title.set_visible(False)
plt.tight_layout()
###############################################################################
# Colorbar
# ========
#
# If you create a colorbar with the :func:`~matplotlib.pyplot.colorbar`
# command, the created colorbar is an instance of Axes, *not* Subplot, so
# tight_layout does not work. With Matplotlib v1.1, you may create a
# colorbar as a subplot using the gridspec.
plt.close('all')
arr = np.arange(100).reshape((10, 10))
fig = plt.figure(figsize=(4, 4))
im = plt.imshow(arr, interpolation="none")
plt.colorbar(im, use_gridspec=True)
plt.tight_layout()
###############################################################################
# Another option is to use AxesGrid1 toolkit to
# explicitly create an axes for colorbar.
from mpl_toolkits.axes_grid1 import make_axes_locatable
plt.close('all')
arr = np.arange(100).reshape((10, 10))
fig = plt.figure(figsize=(4, 4))
im = plt.imshow(arr, interpolation="none")
divider = make_axes_locatable(plt.gca())
cax = divider.append_axes("right", "5%", pad="3%")
plt.colorbar(im, cax=cax)
plt.tight_layout()
|
6415694ebd1f803d787c1f72357ec04a87ebf413133927326e7f5d92058e42aa
|
import numpy as np
import matplotlib
from matplotlib import cbook, docstring, rcParams
from matplotlib.artist import allow_rasterization
import matplotlib.transforms as mtransforms
import matplotlib.patches as mpatches
import matplotlib.path as mpath
class Spine(mpatches.Patch):
"""an axis spine -- the line noting the data area boundaries
Spines are the lines connecting the axis tick marks and noting the
boundaries of the data area. They can be placed at arbitrary
positions. See function:`~matplotlib.spines.Spine.set_position`
for more information.
The default position is ``('outward',0)``.
Spines are subclasses of class:`~matplotlib.patches.Patch`, and
inherit much of their behavior.
Spines draw a line, a circle, or an arc depending if
function:`~matplotlib.spines.Spine.set_patch_line`,
function:`~matplotlib.spines.Spine.set_patch_circle`, or
function:`~matplotlib.spines.Spine.set_patch_arc` has been called.
Line-like is the default.
"""
def __str__(self):
return "Spine"
@docstring.dedent_interpd
def __init__(self, axes, spine_type, path, **kwargs):
"""
- *axes* : the Axes instance containing the spine
- *spine_type* : a string specifying the spine type
- *path* : the path instance used to draw the spine
Valid kwargs are:
%(Patch)s
"""
super().__init__(**kwargs)
self.axes = axes
self.set_figure(self.axes.figure)
self.spine_type = spine_type
self.set_facecolor('none')
self.set_edgecolor(rcParams['axes.edgecolor'])
self.set_linewidth(rcParams['axes.linewidth'])
self.set_capstyle('projecting')
self.axis = None
self.set_zorder(2.5)
self.set_transform(self.axes.transData) # default transform
self._bounds = None # default bounds
self._smart_bounds = False
# Defer initial position determination. (Not much support for
# non-rectangular axes is currently implemented, and this lets
# them pass through the spines machinery without errors.)
self._position = None
if not isinstance(path, matplotlib.path.Path):
raise ValueError(
"'path' must be an instance of 'matplotlib.path.Path'")
self._path = path
# To support drawing both linear and circular spines, this
# class implements Patch behavior three ways. If
# self._patch_type == 'line', behave like a mpatches.PathPatch
# instance. If self._patch_type == 'circle', behave like a
# mpatches.Ellipse instance. If self._patch_type == 'arc', behave like
# a mpatches.Arc instance.
self._patch_type = 'line'
# Behavior copied from mpatches.Ellipse:
# Note: This cannot be calculated until this is added to an Axes
self._patch_transform = mtransforms.IdentityTransform()
def set_smart_bounds(self, value):
"""set the spine and associated axis to have smart bounds"""
self._smart_bounds = value
# also set the axis if possible
if self.spine_type in ('left', 'right'):
self.axes.yaxis.set_smart_bounds(value)
elif self.spine_type in ('top', 'bottom'):
self.axes.xaxis.set_smart_bounds(value)
self.stale = True
def get_smart_bounds(self):
"""get whether the spine has smart bounds"""
return self._smart_bounds
def set_patch_arc(self, center, radius, theta1, theta2):
"""set the spine to be arc-like"""
self._patch_type = 'arc'
self._center = center
self._width = radius * 2
self._height = radius * 2
self._theta1 = theta1
self._theta2 = theta2
self._path = mpath.Path.arc(theta1, theta2)
# arc drawn on axes transform
self.set_transform(self.axes.transAxes)
self.stale = True
def set_patch_circle(self, center, radius):
"""set the spine to be circular"""
self._patch_type = 'circle'
self._center = center
self._width = radius * 2
self._height = radius * 2
# circle drawn on axes transform
self.set_transform(self.axes.transAxes)
self.stale = True
def set_patch_line(self):
"""set the spine to be linear"""
self._patch_type = 'line'
self.stale = True
# Behavior copied from mpatches.Ellipse:
def _recompute_transform(self):
"""NOTE: This cannot be called until after this has been added
to an Axes, otherwise unit conversion will fail. This
makes it very important to call the accessor method and
not directly access the transformation member variable.
"""
assert self._patch_type in ('arc', 'circle')
center = (self.convert_xunits(self._center[0]),
self.convert_yunits(self._center[1]))
width = self.convert_xunits(self._width)
height = self.convert_yunits(self._height)
self._patch_transform = mtransforms.Affine2D() \
.scale(width * 0.5, height * 0.5) \
.translate(*center)
def get_patch_transform(self):
if self._patch_type in ('arc', 'circle'):
self._recompute_transform()
return self._patch_transform
else:
return super().get_patch_transform()
def get_window_extent(self, renderer=None):
"""
Return the window extent of the spines in display space, including
padding for ticks (but not their labels)
See Also
--------
matplotlib.axes.Axes.get_tightbbox
matplotlib.axes.Axes.get_window_extent
"""
# make sure the location is updated so that transforms etc are
# correct:
self._adjust_location()
bb = super().get_window_extent(renderer=renderer)
if self.axis is None:
return bb
bboxes = [bb]
tickstocheck = [self.axis.majorTicks[0]]
if len(self.axis.minorTicks) > 1:
# only pad for minor ticks if there are more than one
# of them. There is always one...
tickstocheck.append(self.axis.minorTicks[1])
for tick in tickstocheck:
bb0 = bb.frozen()
tickl = tick._size
tickdir = tick._tickdir
if tickdir == 'out':
padout = 1
padin = 0
elif tickdir == 'in':
padout = 0
padin = 1
else:
padout = 0.5
padin = 0.5
padout = padout * tickl / 72 * self.figure.dpi
padin = padin * tickl / 72 * self.figure.dpi
if tick.tick1line.get_visible():
if self.spine_type in ['left']:
bb0.x0 = bb0.x0 - padout
bb0.x1 = bb0.x1 + padin
elif self.spine_type in ['bottom']:
bb0.y0 = bb0.y0 - padout
bb0.y1 = bb0.y1 + padin
if tick.tick2line.get_visible():
if self.spine_type in ['right']:
bb0.x1 = bb0.x1 + padout
bb0.x0 = bb0.x0 - padin
elif self.spine_type in ['top']:
bb0.y1 = bb0.y1 + padout
bb0.y0 = bb0.y0 - padout
bboxes.append(bb0)
return mtransforms.Bbox.union(bboxes)
def get_path(self):
return self._path
def _ensure_position_is_set(self):
if self._position is None:
# default position
self._position = ('outward', 0.0) # in points
self.set_position(self._position)
def register_axis(self, axis):
"""register an axis
An axis should be registered with its corresponding spine from
the Axes instance. This allows the spine to clear any axis
properties when needed.
"""
self.axis = axis
if self.axis is not None:
self.axis.cla()
self.stale = True
def cla(self):
"""Clear the current spine"""
self._position = None # clear position
if self.axis is not None:
self.axis.cla()
@cbook.deprecated("3.1")
def is_frame_like(self):
"""return True if directly on axes frame
This is useful for determining if a spine is the edge of an
old style MPL plot. If so, this function will return True.
"""
self._ensure_position_is_set()
position = self._position
if isinstance(position, str):
if position == 'center':
position = ('axes', 0.5)
elif position == 'zero':
position = ('data', 0)
if len(position) != 2:
raise ValueError("position should be 2-tuple")
position_type, amount = position
if position_type == 'outward' and amount == 0:
return True
else:
return False
def _adjust_location(self):
"""automatically set spine bounds to the view interval"""
if self.spine_type == 'circle':
return
if self._bounds is None:
if self.spine_type in ('left', 'right'):
low, high = self.axes.viewLim.intervaly
elif self.spine_type in ('top', 'bottom'):
low, high = self.axes.viewLim.intervalx
else:
raise ValueError('unknown spine spine_type: %s' %
self.spine_type)
if self._smart_bounds:
# attempt to set bounds in sophisticated way
# handle inverted limits
viewlim_low, viewlim_high = sorted([low, high])
if self.spine_type in ('left', 'right'):
datalim_low, datalim_high = self.axes.dataLim.intervaly
ticks = self.axes.get_yticks()
elif self.spine_type in ('top', 'bottom'):
datalim_low, datalim_high = self.axes.dataLim.intervalx
ticks = self.axes.get_xticks()
# handle inverted limits
ticks = np.sort(ticks)
datalim_low, datalim_high = sorted([datalim_low, datalim_high])
if datalim_low < viewlim_low:
# Data extends past view. Clip line to view.
low = viewlim_low
else:
# Data ends before view ends.
cond = (ticks <= datalim_low) & (ticks >= viewlim_low)
tickvals = ticks[cond]
if len(tickvals):
# A tick is less than or equal to lowest data point.
low = tickvals[-1]
else:
# No tick is available
low = datalim_low
low = max(low, viewlim_low)
if datalim_high > viewlim_high:
# Data extends past view. Clip line to view.
high = viewlim_high
else:
# Data ends before view ends.
cond = (ticks >= datalim_high) & (ticks <= viewlim_high)
tickvals = ticks[cond]
if len(tickvals):
# A tick is greater than or equal to highest data
# point.
high = tickvals[0]
else:
# No tick is available
high = datalim_high
high = min(high, viewlim_high)
else:
low, high = self._bounds
if self._patch_type == 'arc':
if self.spine_type in ('bottom', 'top'):
try:
direction = self.axes.get_theta_direction()
except AttributeError:
direction = 1
try:
offset = self.axes.get_theta_offset()
except AttributeError:
offset = 0
low = low * direction + offset
high = high * direction + offset
if low > high:
low, high = high, low
self._path = mpath.Path.arc(np.rad2deg(low), np.rad2deg(high))
if self.spine_type == 'bottom':
rmin, rmax = self.axes.viewLim.intervaly
try:
rorigin = self.axes.get_rorigin()
except AttributeError:
rorigin = rmin
scaled_diameter = (rmin - rorigin) / (rmax - rorigin)
self._height = scaled_diameter
self._width = scaled_diameter
else:
raise ValueError('unable to set bounds for spine "%s"' %
self.spine_type)
else:
v1 = self._path.vertices
assert v1.shape == (2, 2), 'unexpected vertices shape'
if self.spine_type in ['left', 'right']:
v1[0, 1] = low
v1[1, 1] = high
elif self.spine_type in ['bottom', 'top']:
v1[0, 0] = low
v1[1, 0] = high
else:
raise ValueError('unable to set bounds for spine "%s"' %
self.spine_type)
@allow_rasterization
def draw(self, renderer):
self._adjust_location()
ret = super().draw(renderer)
self.stale = False
return ret
def _calc_offset_transform(self):
"""calculate the offset transform performed by the spine"""
self._ensure_position_is_set()
position = self._position
if isinstance(position, str):
if position == 'center':
position = ('axes', 0.5)
elif position == 'zero':
position = ('data', 0)
assert len(position) == 2, "position should be 2-tuple"
position_type, amount = position
assert position_type in ('axes', 'outward', 'data')
if position_type == 'outward':
if amount == 0:
# short circuit commonest case
self._spine_transform = ('identity',
mtransforms.IdentityTransform())
elif self.spine_type in ['left', 'right', 'top', 'bottom']:
offset_vec = {'left': (-1, 0),
'right': (1, 0),
'bottom': (0, -1),
'top': (0, 1),
}[self.spine_type]
# calculate x and y offset in dots
offset_x = amount * offset_vec[0] / 72.0
offset_y = amount * offset_vec[1] / 72.0
self._spine_transform = ('post',
mtransforms.ScaledTranslation(
offset_x,
offset_y,
self.figure.dpi_scale_trans))
else:
cbook._warn_external('unknown spine type "%s": no spine '
'offset performed' % self.spine_type)
self._spine_transform = ('identity',
mtransforms.IdentityTransform())
elif position_type == 'axes':
if self.spine_type in ('left', 'right'):
self._spine_transform = ('pre',
mtransforms.Affine2D.from_values(
# keep y unchanged, fix x at
# amount
0, 0, 0, 1, amount, 0))
elif self.spine_type in ('bottom', 'top'):
self._spine_transform = ('pre',
mtransforms.Affine2D.from_values(
# keep x unchanged, fix y at
# amount
1, 0, 0, 0, 0, amount))
else:
cbook._warn_external('unknown spine type "%s": no spine '
'offset performed' % self.spine_type)
self._spine_transform = ('identity',
mtransforms.IdentityTransform())
elif position_type == 'data':
if self.spine_type in ('right', 'top'):
# The right and top spines have a default position of 1 in
# axes coordinates. When specifying the position in data
# coordinates, we need to calculate the position relative to 0.
amount -= 1
if self.spine_type in ('left', 'right'):
self._spine_transform = ('data',
mtransforms.Affine2D().translate(
amount, 0))
elif self.spine_type in ('bottom', 'top'):
self._spine_transform = ('data',
mtransforms.Affine2D().translate(
0, amount))
else:
cbook._warn_external('unknown spine type "%s": no spine '
'offset performed' % self.spine_type)
self._spine_transform = ('identity',
mtransforms.IdentityTransform())
def set_position(self, position):
"""set the position of the spine
Spine position is specified by a 2 tuple of (position type,
amount). The position types are:
* 'outward' : place the spine out from the data area by the
specified number of points. (Negative values specify placing the
spine inward.)
* 'axes' : place the spine at the specified Axes coordinate (from
0.0-1.0).
* 'data' : place the spine at the specified data coordinate.
Additionally, shorthand notations define a special positions:
* 'center' -> ('axes',0.5)
* 'zero' -> ('data', 0.0)
"""
if position in ('center', 'zero'):
# special positions
pass
else:
if len(position) != 2:
raise ValueError("position should be 'center' or 2-tuple")
if position[0] not in ['outward', 'axes', 'data']:
raise ValueError("position[0] should be one of 'outward', "
"'axes', or 'data' ")
self._position = position
self._calc_offset_transform()
self.set_transform(self.get_spine_transform())
if self.axis is not None:
self.axis.reset_ticks()
self.stale = True
def get_position(self):
"""get the spine position"""
self._ensure_position_is_set()
return self._position
def get_spine_transform(self):
"""get the spine transform"""
self._ensure_position_is_set()
what, how = self._spine_transform
if what == 'data':
# special case data based spine locations
data_xform = self.axes.transScale + \
(how + self.axes.transLimits + self.axes.transAxes)
if self.spine_type in ['left', 'right']:
result = mtransforms.blended_transform_factory(
data_xform, self.axes.transData)
elif self.spine_type in ['top', 'bottom']:
result = mtransforms.blended_transform_factory(
self.axes.transData, data_xform)
else:
raise ValueError('unknown spine spine_type: %s' %
self.spine_type)
return result
if self.spine_type in ['left', 'right']:
base_transform = self.axes.get_yaxis_transform(which='grid')
elif self.spine_type in ['top', 'bottom']:
base_transform = self.axes.get_xaxis_transform(which='grid')
else:
raise ValueError('unknown spine spine_type: %s' %
self.spine_type)
if what == 'identity':
return base_transform
elif what == 'post':
return base_transform + how
elif what == 'pre':
return how + base_transform
else:
raise ValueError("unknown spine_transform type: %s" % what)
def set_bounds(self, low, high):
"""Set the bounds of the spine."""
if self.spine_type == 'circle':
raise ValueError(
'set_bounds() method incompatible with circular spines')
self._bounds = (low, high)
self.stale = True
def get_bounds(self):
"""Get the bounds of the spine."""
return self._bounds
@classmethod
def linear_spine(cls, axes, spine_type, **kwargs):
"""
Returns a linear `Spine`.
"""
# all values of 0.999 get replaced upon call to set_bounds()
if spine_type == 'left':
path = mpath.Path([(0.0, 0.999), (0.0, 0.999)])
elif spine_type == 'right':
path = mpath.Path([(1.0, 0.999), (1.0, 0.999)])
elif spine_type == 'bottom':
path = mpath.Path([(0.999, 0.0), (0.999, 0.0)])
elif spine_type == 'top':
path = mpath.Path([(0.999, 1.0), (0.999, 1.0)])
else:
raise ValueError('unable to make path for spine "%s"' % spine_type)
result = cls(axes, spine_type, path, **kwargs)
result.set_visible(rcParams['axes.spines.{0}'.format(spine_type)])
return result
@classmethod
def arc_spine(cls, axes, spine_type, center, radius, theta1, theta2,
**kwargs):
"""
Returns an arc `Spine`.
"""
path = mpath.Path.arc(theta1, theta2)
result = cls(axes, spine_type, path, **kwargs)
result.set_patch_arc(center, radius, theta1, theta2)
return result
@classmethod
def circular_spine(cls, axes, center, radius, **kwargs):
"""
Returns a circular `Spine`.
"""
path = mpath.Path.unit_circle()
spine_type = 'circle'
result = cls(axes, spine_type, path, **kwargs)
result.set_patch_circle(center, radius)
return result
def set_color(self, c):
"""
Set the edgecolor.
Parameters
----------
c : color
Notes
-----
This method does not modify the facecolor (which defaults to "none"),
unlike the `Patch.set_color` method defined in the parent class. Use
`Patch.set_facecolor` to set the facecolor.
"""
self.set_edgecolor(c)
self.stale = True
|
4177b869394ea04d1da61cd40fec914c8d8b8b08d72da8cee8e4699474a50cbd
|
"""
Nothing here but dictionaries for generating LinearSegmentedColormaps,
and a dictionary of these dictionaries.
Documentation for each is in pyplot.colormaps(). Please update this
with the purpose and type of your colormap if you add data for one here.
"""
from functools import partial
import numpy as np
_binary_data = {
'red': ((0., 1., 1.), (1., 0., 0.)),
'green': ((0., 1., 1.), (1., 0., 0.)),
'blue': ((0., 1., 1.), (1., 0., 0.))
}
_autumn_data = {'red': ((0., 1.0, 1.0), (1.0, 1.0, 1.0)),
'green': ((0., 0., 0.), (1.0, 1.0, 1.0)),
'blue': ((0., 0., 0.), (1.0, 0., 0.))}
_bone_data = {'red': ((0., 0., 0.),
(0.746032, 0.652778, 0.652778),
(1.0, 1.0, 1.0)),
'green': ((0., 0., 0.),
(0.365079, 0.319444, 0.319444),
(0.746032, 0.777778, 0.777778),
(1.0, 1.0, 1.0)),
'blue': ((0., 0., 0.),
(0.365079, 0.444444, 0.444444),
(1.0, 1.0, 1.0))}
_cool_data = {'red': ((0., 0., 0.), (1.0, 1.0, 1.0)),
'green': ((0., 1., 1.), (1.0, 0., 0.)),
'blue': ((0., 1., 1.), (1.0, 1., 1.))}
_copper_data = {'red': ((0., 0., 0.),
(0.809524, 1.000000, 1.000000),
(1.0, 1.0, 1.0)),
'green': ((0., 0., 0.),
(1.0, 0.7812, 0.7812)),
'blue': ((0., 0., 0.),
(1.0, 0.4975, 0.4975))}
def _flag_red(x): return 0.75 * np.sin((x * 31.5 + 0.25) * np.pi) + 0.5
def _flag_green(x): return np.sin(x * 31.5 * np.pi)
def _flag_blue(x): return 0.75 * np.sin((x * 31.5 - 0.25) * np.pi) + 0.5
_flag_data = {'red': _flag_red, 'green': _flag_green, 'blue': _flag_blue}
def _prism_red(x): return 0.75 * np.sin((x * 20.9 + 0.25) * np.pi) + 0.67
def _prism_green(x): return 0.75 * np.sin((x * 20.9 - 0.25) * np.pi) + 0.33
def _prism_blue(x): return -1.1 * np.sin((x * 20.9) * np.pi)
_prism_data = {'red': _prism_red, 'green': _prism_green, 'blue': _prism_blue}
def _ch_helper(gamma, s, r, h, p0, p1, x):
"""Helper function for generating picklable cubehelix color maps."""
# Apply gamma factor to emphasise low or high intensity values
xg = x ** gamma
# Calculate amplitude and angle of deviation from the black to white
# diagonal in the plane of constant perceived intensity.
a = h * xg * (1 - xg) / 2
phi = 2 * np.pi * (s / 3 + r * x)
return xg + a * (p0 * np.cos(phi) + p1 * np.sin(phi))
def cubehelix(gamma=1.0, s=0.5, r=-1.5, h=1.0):
"""
Return custom data dictionary of (r,g,b) conversion functions, which can be
used with :func:`register_cmap`, for the cubehelix color scheme.
Unlike most other color schemes cubehelix was designed by D.A. Green to
be monotonically increasing in terms of perceived brightness.
Also, when printed on a black and white postscript printer, the scheme
results in a greyscale with monotonically increasing brightness.
This color scheme is named cubehelix because the r,g,b values produced
can be visualised as a squashed helix around the diagonal in the
r,g,b color cube.
For a unit color cube (i.e. 3-D coordinates for r,g,b each in the
range 0 to 1) the color scheme starts at (r,g,b) = (0,0,0), i.e. black,
and finishes at (r,g,b) = (1,1,1), i.e. white. For some fraction *x*,
between 0 and 1, the color is the corresponding grey value at that
fraction along the black to white diagonal (x,x,x) plus a color
element. This color element is calculated in a plane of constant
perceived intensity and controlled by the following parameters.
Optional keyword arguments:
========= =======================================================
Keyword Description
========= =======================================================
gamma gamma factor to emphasise either low intensity values
(gamma < 1), or high intensity values (gamma > 1);
defaults to 1.0.
s the start color; defaults to 0.5 (i.e. purple).
r the number of r,g,b rotations in color that are made
from the start to the end of the color scheme; defaults
to -1.5 (i.e. -> B -> G -> R -> B).
h the hue parameter which controls how saturated the
colors are. If this parameter is zero then the color
scheme is purely a greyscale; defaults to 1.0.
========= =======================================================
"""
return {'red': partial(_ch_helper, gamma, s, r, h, -0.14861, 1.78277),
'green': partial(_ch_helper, gamma, s, r, h, -0.29227, -0.90649),
'blue': partial(_ch_helper, gamma, s, r, h, 1.97294, 0.0)}
_cubehelix_data = cubehelix()
_bwr_data = ((0.0, 0.0, 1.0), (1.0, 1.0, 1.0), (1.0, 0.0, 0.0))
_brg_data = ((0.0, 0.0, 1.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0))
# Gnuplot palette functions
def _g0(x): return 0
def _g1(x): return 0.5
def _g2(x): return 1
def _g3(x): return x
def _g4(x): return x ** 2
def _g5(x): return x ** 3
def _g6(x): return x ** 4
def _g7(x): return np.sqrt(x)
def _g8(x): return np.sqrt(np.sqrt(x))
def _g9(x): return np.sin(x * np.pi / 2)
def _g10(x): return np.cos(x * np.pi / 2)
def _g11(x): return np.abs(x - 0.5)
def _g12(x): return (2 * x - 1) ** 2
def _g13(x): return np.sin(x * np.pi)
def _g14(x): return np.abs(np.cos(x * np.pi))
def _g15(x): return np.sin(x * 2 * np.pi)
def _g16(x): return np.cos(x * 2 * np.pi)
def _g17(x): return np.abs(np.sin(x * 2 * np.pi))
def _g18(x): return np.abs(np.cos(x * 2 * np.pi))
def _g19(x): return np.abs(np.sin(x * 4 * np.pi))
def _g20(x): return np.abs(np.cos(x * 4 * np.pi))
def _g21(x): return 3 * x
def _g22(x): return 3 * x - 1
def _g23(x): return 3 * x - 2
def _g24(x): return np.abs(3 * x - 1)
def _g25(x): return np.abs(3 * x - 2)
def _g26(x): return (3 * x - 1) / 2
def _g27(x): return (3 * x - 2) / 2
def _g28(x): return np.abs((3 * x - 1) / 2)
def _g29(x): return np.abs((3 * x - 2) / 2)
def _g30(x): return x / 0.32 - 0.78125
def _g31(x): return 2 * x - 0.84
def _g32(x):
ret = np.zeros(len(x))
m = (x < 0.25)
ret[m] = 4 * x[m]
m = (x >= 0.25) & (x < 0.92)
ret[m] = -2 * x[m] + 1.84
m = (x >= 0.92)
ret[m] = x[m] / 0.08 - 11.5
return ret
def _g33(x): return np.abs(2 * x - 0.5)
def _g34(x): return 2 * x
def _g35(x): return 2 * x - 0.5
def _g36(x): return 2 * x - 1
gfunc = {i: globals()["_g{}".format(i)] for i in range(37)}
_gnuplot_data = {
'red': gfunc[7],
'green': gfunc[5],
'blue': gfunc[15],
}
_gnuplot2_data = {
'red': gfunc[30],
'green': gfunc[31],
'blue': gfunc[32],
}
_ocean_data = {
'red': gfunc[23],
'green': gfunc[28],
'blue': gfunc[3],
}
_afmhot_data = {
'red': gfunc[34],
'green': gfunc[35],
'blue': gfunc[36],
}
_rainbow_data = {
'red': gfunc[33],
'green': gfunc[13],
'blue': gfunc[10],
}
_seismic_data = (
(0.0, 0.0, 0.3), (0.0, 0.0, 1.0),
(1.0, 1.0, 1.0), (1.0, 0.0, 0.0),
(0.5, 0.0, 0.0))
_terrain_data = (
(0.00, (0.2, 0.2, 0.6)),
(0.15, (0.0, 0.6, 1.0)),
(0.25, (0.0, 0.8, 0.4)),
(0.50, (1.0, 1.0, 0.6)),
(0.75, (0.5, 0.36, 0.33)),
(1.00, (1.0, 1.0, 1.0)))
_gray_data = {'red': ((0., 0, 0), (1., 1, 1)),
'green': ((0., 0, 0), (1., 1, 1)),
'blue': ((0., 0, 0), (1., 1, 1))}
_hot_data = {'red': ((0., 0.0416, 0.0416),
(0.365079, 1.000000, 1.000000),
(1.0, 1.0, 1.0)),
'green': ((0., 0., 0.),
(0.365079, 0.000000, 0.000000),
(0.746032, 1.000000, 1.000000),
(1.0, 1.0, 1.0)),
'blue': ((0., 0., 0.),
(0.746032, 0.000000, 0.000000),
(1.0, 1.0, 1.0))}
_hsv_data = {'red': ((0., 1., 1.),
(0.158730, 1.000000, 1.000000),
(0.174603, 0.968750, 0.968750),
(0.333333, 0.031250, 0.031250),
(0.349206, 0.000000, 0.000000),
(0.666667, 0.000000, 0.000000),
(0.682540, 0.031250, 0.031250),
(0.841270, 0.968750, 0.968750),
(0.857143, 1.000000, 1.000000),
(1.0, 1.0, 1.0)),
'green': ((0., 0., 0.),
(0.158730, 0.937500, 0.937500),
(0.174603, 1.000000, 1.000000),
(0.507937, 1.000000, 1.000000),
(0.666667, 0.062500, 0.062500),
(0.682540, 0.000000, 0.000000),
(1.0, 0., 0.)),
'blue': ((0., 0., 0.),
(0.333333, 0.000000, 0.000000),
(0.349206, 0.062500, 0.062500),
(0.507937, 1.000000, 1.000000),
(0.841270, 1.000000, 1.000000),
(0.857143, 0.937500, 0.937500),
(1.0, 0.09375, 0.09375))}
_jet_data = {'red': ((0., 0, 0), (0.35, 0, 0), (0.66, 1, 1), (0.89, 1, 1),
(1, 0.5, 0.5)),
'green': ((0., 0, 0), (0.125, 0, 0), (0.375, 1, 1), (0.64, 1, 1),
(0.91, 0, 0), (1, 0, 0)),
'blue': ((0., 0.5, 0.5), (0.11, 1, 1), (0.34, 1, 1),
(0.65, 0, 0), (1, 0, 0))}
_pink_data = {'red': ((0., 0.1178, 0.1178), (0.015873, 0.195857, 0.195857),
(0.031746, 0.250661, 0.250661),
(0.047619, 0.295468, 0.295468),
(0.063492, 0.334324, 0.334324),
(0.079365, 0.369112, 0.369112),
(0.095238, 0.400892, 0.400892),
(0.111111, 0.430331, 0.430331),
(0.126984, 0.457882, 0.457882),
(0.142857, 0.483867, 0.483867),
(0.158730, 0.508525, 0.508525),
(0.174603, 0.532042, 0.532042),
(0.190476, 0.554563, 0.554563),
(0.206349, 0.576204, 0.576204),
(0.222222, 0.597061, 0.597061),
(0.238095, 0.617213, 0.617213),
(0.253968, 0.636729, 0.636729),
(0.269841, 0.655663, 0.655663),
(0.285714, 0.674066, 0.674066),
(0.301587, 0.691980, 0.691980),
(0.317460, 0.709441, 0.709441),
(0.333333, 0.726483, 0.726483),
(0.349206, 0.743134, 0.743134),
(0.365079, 0.759421, 0.759421),
(0.380952, 0.766356, 0.766356),
(0.396825, 0.773229, 0.773229),
(0.412698, 0.780042, 0.780042),
(0.428571, 0.786796, 0.786796),
(0.444444, 0.793492, 0.793492),
(0.460317, 0.800132, 0.800132),
(0.476190, 0.806718, 0.806718),
(0.492063, 0.813250, 0.813250),
(0.507937, 0.819730, 0.819730),
(0.523810, 0.826160, 0.826160),
(0.539683, 0.832539, 0.832539),
(0.555556, 0.838870, 0.838870),
(0.571429, 0.845154, 0.845154),
(0.587302, 0.851392, 0.851392),
(0.603175, 0.857584, 0.857584),
(0.619048, 0.863731, 0.863731),
(0.634921, 0.869835, 0.869835),
(0.650794, 0.875897, 0.875897),
(0.666667, 0.881917, 0.881917),
(0.682540, 0.887896, 0.887896),
(0.698413, 0.893835, 0.893835),
(0.714286, 0.899735, 0.899735),
(0.730159, 0.905597, 0.905597),
(0.746032, 0.911421, 0.911421),
(0.761905, 0.917208, 0.917208),
(0.777778, 0.922958, 0.922958),
(0.793651, 0.928673, 0.928673),
(0.809524, 0.934353, 0.934353),
(0.825397, 0.939999, 0.939999),
(0.841270, 0.945611, 0.945611),
(0.857143, 0.951190, 0.951190),
(0.873016, 0.956736, 0.956736),
(0.888889, 0.962250, 0.962250),
(0.904762, 0.967733, 0.967733),
(0.920635, 0.973185, 0.973185),
(0.936508, 0.978607, 0.978607),
(0.952381, 0.983999, 0.983999),
(0.968254, 0.989361, 0.989361),
(0.984127, 0.994695, 0.994695), (1.0, 1.0, 1.0)),
'green': ((0., 0., 0.), (0.015873, 0.102869, 0.102869),
(0.031746, 0.145479, 0.145479),
(0.047619, 0.178174, 0.178174),
(0.063492, 0.205738, 0.205738),
(0.079365, 0.230022, 0.230022),
(0.095238, 0.251976, 0.251976),
(0.111111, 0.272166, 0.272166),
(0.126984, 0.290957, 0.290957),
(0.142857, 0.308607, 0.308607),
(0.158730, 0.325300, 0.325300),
(0.174603, 0.341178, 0.341178),
(0.190476, 0.356348, 0.356348),
(0.206349, 0.370899, 0.370899),
(0.222222, 0.384900, 0.384900),
(0.238095, 0.398410, 0.398410),
(0.253968, 0.411476, 0.411476),
(0.269841, 0.424139, 0.424139),
(0.285714, 0.436436, 0.436436),
(0.301587, 0.448395, 0.448395),
(0.317460, 0.460044, 0.460044),
(0.333333, 0.471405, 0.471405),
(0.349206, 0.482498, 0.482498),
(0.365079, 0.493342, 0.493342),
(0.380952, 0.517549, 0.517549),
(0.396825, 0.540674, 0.540674),
(0.412698, 0.562849, 0.562849),
(0.428571, 0.584183, 0.584183),
(0.444444, 0.604765, 0.604765),
(0.460317, 0.624669, 0.624669),
(0.476190, 0.643958, 0.643958),
(0.492063, 0.662687, 0.662687),
(0.507937, 0.680900, 0.680900),
(0.523810, 0.698638, 0.698638),
(0.539683, 0.715937, 0.715937),
(0.555556, 0.732828, 0.732828),
(0.571429, 0.749338, 0.749338),
(0.587302, 0.765493, 0.765493),
(0.603175, 0.781313, 0.781313),
(0.619048, 0.796819, 0.796819),
(0.634921, 0.812029, 0.812029),
(0.650794, 0.826960, 0.826960),
(0.666667, 0.841625, 0.841625),
(0.682540, 0.856040, 0.856040),
(0.698413, 0.870216, 0.870216),
(0.714286, 0.884164, 0.884164),
(0.730159, 0.897896, 0.897896),
(0.746032, 0.911421, 0.911421),
(0.761905, 0.917208, 0.917208),
(0.777778, 0.922958, 0.922958),
(0.793651, 0.928673, 0.928673),
(0.809524, 0.934353, 0.934353),
(0.825397, 0.939999, 0.939999),
(0.841270, 0.945611, 0.945611),
(0.857143, 0.951190, 0.951190),
(0.873016, 0.956736, 0.956736),
(0.888889, 0.962250, 0.962250),
(0.904762, 0.967733, 0.967733),
(0.920635, 0.973185, 0.973185),
(0.936508, 0.978607, 0.978607),
(0.952381, 0.983999, 0.983999),
(0.968254, 0.989361, 0.989361),
(0.984127, 0.994695, 0.994695), (1.0, 1.0, 1.0)),
'blue': ((0., 0., 0.), (0.015873, 0.102869, 0.102869),
(0.031746, 0.145479, 0.145479),
(0.047619, 0.178174, 0.178174),
(0.063492, 0.205738, 0.205738),
(0.079365, 0.230022, 0.230022),
(0.095238, 0.251976, 0.251976),
(0.111111, 0.272166, 0.272166),
(0.126984, 0.290957, 0.290957),
(0.142857, 0.308607, 0.308607),
(0.158730, 0.325300, 0.325300),
(0.174603, 0.341178, 0.341178),
(0.190476, 0.356348, 0.356348),
(0.206349, 0.370899, 0.370899),
(0.222222, 0.384900, 0.384900),
(0.238095, 0.398410, 0.398410),
(0.253968, 0.411476, 0.411476),
(0.269841, 0.424139, 0.424139),
(0.285714, 0.436436, 0.436436),
(0.301587, 0.448395, 0.448395),
(0.317460, 0.460044, 0.460044),
(0.333333, 0.471405, 0.471405),
(0.349206, 0.482498, 0.482498),
(0.365079, 0.493342, 0.493342),
(0.380952, 0.503953, 0.503953),
(0.396825, 0.514344, 0.514344),
(0.412698, 0.524531, 0.524531),
(0.428571, 0.534522, 0.534522),
(0.444444, 0.544331, 0.544331),
(0.460317, 0.553966, 0.553966),
(0.476190, 0.563436, 0.563436),
(0.492063, 0.572750, 0.572750),
(0.507937, 0.581914, 0.581914),
(0.523810, 0.590937, 0.590937),
(0.539683, 0.599824, 0.599824),
(0.555556, 0.608581, 0.608581),
(0.571429, 0.617213, 0.617213),
(0.587302, 0.625727, 0.625727),
(0.603175, 0.634126, 0.634126),
(0.619048, 0.642416, 0.642416),
(0.634921, 0.650600, 0.650600),
(0.650794, 0.658682, 0.658682),
(0.666667, 0.666667, 0.666667),
(0.682540, 0.674556, 0.674556),
(0.698413, 0.682355, 0.682355),
(0.714286, 0.690066, 0.690066),
(0.730159, 0.697691, 0.697691),
(0.746032, 0.705234, 0.705234),
(0.761905, 0.727166, 0.727166),
(0.777778, 0.748455, 0.748455),
(0.793651, 0.769156, 0.769156),
(0.809524, 0.789314, 0.789314),
(0.825397, 0.808969, 0.808969),
(0.841270, 0.828159, 0.828159),
(0.857143, 0.846913, 0.846913),
(0.873016, 0.865261, 0.865261),
(0.888889, 0.883229, 0.883229),
(0.904762, 0.900837, 0.900837),
(0.920635, 0.918109, 0.918109),
(0.936508, 0.935061, 0.935061),
(0.952381, 0.951711, 0.951711),
(0.968254, 0.968075, 0.968075),
(0.984127, 0.984167, 0.984167), (1.0, 1.0, 1.0))}
_spring_data = {'red': ((0., 1., 1.), (1.0, 1.0, 1.0)),
'green': ((0., 0., 0.), (1.0, 1.0, 1.0)),
'blue': ((0., 1., 1.), (1.0, 0.0, 0.0))}
_summer_data = {'red': ((0., 0., 0.), (1.0, 1.0, 1.0)),
'green': ((0., 0.5, 0.5), (1.0, 1.0, 1.0)),
'blue': ((0., 0.4, 0.4), (1.0, 0.4, 0.4))}
_winter_data = {'red': ((0., 0., 0.), (1.0, 0.0, 0.0)),
'green': ((0., 0., 0.), (1.0, 1.0, 1.0)),
'blue': ((0., 1., 1.), (1.0, 0.5, 0.5))}
_nipy_spectral_data = {
'red': [(0.0, 0.0, 0.0), (0.05, 0.4667, 0.4667),
(0.10, 0.5333, 0.5333), (0.15, 0.0, 0.0),
(0.20, 0.0, 0.0), (0.25, 0.0, 0.0),
(0.30, 0.0, 0.0), (0.35, 0.0, 0.0),
(0.40, 0.0, 0.0), (0.45, 0.0, 0.0),
(0.50, 0.0, 0.0), (0.55, 0.0, 0.0),
(0.60, 0.0, 0.0), (0.65, 0.7333, 0.7333),
(0.70, 0.9333, 0.9333), (0.75, 1.0, 1.0),
(0.80, 1.0, 1.0), (0.85, 1.0, 1.0),
(0.90, 0.8667, 0.8667), (0.95, 0.80, 0.80),
(1.0, 0.80, 0.80)],
'green': [(0.0, 0.0, 0.0), (0.05, 0.0, 0.0),
(0.10, 0.0, 0.0), (0.15, 0.0, 0.0),
(0.20, 0.0, 0.0), (0.25, 0.4667, 0.4667),
(0.30, 0.6000, 0.6000), (0.35, 0.6667, 0.6667),
(0.40, 0.6667, 0.6667), (0.45, 0.6000, 0.6000),
(0.50, 0.7333, 0.7333), (0.55, 0.8667, 0.8667),
(0.60, 1.0, 1.0), (0.65, 1.0, 1.0),
(0.70, 0.9333, 0.9333), (0.75, 0.8000, 0.8000),
(0.80, 0.6000, 0.6000), (0.85, 0.0, 0.0),
(0.90, 0.0, 0.0), (0.95, 0.0, 0.0),
(1.0, 0.80, 0.80)],
'blue': [(0.0, 0.0, 0.0), (0.05, 0.5333, 0.5333),
(0.10, 0.6000, 0.6000), (0.15, 0.6667, 0.6667),
(0.20, 0.8667, 0.8667), (0.25, 0.8667, 0.8667),
(0.30, 0.8667, 0.8667), (0.35, 0.6667, 0.6667),
(0.40, 0.5333, 0.5333), (0.45, 0.0, 0.0),
(0.5, 0.0, 0.0), (0.55, 0.0, 0.0),
(0.60, 0.0, 0.0), (0.65, 0.0, 0.0),
(0.70, 0.0, 0.0), (0.75, 0.0, 0.0),
(0.80, 0.0, 0.0), (0.85, 0.0, 0.0),
(0.90, 0.0, 0.0), (0.95, 0.0, 0.0),
(1.0, 0.80, 0.80)],
}
# 34 colormaps based on color specifications and designs
# developed by Cynthia Brewer (http://colorbrewer.org).
# The ColorBrewer palettes have been included under the terms
# of an Apache-stype license (for details, see the file
# LICENSE_COLORBREWER in the license directory of the matplotlib
# source distribution).
# RGB values taken from Brewer's Excel sheet, divided by 255
_Blues_data = (
(0.96862745098039216, 0.98431372549019602, 1.0 ),
(0.87058823529411766, 0.92156862745098034, 0.96862745098039216),
(0.77647058823529413, 0.85882352941176465, 0.93725490196078431),
(0.61960784313725492, 0.792156862745098 , 0.88235294117647056),
(0.41960784313725491, 0.68235294117647061, 0.83921568627450982),
(0.25882352941176473, 0.5725490196078431 , 0.77647058823529413),
(0.12941176470588237, 0.44313725490196076, 0.70980392156862748),
(0.03137254901960784, 0.31764705882352939, 0.61176470588235299),
(0.03137254901960784, 0.18823529411764706, 0.41960784313725491)
)
_BrBG_data = (
(0.32941176470588235, 0.18823529411764706, 0.0196078431372549 ),
(0.5490196078431373 , 0.31764705882352939, 0.0392156862745098 ),
(0.74901960784313726, 0.50588235294117645, 0.17647058823529413),
(0.87450980392156863, 0.76078431372549016, 0.49019607843137253),
(0.96470588235294119, 0.90980392156862744, 0.76470588235294112),
(0.96078431372549022, 0.96078431372549022, 0.96078431372549022),
(0.7803921568627451 , 0.91764705882352937, 0.89803921568627454),
(0.50196078431372548, 0.80392156862745101, 0.75686274509803919),
(0.20784313725490197, 0.59215686274509804, 0.5607843137254902 ),
(0.00392156862745098, 0.4 , 0.36862745098039218),
(0.0 , 0.23529411764705882, 0.18823529411764706)
)
_BuGn_data = (
(0.96862745098039216, 0.9882352941176471 , 0.99215686274509807),
(0.89803921568627454, 0.96078431372549022, 0.97647058823529409),
(0.8 , 0.92549019607843142, 0.90196078431372551),
(0.6 , 0.84705882352941175, 0.78823529411764703),
(0.4 , 0.76078431372549016, 0.64313725490196083),
(0.25490196078431371, 0.68235294117647061, 0.46274509803921571),
(0.13725490196078433, 0.54509803921568623, 0.27058823529411763),
(0.0 , 0.42745098039215684, 0.17254901960784313),
(0.0 , 0.26666666666666666, 0.10588235294117647)
)
_BuPu_data = (
(0.96862745098039216, 0.9882352941176471 , 0.99215686274509807),
(0.8784313725490196 , 0.92549019607843142, 0.95686274509803926),
(0.74901960784313726, 0.82745098039215681, 0.90196078431372551),
(0.61960784313725492, 0.73725490196078436, 0.85490196078431369),
(0.5490196078431373 , 0.58823529411764708, 0.77647058823529413),
(0.5490196078431373 , 0.41960784313725491, 0.69411764705882351),
(0.53333333333333333, 0.25490196078431371, 0.61568627450980395),
(0.50588235294117645, 0.05882352941176471, 0.48627450980392156),
(0.30196078431372547, 0.0 , 0.29411764705882354)
)
_GnBu_data = (
(0.96862745098039216, 0.9882352941176471 , 0.94117647058823528),
(0.8784313725490196 , 0.95294117647058818, 0.85882352941176465),
(0.8 , 0.92156862745098034, 0.77254901960784317),
(0.6588235294117647 , 0.8666666666666667 , 0.70980392156862748),
(0.4823529411764706 , 0.8 , 0.7686274509803922 ),
(0.30588235294117649, 0.70196078431372544, 0.82745098039215681),
(0.16862745098039217, 0.5490196078431373 , 0.74509803921568629),
(0.03137254901960784, 0.40784313725490196, 0.67450980392156867),
(0.03137254901960784, 0.25098039215686274, 0.50588235294117645)
)
_Greens_data = (
(0.96862745098039216, 0.9882352941176471 , 0.96078431372549022),
(0.89803921568627454, 0.96078431372549022, 0.8784313725490196 ),
(0.7803921568627451 , 0.9137254901960784 , 0.75294117647058822),
(0.63137254901960782, 0.85098039215686272, 0.60784313725490191),
(0.45490196078431372, 0.7686274509803922 , 0.46274509803921571),
(0.25490196078431371, 0.6705882352941176 , 0.36470588235294116),
(0.13725490196078433, 0.54509803921568623, 0.27058823529411763),
(0.0 , 0.42745098039215684, 0.17254901960784313),
(0.0 , 0.26666666666666666, 0.10588235294117647)
)
_Greys_data = (
(1.0 , 1.0 , 1.0 ),
(0.94117647058823528, 0.94117647058823528, 0.94117647058823528),
(0.85098039215686272, 0.85098039215686272, 0.85098039215686272),
(0.74117647058823533, 0.74117647058823533, 0.74117647058823533),
(0.58823529411764708, 0.58823529411764708, 0.58823529411764708),
(0.45098039215686275, 0.45098039215686275, 0.45098039215686275),
(0.32156862745098042, 0.32156862745098042, 0.32156862745098042),
(0.14509803921568629, 0.14509803921568629, 0.14509803921568629),
(0.0 , 0.0 , 0.0 )
)
_Oranges_data = (
(1.0 , 0.96078431372549022, 0.92156862745098034),
(0.99607843137254903, 0.90196078431372551, 0.80784313725490198),
(0.99215686274509807, 0.81568627450980391, 0.63529411764705879),
(0.99215686274509807, 0.68235294117647061, 0.41960784313725491),
(0.99215686274509807, 0.55294117647058827, 0.23529411764705882),
(0.94509803921568625, 0.41176470588235292, 0.07450980392156863),
(0.85098039215686272, 0.28235294117647058, 0.00392156862745098),
(0.65098039215686276, 0.21176470588235294, 0.01176470588235294),
(0.49803921568627452, 0.15294117647058825, 0.01568627450980392)
)
_OrRd_data = (
(1.0 , 0.96862745098039216, 0.92549019607843142),
(0.99607843137254903, 0.90980392156862744, 0.78431372549019607),
(0.99215686274509807, 0.83137254901960789, 0.61960784313725492),
(0.99215686274509807, 0.73333333333333328, 0.51764705882352946),
(0.9882352941176471 , 0.55294117647058827, 0.34901960784313724),
(0.93725490196078431, 0.396078431372549 , 0.28235294117647058),
(0.84313725490196079, 0.18823529411764706, 0.12156862745098039),
(0.70196078431372544, 0.0 , 0.0 ),
(0.49803921568627452, 0.0 , 0.0 )
)
_PiYG_data = (
(0.55686274509803924, 0.00392156862745098, 0.32156862745098042),
(0.77254901960784317, 0.10588235294117647, 0.49019607843137253),
(0.87058823529411766, 0.46666666666666667, 0.68235294117647061),
(0.94509803921568625, 0.71372549019607845, 0.85490196078431369),
(0.99215686274509807, 0.8784313725490196 , 0.93725490196078431),
(0.96862745098039216, 0.96862745098039216, 0.96862745098039216),
(0.90196078431372551, 0.96078431372549022, 0.81568627450980391),
(0.72156862745098038, 0.88235294117647056, 0.52549019607843139),
(0.49803921568627452, 0.73725490196078436, 0.25490196078431371),
(0.30196078431372547, 0.5725490196078431 , 0.12941176470588237),
(0.15294117647058825, 0.39215686274509803, 0.09803921568627451)
)
_PRGn_data = (
(0.25098039215686274, 0.0 , 0.29411764705882354),
(0.46274509803921571, 0.16470588235294117, 0.51372549019607838),
(0.6 , 0.4392156862745098 , 0.6705882352941176 ),
(0.76078431372549016, 0.6470588235294118 , 0.81176470588235294),
(0.90588235294117647, 0.83137254901960789, 0.90980392156862744),
(0.96862745098039216, 0.96862745098039216, 0.96862745098039216),
(0.85098039215686272, 0.94117647058823528, 0.82745098039215681),
(0.65098039215686276, 0.85882352941176465, 0.62745098039215685),
(0.35294117647058826, 0.68235294117647061, 0.38039215686274508),
(0.10588235294117647, 0.47058823529411764, 0.21568627450980393),
(0.0 , 0.26666666666666666, 0.10588235294117647)
)
_PuBu_data = (
(1.0 , 0.96862745098039216, 0.98431372549019602),
(0.92549019607843142, 0.90588235294117647, 0.94901960784313721),
(0.81568627450980391, 0.81960784313725488, 0.90196078431372551),
(0.65098039215686276, 0.74117647058823533, 0.85882352941176465),
(0.45490196078431372, 0.66274509803921566, 0.81176470588235294),
(0.21176470588235294, 0.56470588235294117, 0.75294117647058822),
(0.0196078431372549 , 0.4392156862745098 , 0.69019607843137254),
(0.01568627450980392, 0.35294117647058826, 0.55294117647058827),
(0.00784313725490196, 0.2196078431372549 , 0.34509803921568627)
)
_PuBuGn_data = (
(1.0 , 0.96862745098039216, 0.98431372549019602),
(0.92549019607843142, 0.88627450980392153, 0.94117647058823528),
(0.81568627450980391, 0.81960784313725488, 0.90196078431372551),
(0.65098039215686276, 0.74117647058823533, 0.85882352941176465),
(0.40392156862745099, 0.66274509803921566, 0.81176470588235294),
(0.21176470588235294, 0.56470588235294117, 0.75294117647058822),
(0.00784313725490196, 0.50588235294117645, 0.54117647058823526),
(0.00392156862745098, 0.42352941176470588, 0.34901960784313724),
(0.00392156862745098, 0.27450980392156865, 0.21176470588235294)
)
_PuOr_data = (
(0.49803921568627452, 0.23137254901960785, 0.03137254901960784),
(0.70196078431372544, 0.34509803921568627, 0.02352941176470588),
(0.8784313725490196 , 0.50980392156862742, 0.07843137254901961),
(0.99215686274509807, 0.72156862745098038, 0.38823529411764707),
(0.99607843137254903, 0.8784313725490196 , 0.71372549019607845),
(0.96862745098039216, 0.96862745098039216, 0.96862745098039216),
(0.84705882352941175, 0.85490196078431369, 0.92156862745098034),
(0.69803921568627447, 0.6705882352941176 , 0.82352941176470584),
(0.50196078431372548, 0.45098039215686275, 0.67450980392156867),
(0.32941176470588235, 0.15294117647058825, 0.53333333333333333),
(0.17647058823529413, 0.0 , 0.29411764705882354)
)
_PuRd_data = (
(0.96862745098039216, 0.95686274509803926, 0.97647058823529409),
(0.90588235294117647, 0.88235294117647056, 0.93725490196078431),
(0.83137254901960789, 0.72549019607843135, 0.85490196078431369),
(0.78823529411764703, 0.58039215686274515, 0.7803921568627451 ),
(0.87450980392156863, 0.396078431372549 , 0.69019607843137254),
(0.90588235294117647, 0.16078431372549021, 0.54117647058823526),
(0.80784313725490198, 0.07058823529411765, 0.33725490196078434),
(0.59607843137254901, 0.0 , 0.2627450980392157 ),
(0.40392156862745099, 0.0 , 0.12156862745098039)
)
_Purples_data = (
(0.9882352941176471 , 0.98431372549019602, 0.99215686274509807),
(0.93725490196078431, 0.92941176470588238, 0.96078431372549022),
(0.85490196078431369, 0.85490196078431369, 0.92156862745098034),
(0.73725490196078436, 0.74117647058823533, 0.86274509803921573),
(0.61960784313725492, 0.60392156862745094, 0.78431372549019607),
(0.50196078431372548, 0.49019607843137253, 0.72941176470588232),
(0.41568627450980394, 0.31764705882352939, 0.63921568627450975),
(0.32941176470588235, 0.15294117647058825, 0.5607843137254902 ),
(0.24705882352941178, 0.0 , 0.49019607843137253)
)
_RdBu_data = (
(0.40392156862745099, 0.0 , 0.12156862745098039),
(0.69803921568627447, 0.09411764705882353, 0.16862745098039217),
(0.83921568627450982, 0.37647058823529411, 0.30196078431372547),
(0.95686274509803926, 0.6470588235294118 , 0.50980392156862742),
(0.99215686274509807, 0.85882352941176465, 0.7803921568627451 ),
(0.96862745098039216, 0.96862745098039216, 0.96862745098039216),
(0.81960784313725488, 0.89803921568627454, 0.94117647058823528),
(0.5725490196078431 , 0.77254901960784317, 0.87058823529411766),
(0.2627450980392157 , 0.57647058823529407, 0.76470588235294112),
(0.12941176470588237, 0.4 , 0.67450980392156867),
(0.0196078431372549 , 0.18823529411764706, 0.38039215686274508)
)
_RdGy_data = (
(0.40392156862745099, 0.0 , 0.12156862745098039),
(0.69803921568627447, 0.09411764705882353, 0.16862745098039217),
(0.83921568627450982, 0.37647058823529411, 0.30196078431372547),
(0.95686274509803926, 0.6470588235294118 , 0.50980392156862742),
(0.99215686274509807, 0.85882352941176465, 0.7803921568627451 ),
(1.0 , 1.0 , 1.0 ),
(0.8784313725490196 , 0.8784313725490196 , 0.8784313725490196 ),
(0.72941176470588232, 0.72941176470588232, 0.72941176470588232),
(0.52941176470588236, 0.52941176470588236, 0.52941176470588236),
(0.30196078431372547, 0.30196078431372547, 0.30196078431372547),
(0.10196078431372549, 0.10196078431372549, 0.10196078431372549)
)
_RdPu_data = (
(1.0 , 0.96862745098039216, 0.95294117647058818),
(0.99215686274509807, 0.8784313725490196 , 0.86666666666666667),
(0.9882352941176471 , 0.77254901960784317, 0.75294117647058822),
(0.98039215686274506, 0.62352941176470589, 0.70980392156862748),
(0.96862745098039216, 0.40784313725490196, 0.63137254901960782),
(0.86666666666666667, 0.20392156862745098, 0.59215686274509804),
(0.68235294117647061, 0.00392156862745098, 0.49411764705882355),
(0.47843137254901963, 0.00392156862745098, 0.46666666666666667),
(0.28627450980392155, 0.0 , 0.41568627450980394)
)
_RdYlBu_data = (
(0.6470588235294118 , 0.0 , 0.14901960784313725),
(0.84313725490196079, 0.18823529411764706 , 0.15294117647058825),
(0.95686274509803926, 0.42745098039215684 , 0.2627450980392157 ),
(0.99215686274509807, 0.68235294117647061 , 0.38039215686274508),
(0.99607843137254903, 0.8784313725490196 , 0.56470588235294117),
(1.0 , 1.0 , 0.74901960784313726),
(0.8784313725490196 , 0.95294117647058818 , 0.97254901960784312),
(0.6705882352941176 , 0.85098039215686272 , 0.9137254901960784 ),
(0.45490196078431372, 0.67843137254901964 , 0.81960784313725488),
(0.27058823529411763, 0.45882352941176469 , 0.70588235294117652),
(0.19215686274509805, 0.21176470588235294 , 0.58431372549019611)
)
_RdYlGn_data = (
(0.6470588235294118 , 0.0 , 0.14901960784313725),
(0.84313725490196079, 0.18823529411764706 , 0.15294117647058825),
(0.95686274509803926, 0.42745098039215684 , 0.2627450980392157 ),
(0.99215686274509807, 0.68235294117647061 , 0.38039215686274508),
(0.99607843137254903, 0.8784313725490196 , 0.54509803921568623),
(1.0 , 1.0 , 0.74901960784313726),
(0.85098039215686272, 0.93725490196078431 , 0.54509803921568623),
(0.65098039215686276, 0.85098039215686272 , 0.41568627450980394),
(0.4 , 0.74117647058823533 , 0.38823529411764707),
(0.10196078431372549, 0.59607843137254901 , 0.31372549019607843),
(0.0 , 0.40784313725490196 , 0.21568627450980393)
)
_Reds_data = (
(1.0 , 0.96078431372549022 , 0.94117647058823528),
(0.99607843137254903, 0.8784313725490196 , 0.82352941176470584),
(0.9882352941176471 , 0.73333333333333328 , 0.63137254901960782),
(0.9882352941176471 , 0.5725490196078431 , 0.44705882352941179),
(0.98431372549019602, 0.41568627450980394 , 0.29019607843137257),
(0.93725490196078431, 0.23137254901960785 , 0.17254901960784313),
(0.79607843137254897, 0.094117647058823528, 0.11372549019607843),
(0.6470588235294118 , 0.058823529411764705, 0.08235294117647058),
(0.40392156862745099, 0.0 , 0.05098039215686274)
)
_Spectral_data = (
(0.61960784313725492, 0.003921568627450980, 0.25882352941176473),
(0.83529411764705885, 0.24313725490196078 , 0.30980392156862746),
(0.95686274509803926, 0.42745098039215684 , 0.2627450980392157 ),
(0.99215686274509807, 0.68235294117647061 , 0.38039215686274508),
(0.99607843137254903, 0.8784313725490196 , 0.54509803921568623),
(1.0 , 1.0 , 0.74901960784313726),
(0.90196078431372551, 0.96078431372549022 , 0.59607843137254901),
(0.6705882352941176 , 0.8666666666666667 , 0.64313725490196083),
(0.4 , 0.76078431372549016 , 0.6470588235294118 ),
(0.19607843137254902, 0.53333333333333333 , 0.74117647058823533),
(0.36862745098039218, 0.30980392156862746 , 0.63529411764705879)
)
_YlGn_data = (
(1.0 , 1.0 , 0.89803921568627454),
(0.96862745098039216, 0.9882352941176471 , 0.72549019607843135),
(0.85098039215686272, 0.94117647058823528 , 0.63921568627450975),
(0.67843137254901964, 0.8666666666666667 , 0.55686274509803924),
(0.47058823529411764, 0.77647058823529413 , 0.47450980392156861),
(0.25490196078431371, 0.6705882352941176 , 0.36470588235294116),
(0.13725490196078433, 0.51764705882352946 , 0.2627450980392157 ),
(0.0 , 0.40784313725490196 , 0.21568627450980393),
(0.0 , 0.27058823529411763 , 0.16078431372549021)
)
_YlGnBu_data = (
(1.0 , 1.0 , 0.85098039215686272),
(0.92941176470588238, 0.97254901960784312 , 0.69411764705882351),
(0.7803921568627451 , 0.9137254901960784 , 0.70588235294117652),
(0.49803921568627452, 0.80392156862745101 , 0.73333333333333328),
(0.25490196078431371, 0.71372549019607845 , 0.7686274509803922 ),
(0.11372549019607843, 0.56862745098039214 , 0.75294117647058822),
(0.13333333333333333, 0.36862745098039218 , 0.6588235294117647 ),
(0.14509803921568629, 0.20392156862745098 , 0.58039215686274515),
(0.03137254901960784, 0.11372549019607843 , 0.34509803921568627)
)
_YlOrBr_data = (
(1.0 , 1.0 , 0.89803921568627454),
(1.0 , 0.96862745098039216 , 0.73725490196078436),
(0.99607843137254903, 0.8901960784313725 , 0.56862745098039214),
(0.99607843137254903, 0.7686274509803922 , 0.30980392156862746),
(0.99607843137254903, 0.6 , 0.16078431372549021),
(0.92549019607843142, 0.4392156862745098 , 0.07843137254901961),
(0.8 , 0.29803921568627451 , 0.00784313725490196),
(0.6 , 0.20392156862745098 , 0.01568627450980392),
(0.4 , 0.14509803921568629 , 0.02352941176470588)
)
_YlOrRd_data = (
(1.0 , 1.0 , 0.8 ),
(1.0 , 0.92941176470588238 , 0.62745098039215685),
(0.99607843137254903, 0.85098039215686272 , 0.46274509803921571),
(0.99607843137254903, 0.69803921568627447 , 0.29803921568627451),
(0.99215686274509807, 0.55294117647058827 , 0.23529411764705882),
(0.9882352941176471 , 0.30588235294117649 , 0.16470588235294117),
(0.8901960784313725 , 0.10196078431372549 , 0.10980392156862745),
(0.74117647058823533, 0.0 , 0.14901960784313725),
(0.50196078431372548, 0.0 , 0.14901960784313725)
)
# ColorBrewer's qualitative maps, implemented using ListedColormap
# for use with mpl.colors.NoNorm
_Accent_data = (
(0.49803921568627452, 0.78823529411764703, 0.49803921568627452),
(0.74509803921568629, 0.68235294117647061, 0.83137254901960789),
(0.99215686274509807, 0.75294117647058822, 0.52549019607843139),
(1.0, 1.0, 0.6 ),
(0.2196078431372549, 0.42352941176470588, 0.69019607843137254),
(0.94117647058823528, 0.00784313725490196, 0.49803921568627452),
(0.74901960784313726, 0.35686274509803922, 0.09019607843137254),
(0.4, 0.4, 0.4 ),
)
_Dark2_data = (
(0.10588235294117647, 0.61960784313725492, 0.46666666666666667),
(0.85098039215686272, 0.37254901960784315, 0.00784313725490196),
(0.45882352941176469, 0.4392156862745098, 0.70196078431372544),
(0.90588235294117647, 0.16078431372549021, 0.54117647058823526),
(0.4, 0.65098039215686276, 0.11764705882352941),
(0.90196078431372551, 0.6705882352941176, 0.00784313725490196),
(0.65098039215686276, 0.46274509803921571, 0.11372549019607843),
(0.4, 0.4, 0.4 ),
)
_Paired_data = (
(0.65098039215686276, 0.80784313725490198, 0.8901960784313725 ),
(0.12156862745098039, 0.47058823529411764, 0.70588235294117652),
(0.69803921568627447, 0.87450980392156863, 0.54117647058823526),
(0.2, 0.62745098039215685, 0.17254901960784313),
(0.98431372549019602, 0.60392156862745094, 0.6 ),
(0.8901960784313725, 0.10196078431372549, 0.10980392156862745),
(0.99215686274509807, 0.74901960784313726, 0.43529411764705883),
(1.0, 0.49803921568627452, 0.0 ),
(0.792156862745098, 0.69803921568627447, 0.83921568627450982),
(0.41568627450980394, 0.23921568627450981, 0.60392156862745094),
(1.0, 1.0, 0.6 ),
(0.69411764705882351, 0.34901960784313724, 0.15686274509803921),
)
_Pastel1_data = (
(0.98431372549019602, 0.70588235294117652, 0.68235294117647061),
(0.70196078431372544, 0.80392156862745101, 0.8901960784313725 ),
(0.8, 0.92156862745098034, 0.77254901960784317),
(0.87058823529411766, 0.79607843137254897, 0.89411764705882357),
(0.99607843137254903, 0.85098039215686272, 0.65098039215686276),
(1.0, 1.0, 0.8 ),
(0.89803921568627454, 0.84705882352941175, 0.74117647058823533),
(0.99215686274509807, 0.85490196078431369, 0.92549019607843142),
(0.94901960784313721, 0.94901960784313721, 0.94901960784313721),
)
_Pastel2_data = (
(0.70196078431372544, 0.88627450980392153, 0.80392156862745101),
(0.99215686274509807, 0.80392156862745101, 0.67450980392156867),
(0.79607843137254897, 0.83529411764705885, 0.90980392156862744),
(0.95686274509803926, 0.792156862745098, 0.89411764705882357),
(0.90196078431372551, 0.96078431372549022, 0.78823529411764703),
(1.0, 0.94901960784313721, 0.68235294117647061),
(0.94509803921568625, 0.88627450980392153, 0.8 ),
(0.8, 0.8, 0.8 ),
)
_Set1_data = (
(0.89411764705882357, 0.10196078431372549, 0.10980392156862745),
(0.21568627450980393, 0.49411764705882355, 0.72156862745098038),
(0.30196078431372547, 0.68627450980392157, 0.29019607843137257),
(0.59607843137254901, 0.30588235294117649, 0.63921568627450975),
(1.0, 0.49803921568627452, 0.0 ),
(1.0, 1.0, 0.2 ),
(0.65098039215686276, 0.33725490196078434, 0.15686274509803921),
(0.96862745098039216, 0.50588235294117645, 0.74901960784313726),
(0.6, 0.6, 0.6),
)
_Set2_data = (
(0.4, 0.76078431372549016, 0.6470588235294118 ),
(0.9882352941176471, 0.55294117647058827, 0.3843137254901961 ),
(0.55294117647058827, 0.62745098039215685, 0.79607843137254897),
(0.90588235294117647, 0.54117647058823526, 0.76470588235294112),
(0.65098039215686276, 0.84705882352941175, 0.32941176470588235),
(1.0, 0.85098039215686272, 0.18431372549019609),
(0.89803921568627454, 0.7686274509803922, 0.58039215686274515),
(0.70196078431372544, 0.70196078431372544, 0.70196078431372544),
)
_Set3_data = (
(0.55294117647058827, 0.82745098039215681, 0.7803921568627451 ),
(1.0, 1.0, 0.70196078431372544),
(0.74509803921568629, 0.72941176470588232, 0.85490196078431369),
(0.98431372549019602, 0.50196078431372548, 0.44705882352941179),
(0.50196078431372548, 0.69411764705882351, 0.82745098039215681),
(0.99215686274509807, 0.70588235294117652, 0.3843137254901961 ),
(0.70196078431372544, 0.87058823529411766, 0.41176470588235292),
(0.9882352941176471, 0.80392156862745101, 0.89803921568627454),
(0.85098039215686272, 0.85098039215686272, 0.85098039215686272),
(0.73725490196078436, 0.50196078431372548, 0.74117647058823533),
(0.8, 0.92156862745098034, 0.77254901960784317),
(1.0, 0.92941176470588238, 0.43529411764705883),
)
# The next 7 palettes are from the Yorick scientific visualization package,
# an evolution of the GIST package, both by David H. Munro.
# They are released under a BSD-like license (see LICENSE_YORICK in
# the license directory of the matplotlib source distribution).
#
# Most palette functions have been reduced to simple function descriptions
# by Reinier Heeres, since the rgb components were mostly straight lines.
# gist_earth_data and gist_ncar_data were simplified by a script and some
# manual effort.
_gist_earth_data = \
{'red': (
(0.0, 0.0, 0.0000),
(0.2824, 0.1882, 0.1882),
(0.4588, 0.2714, 0.2714),
(0.5490, 0.4719, 0.4719),
(0.6980, 0.7176, 0.7176),
(0.7882, 0.7553, 0.7553),
(1.0000, 0.9922, 0.9922),
), 'green': (
(0.0, 0.0, 0.0000),
(0.0275, 0.0000, 0.0000),
(0.1098, 0.1893, 0.1893),
(0.1647, 0.3035, 0.3035),
(0.2078, 0.3841, 0.3841),
(0.2824, 0.5020, 0.5020),
(0.5216, 0.6397, 0.6397),
(0.6980, 0.7171, 0.7171),
(0.7882, 0.6392, 0.6392),
(0.7922, 0.6413, 0.6413),
(0.8000, 0.6447, 0.6447),
(0.8078, 0.6481, 0.6481),
(0.8157, 0.6549, 0.6549),
(0.8667, 0.6991, 0.6991),
(0.8745, 0.7103, 0.7103),
(0.8824, 0.7216, 0.7216),
(0.8902, 0.7323, 0.7323),
(0.8980, 0.7430, 0.7430),
(0.9412, 0.8275, 0.8275),
(0.9569, 0.8635, 0.8635),
(0.9647, 0.8816, 0.8816),
(0.9961, 0.9733, 0.9733),
(1.0000, 0.9843, 0.9843),
), 'blue': (
(0.0, 0.0, 0.0000),
(0.0039, 0.1684, 0.1684),
(0.0078, 0.2212, 0.2212),
(0.0275, 0.4329, 0.4329),
(0.0314, 0.4549, 0.4549),
(0.2824, 0.5004, 0.5004),
(0.4667, 0.2748, 0.2748),
(0.5451, 0.3205, 0.3205),
(0.7843, 0.3961, 0.3961),
(0.8941, 0.6651, 0.6651),
(1.0000, 0.9843, 0.9843),
)}
_gist_gray_data = {
'red': gfunc[3],
'green': gfunc[3],
'blue': gfunc[3],
}
def _gist_heat_red(x): return 1.5 * x
def _gist_heat_green(x): return 2 * x - 1
def _gist_heat_blue(x): return 4 * x - 3
_gist_heat_data = {
'red': _gist_heat_red, 'green': _gist_heat_green, 'blue': _gist_heat_blue}
_gist_ncar_data = \
{'red': (
(0.0, 0.0, 0.0000),
(0.3098, 0.0000, 0.0000),
(0.3725, 0.3993, 0.3993),
(0.4235, 0.5003, 0.5003),
(0.5333, 1.0000, 1.0000),
(0.7922, 1.0000, 1.0000),
(0.8471, 0.6218, 0.6218),
(0.8980, 0.9235, 0.9235),
(1.0000, 0.9961, 0.9961),
), 'green': (
(0.0, 0.0, 0.0000),
(0.0510, 0.3722, 0.3722),
(0.1059, 0.0000, 0.0000),
(0.1569, 0.7202, 0.7202),
(0.1608, 0.7537, 0.7537),
(0.1647, 0.7752, 0.7752),
(0.2157, 1.0000, 1.0000),
(0.2588, 0.9804, 0.9804),
(0.2706, 0.9804, 0.9804),
(0.3176, 1.0000, 1.0000),
(0.3686, 0.8081, 0.8081),
(0.4275, 1.0000, 1.0000),
(0.5216, 1.0000, 1.0000),
(0.6314, 0.7292, 0.7292),
(0.6863, 0.2796, 0.2796),
(0.7451, 0.0000, 0.0000),
(0.7922, 0.0000, 0.0000),
(0.8431, 0.1753, 0.1753),
(0.8980, 0.5000, 0.5000),
(1.0000, 0.9725, 0.9725),
), 'blue': (
(0.0, 0.5020, 0.5020),
(0.0510, 0.0222, 0.0222),
(0.1098, 1.0000, 1.0000),
(0.2039, 1.0000, 1.0000),
(0.2627, 0.6145, 0.6145),
(0.3216, 0.0000, 0.0000),
(0.4157, 0.0000, 0.0000),
(0.4745, 0.2342, 0.2342),
(0.5333, 0.0000, 0.0000),
(0.5804, 0.0000, 0.0000),
(0.6314, 0.0549, 0.0549),
(0.6902, 0.0000, 0.0000),
(0.7373, 0.0000, 0.0000),
(0.7922, 0.9738, 0.9738),
(0.8000, 1.0000, 1.0000),
(0.8431, 1.0000, 1.0000),
(0.8980, 0.9341, 0.9341),
(1.0000, 0.9961, 0.9961),
)}
_gist_rainbow_data = (
(0.000, (1.00, 0.00, 0.16)),
(0.030, (1.00, 0.00, 0.00)),
(0.215, (1.00, 1.00, 0.00)),
(0.400, (0.00, 1.00, 0.00)),
(0.586, (0.00, 1.00, 1.00)),
(0.770, (0.00, 0.00, 1.00)),
(0.954, (1.00, 0.00, 1.00)),
(1.000, (1.00, 0.00, 0.75))
)
_gist_stern_data = {
'red': (
(0.000, 0.000, 0.000), (0.0547, 1.000, 1.000),
(0.250, 0.027, 0.250), # (0.2500, 0.250, 0.250),
(1.000, 1.000, 1.000)),
'green': ((0, 0, 0), (1, 1, 1)),
'blue': (
(0.000, 0.000, 0.000), (0.500, 1.000, 1.000),
(0.735, 0.000, 0.000), (1.000, 1.000, 1.000))
}
def _gist_yarg(x): return 1 - x
_gist_yarg_data = {'red': _gist_yarg, 'green': _gist_yarg, 'blue': _gist_yarg}
# This bipolar color map was generated from CoolWarmFloat33.csv of
# "Diverging Color Maps for Scientific Visualization" by Kenneth Moreland.
# <http://www.kennethmoreland.com/color-maps/>
_coolwarm_data = {
'red': [
(0.0, 0.2298057, 0.2298057),
(0.03125, 0.26623388, 0.26623388),
(0.0625, 0.30386891, 0.30386891),
(0.09375, 0.342804478, 0.342804478),
(0.125, 0.38301334, 0.38301334),
(0.15625, 0.424369608, 0.424369608),
(0.1875, 0.46666708, 0.46666708),
(0.21875, 0.509635204, 0.509635204),
(0.25, 0.552953156, 0.552953156),
(0.28125, 0.596262162, 0.596262162),
(0.3125, 0.639176211, 0.639176211),
(0.34375, 0.681291281, 0.681291281),
(0.375, 0.722193294, 0.722193294),
(0.40625, 0.761464949, 0.761464949),
(0.4375, 0.798691636, 0.798691636),
(0.46875, 0.833466556, 0.833466556),
(0.5, 0.865395197, 0.865395197),
(0.53125, 0.897787179, 0.897787179),
(0.5625, 0.924127593, 0.924127593),
(0.59375, 0.944468518, 0.944468518),
(0.625, 0.958852946, 0.958852946),
(0.65625, 0.96732803, 0.96732803),
(0.6875, 0.969954137, 0.969954137),
(0.71875, 0.966811177, 0.966811177),
(0.75, 0.958003065, 0.958003065),
(0.78125, 0.943660866, 0.943660866),
(0.8125, 0.923944917, 0.923944917),
(0.84375, 0.89904617, 0.89904617),
(0.875, 0.869186849, 0.869186849),
(0.90625, 0.834620542, 0.834620542),
(0.9375, 0.795631745, 0.795631745),
(0.96875, 0.752534934, 0.752534934),
(1.0, 0.705673158, 0.705673158)],
'green': [
(0.0, 0.298717966, 0.298717966),
(0.03125, 0.353094838, 0.353094838),
(0.0625, 0.406535296, 0.406535296),
(0.09375, 0.458757618, 0.458757618),
(0.125, 0.50941904, 0.50941904),
(0.15625, 0.558148092, 0.558148092),
(0.1875, 0.604562568, 0.604562568),
(0.21875, 0.648280772, 0.648280772),
(0.25, 0.688929332, 0.688929332),
(0.28125, 0.726149107, 0.726149107),
(0.3125, 0.759599947, 0.759599947),
(0.34375, 0.788964712, 0.788964712),
(0.375, 0.813952739, 0.813952739),
(0.40625, 0.834302879, 0.834302879),
(0.4375, 0.849786142, 0.849786142),
(0.46875, 0.860207984, 0.860207984),
(0.5, 0.86541021, 0.86541021),
(0.53125, 0.848937047, 0.848937047),
(0.5625, 0.827384882, 0.827384882),
(0.59375, 0.800927443, 0.800927443),
(0.625, 0.769767752, 0.769767752),
(0.65625, 0.734132809, 0.734132809),
(0.6875, 0.694266682, 0.694266682),
(0.71875, 0.650421156, 0.650421156),
(0.75, 0.602842431, 0.602842431),
(0.78125, 0.551750968, 0.551750968),
(0.8125, 0.49730856, 0.49730856),
(0.84375, 0.439559467, 0.439559467),
(0.875, 0.378313092, 0.378313092),
(0.90625, 0.312874446, 0.312874446),
(0.9375, 0.24128379, 0.24128379),
(0.96875, 0.157246067, 0.157246067),
(1.0, 0.01555616, 0.01555616)],
'blue': [
(0.0, 0.753683153, 0.753683153),
(0.03125, 0.801466763, 0.801466763),
(0.0625, 0.84495867, 0.84495867),
(0.09375, 0.883725899, 0.883725899),
(0.125, 0.917387822, 0.917387822),
(0.15625, 0.945619588, 0.945619588),
(0.1875, 0.968154911, 0.968154911),
(0.21875, 0.98478814, 0.98478814),
(0.25, 0.995375608, 0.995375608),
(0.28125, 0.999836203, 0.999836203),
(0.3125, 0.998151185, 0.998151185),
(0.34375, 0.990363227, 0.990363227),
(0.375, 0.976574709, 0.976574709),
(0.40625, 0.956945269, 0.956945269),
(0.4375, 0.931688648, 0.931688648),
(0.46875, 0.901068838, 0.901068838),
(0.5, 0.865395561, 0.865395561),
(0.53125, 0.820880546, 0.820880546),
(0.5625, 0.774508472, 0.774508472),
(0.59375, 0.726736146, 0.726736146),
(0.625, 0.678007945, 0.678007945),
(0.65625, 0.628751763, 0.628751763),
(0.6875, 0.579375448, 0.579375448),
(0.71875, 0.530263762, 0.530263762),
(0.75, 0.481775914, 0.481775914),
(0.78125, 0.434243684, 0.434243684),
(0.8125, 0.387970225, 0.387970225),
(0.84375, 0.343229596, 0.343229596),
(0.875, 0.300267182, 0.300267182),
(0.90625, 0.259301199, 0.259301199),
(0.9375, 0.220525627, 0.220525627),
(0.96875, 0.184115123, 0.184115123),
(1.0, 0.150232812, 0.150232812)]
}
# Implementation of Carey Rappaport's CMRmap.
# See `A Color Map for Effective Black-and-White Rendering of Color-Scale
# Images' by Carey Rappaport
# http://www.mathworks.com/matlabcentral/fileexchange/2662-cmrmap-m
_CMRmap_data = {'red': ((0.000, 0.00, 0.00),
(0.125, 0.15, 0.15),
(0.250, 0.30, 0.30),
(0.375, 0.60, 0.60),
(0.500, 1.00, 1.00),
(0.625, 0.90, 0.90),
(0.750, 0.90, 0.90),
(0.875, 0.90, 0.90),
(1.000, 1.00, 1.00)),
'green': ((0.000, 0.00, 0.00),
(0.125, 0.15, 0.15),
(0.250, 0.15, 0.15),
(0.375, 0.20, 0.20),
(0.500, 0.25, 0.25),
(0.625, 0.50, 0.50),
(0.750, 0.75, 0.75),
(0.875, 0.90, 0.90),
(1.000, 1.00, 1.00)),
'blue': ((0.000, 0.00, 0.00),
(0.125, 0.50, 0.50),
(0.250, 0.75, 0.75),
(0.375, 0.50, 0.50),
(0.500, 0.15, 0.15),
(0.625, 0.00, 0.00),
(0.750, 0.10, 0.10),
(0.875, 0.50, 0.50),
(1.000, 1.00, 1.00))}
# An MIT licensed, colorblind-friendly heatmap from Wistia:
# https://github.com/wistia/heatmap-palette
# http://wistia.com/blog/heatmaps-for-colorblindness
#
# >>> import matplotlib.colors as c
# >>> colors = ["#e4ff7a", "#ffe81a", "#ffbd00", "#ffa000", "#fc7f00"]
# >>> cm = c.LinearSegmentedColormap.from_list('wistia', colors)
# >>> _wistia_data = cm._segmentdata
# >>> del _wistia_data['alpha']
#
_wistia_data = {
'red': [(0.0, 0.8941176470588236, 0.8941176470588236),
(0.25, 1.0, 1.0),
(0.5, 1.0, 1.0),
(0.75, 1.0, 1.0),
(1.0, 0.9882352941176471, 0.9882352941176471)],
'green': [(0.0, 1.0, 1.0),
(0.25, 0.9098039215686274, 0.9098039215686274),
(0.5, 0.7411764705882353, 0.7411764705882353),
(0.75, 0.6274509803921569, 0.6274509803921569),
(1.0, 0.4980392156862745, 0.4980392156862745)],
'blue': [(0.0, 0.47843137254901963, 0.47843137254901963),
(0.25, 0.10196078431372549, 0.10196078431372549),
(0.5, 0.0, 0.0),
(0.75, 0.0, 0.0),
(1.0, 0.0, 0.0)],
}
# Categorical palettes from Vega:
# https://github.com/vega/vega/wiki/Scales
# (divided by 255)
#
_tab10_data = (
(0.12156862745098039, 0.4666666666666667, 0.7058823529411765 ), # 1f77b4
(1.0, 0.4980392156862745, 0.054901960784313725), # ff7f0e
(0.17254901960784313, 0.6274509803921569, 0.17254901960784313 ), # 2ca02c
(0.8392156862745098, 0.15294117647058825, 0.1568627450980392 ), # d62728
(0.5803921568627451, 0.403921568627451, 0.7411764705882353 ), # 9467bd
(0.5490196078431373, 0.33725490196078434, 0.29411764705882354 ), # 8c564b
(0.8901960784313725, 0.4666666666666667, 0.7607843137254902 ), # e377c2
(0.4980392156862745, 0.4980392156862745, 0.4980392156862745 ), # 7f7f7f
(0.7372549019607844, 0.7411764705882353, 0.13333333333333333 ), # bcbd22
(0.09019607843137255, 0.7450980392156863, 0.8117647058823529), # 17becf
)
_tab20_data = (
(0.12156862745098039, 0.4666666666666667, 0.7058823529411765 ), # 1f77b4
(0.6823529411764706, 0.7803921568627451, 0.9098039215686274 ), # aec7e8
(1.0, 0.4980392156862745, 0.054901960784313725), # ff7f0e
(1.0, 0.7333333333333333, 0.47058823529411764 ), # ffbb78
(0.17254901960784313, 0.6274509803921569, 0.17254901960784313 ), # 2ca02c
(0.596078431372549, 0.8745098039215686, 0.5411764705882353 ), # 98df8a
(0.8392156862745098, 0.15294117647058825, 0.1568627450980392 ), # d62728
(1.0, 0.596078431372549, 0.5882352941176471 ), # ff9896
(0.5803921568627451, 0.403921568627451, 0.7411764705882353 ), # 9467bd
(0.7725490196078432, 0.6901960784313725, 0.8352941176470589 ), # c5b0d5
(0.5490196078431373, 0.33725490196078434, 0.29411764705882354 ), # 8c564b
(0.7686274509803922, 0.611764705882353, 0.5803921568627451 ), # c49c94
(0.8901960784313725, 0.4666666666666667, 0.7607843137254902 ), # e377c2
(0.9686274509803922, 0.7137254901960784, 0.8235294117647058 ), # f7b6d2
(0.4980392156862745, 0.4980392156862745, 0.4980392156862745 ), # 7f7f7f
(0.7803921568627451, 0.7803921568627451, 0.7803921568627451 ), # c7c7c7
(0.7372549019607844, 0.7411764705882353, 0.13333333333333333 ), # bcbd22
(0.8588235294117647, 0.8588235294117647, 0.5529411764705883 ), # dbdb8d
(0.09019607843137255, 0.7450980392156863, 0.8117647058823529 ), # 17becf
(0.6196078431372549, 0.8549019607843137, 0.8980392156862745), # 9edae5
)
_tab20b_data = (
(0.2235294117647059, 0.23137254901960785, 0.4745098039215686 ), # 393b79
(0.3215686274509804, 0.32941176470588235, 0.6392156862745098 ), # 5254a3
(0.4196078431372549, 0.43137254901960786, 0.8117647058823529 ), # 6b6ecf
(0.611764705882353, 0.6196078431372549, 0.8705882352941177 ), # 9c9ede
(0.38823529411764707, 0.4745098039215686, 0.2235294117647059 ), # 637939
(0.5490196078431373, 0.6352941176470588, 0.3215686274509804 ), # 8ca252
(0.7098039215686275, 0.8117647058823529, 0.4196078431372549 ), # b5cf6b
(0.807843137254902, 0.8588235294117647, 0.611764705882353 ), # cedb9c
(0.5490196078431373, 0.42745098039215684, 0.19215686274509805), # 8c6d31
(0.7411764705882353, 0.6196078431372549, 0.2235294117647059 ), # bd9e39
(0.9058823529411765, 0.7294117647058823, 0.3215686274509804 ), # e7ba52
(0.9058823529411765, 0.796078431372549, 0.5803921568627451 ), # e7cb94
(0.5176470588235295, 0.23529411764705882, 0.2235294117647059 ), # 843c39
(0.6784313725490196, 0.28627450980392155, 0.2901960784313726 ), # ad494a
(0.8392156862745098, 0.3803921568627451, 0.4196078431372549 ), # d6616b
(0.9058823529411765, 0.5882352941176471, 0.611764705882353 ), # e7969c
(0.4823529411764706, 0.2549019607843137, 0.45098039215686275), # 7b4173
(0.6470588235294118, 0.3176470588235294, 0.5803921568627451 ), # a55194
(0.807843137254902, 0.42745098039215684, 0.7411764705882353 ), # ce6dbd
(0.8705882352941177, 0.6196078431372549, 0.8392156862745098 ), # de9ed6
)
_tab20c_data = (
(0.19215686274509805, 0.5098039215686274, 0.7411764705882353 ), # 3182bd
(0.4196078431372549, 0.6823529411764706, 0.8392156862745098 ), # 6baed6
(0.6196078431372549, 0.792156862745098, 0.8823529411764706 ), # 9ecae1
(0.7764705882352941, 0.8588235294117647, 0.9372549019607843 ), # c6dbef
(0.9019607843137255, 0.3333333333333333, 0.050980392156862744), # e6550d
(0.9921568627450981, 0.5529411764705883, 0.23529411764705882 ), # fd8d3c
(0.9921568627450981, 0.6823529411764706, 0.4196078431372549 ), # fdae6b
(0.9921568627450981, 0.8156862745098039, 0.6352941176470588 ), # fdd0a2
(0.19215686274509805, 0.6392156862745098, 0.32941176470588235 ), # 31a354
(0.4549019607843137, 0.7686274509803922, 0.4627450980392157 ), # 74c476
(0.6313725490196078, 0.8509803921568627, 0.6078431372549019 ), # a1d99b
(0.7803921568627451, 0.9137254901960784, 0.7529411764705882 ), # c7e9c0
(0.4588235294117647, 0.4196078431372549, 0.6941176470588235 ), # 756bb1
(0.6196078431372549, 0.6039215686274509, 0.7843137254901961 ), # 9e9ac8
(0.7372549019607844, 0.7411764705882353, 0.8627450980392157 ), # bcbddc
(0.8549019607843137, 0.8549019607843137, 0.9215686274509803 ), # dadaeb
(0.38823529411764707, 0.38823529411764707, 0.38823529411764707 ), # 636363
(0.5882352941176471, 0.5882352941176471, 0.5882352941176471 ), # 969696
(0.7411764705882353, 0.7411764705882353, 0.7411764705882353 ), # bdbdbd
(0.8509803921568627, 0.8509803921568627, 0.8509803921568627 ), # d9d9d9
)
datad = {
'Blues': _Blues_data,
'BrBG': _BrBG_data,
'BuGn': _BuGn_data,
'BuPu': _BuPu_data,
'CMRmap': _CMRmap_data,
'GnBu': _GnBu_data,
'Greens': _Greens_data,
'Greys': _Greys_data,
'OrRd': _OrRd_data,
'Oranges': _Oranges_data,
'PRGn': _PRGn_data,
'PiYG': _PiYG_data,
'PuBu': _PuBu_data,
'PuBuGn': _PuBuGn_data,
'PuOr': _PuOr_data,
'PuRd': _PuRd_data,
'Purples': _Purples_data,
'RdBu': _RdBu_data,
'RdGy': _RdGy_data,
'RdPu': _RdPu_data,
'RdYlBu': _RdYlBu_data,
'RdYlGn': _RdYlGn_data,
'Reds': _Reds_data,
'Spectral': _Spectral_data,
'Wistia': _wistia_data,
'YlGn': _YlGn_data,
'YlGnBu': _YlGnBu_data,
'YlOrBr': _YlOrBr_data,
'YlOrRd': _YlOrRd_data,
'afmhot': _afmhot_data,
'autumn': _autumn_data,
'binary': _binary_data,
'bone': _bone_data,
'brg': _brg_data,
'bwr': _bwr_data,
'cool': _cool_data,
'coolwarm': _coolwarm_data,
'copper': _copper_data,
'cubehelix': _cubehelix_data,
'flag': _flag_data,
'gist_earth': _gist_earth_data,
'gist_gray': _gist_gray_data,
'gist_heat': _gist_heat_data,
'gist_ncar': _gist_ncar_data,
'gist_rainbow': _gist_rainbow_data,
'gist_stern': _gist_stern_data,
'gist_yarg': _gist_yarg_data,
'gnuplot': _gnuplot_data,
'gnuplot2': _gnuplot2_data,
'gray': _gray_data,
'hot': _hot_data,
'hsv': _hsv_data,
'jet': _jet_data,
'nipy_spectral': _nipy_spectral_data,
'ocean': _ocean_data,
'pink': _pink_data,
'prism': _prism_data,
'rainbow': _rainbow_data,
'seismic': _seismic_data,
'spring': _spring_data,
'summer': _summer_data,
'terrain': _terrain_data,
'winter': _winter_data,
# Qualitative
'Accent': {'listed': _Accent_data},
'Dark2': {'listed': _Dark2_data},
'Paired': {'listed': _Paired_data},
'Pastel1': {'listed': _Pastel1_data},
'Pastel2': {'listed': _Pastel2_data},
'Set1': {'listed': _Set1_data},
'Set2': {'listed': _Set2_data},
'Set3': {'listed': _Set3_data},
'tab10': {'listed': _tab10_data},
'tab20': {'listed': _tab20_data},
'tab20b': {'listed': _tab20b_data},
'tab20c': {'listed': _tab20c_data},
}
|
535e40207dba33286af2bf7e823920e95d725d057b4519fdbe17624136d7530e
|
"""
:mod:`~matplotlib.gridspec` is a module which specifies the location
of the subplot in the figure.
`GridSpec`
specifies the geometry of the grid that a subplot will be
placed. The number of rows and number of columns of the grid
need to be set. Optionally, the subplot layout parameters
(e.g., left, right, etc.) can be tuned.
`SubplotSpec`
specifies the location of the subplot in the given `GridSpec`.
"""
import copy
import logging
import numpy as np
import matplotlib as mpl
from matplotlib import _pylab_helpers, cbook, tight_layout, rcParams
from matplotlib.transforms import Bbox
import matplotlib._layoutbox as layoutbox
_log = logging.getLogger(__name__)
class GridSpecBase(object):
"""
A base class of GridSpec that specifies the geometry of the grid
that a subplot will be placed.
"""
def __init__(self, nrows, ncols, height_ratios=None, width_ratios=None):
"""
The number of rows and number of columns of the grid need to
be set. Optionally, the ratio of heights and widths of rows and
columns can be specified.
"""
self._nrows, self._ncols = nrows, ncols
self.set_height_ratios(height_ratios)
self.set_width_ratios(width_ratios)
def __repr__(self):
height_arg = (', height_ratios=%r' % self._row_height_ratios
if self._row_height_ratios is not None else '')
width_arg = (', width_ratios=%r' % self._col_width_ratios
if self._col_width_ratios is not None else '')
return '{clsname}({nrows}, {ncols}{optionals})'.format(
clsname=self.__class__.__name__,
nrows=self._nrows,
ncols=self._ncols,
optionals=height_arg + width_arg,
)
def get_geometry(self):
'get the geometry of the grid, e.g., 2,3'
return self._nrows, self._ncols
def get_subplot_params(self, figure=None, fig=None):
pass
def new_subplotspec(self, loc, rowspan=1, colspan=1):
"""
create and return a SubplotSpec instance.
"""
loc1, loc2 = loc
subplotspec = self[loc1:loc1+rowspan, loc2:loc2+colspan]
return subplotspec
def set_width_ratios(self, width_ratios):
if width_ratios is not None and len(width_ratios) != self._ncols:
raise ValueError('Expected the given number of width ratios to '
'match the number of columns of the grid')
self._col_width_ratios = width_ratios
def get_width_ratios(self):
return self._col_width_ratios
def set_height_ratios(self, height_ratios):
if height_ratios is not None and len(height_ratios) != self._nrows:
raise ValueError('Expected the given number of height ratios to '
'match the number of rows of the grid')
self._row_height_ratios = height_ratios
def get_height_ratios(self):
return self._row_height_ratios
def get_grid_positions(self, fig, raw=False):
"""
return lists of bottom and top position of rows, left and
right positions of columns.
If raw=True, then these are all in units relative to the container
with no margins. (used for constrained_layout).
"""
nrows, ncols = self.get_geometry()
if raw:
left = 0.
right = 1.
bottom = 0.
top = 1.
wspace = 0.
hspace = 0.
else:
subplot_params = self.get_subplot_params(fig)
left = subplot_params.left
right = subplot_params.right
bottom = subplot_params.bottom
top = subplot_params.top
wspace = subplot_params.wspace
hspace = subplot_params.hspace
tot_width = right - left
tot_height = top - bottom
# calculate accumulated heights of columns
cell_h = tot_height / (nrows + hspace*(nrows-1))
sep_h = hspace * cell_h
if self._row_height_ratios is not None:
norm = cell_h * nrows / sum(self._row_height_ratios)
cell_heights = [r * norm for r in self._row_height_ratios]
else:
cell_heights = [cell_h] * nrows
sep_heights = [0] + ([sep_h] * (nrows-1))
cell_hs = np.cumsum(np.column_stack([sep_heights, cell_heights]).flat)
# calculate accumulated widths of rows
cell_w = tot_width / (ncols + wspace*(ncols-1))
sep_w = wspace * cell_w
if self._col_width_ratios is not None:
norm = cell_w * ncols / sum(self._col_width_ratios)
cell_widths = [r * norm for r in self._col_width_ratios]
else:
cell_widths = [cell_w] * ncols
sep_widths = [0] + ([sep_w] * (ncols-1))
cell_ws = np.cumsum(np.column_stack([sep_widths, cell_widths]).flat)
fig_tops, fig_bottoms = (top - cell_hs).reshape((-1, 2)).T
fig_lefts, fig_rights = (left + cell_ws).reshape((-1, 2)).T
return fig_bottoms, fig_tops, fig_lefts, fig_rights
def __getitem__(self, key):
"""Create and return a SubplotSpec instance.
"""
nrows, ncols = self.get_geometry()
def _normalize(key, size, axis): # Includes last index.
orig_key = key
if isinstance(key, slice):
start, stop, _ = key.indices(size)
if stop > start:
return start, stop - 1
raise IndexError("GridSpec slice would result in no space "
"allocated for subplot")
else:
if key < 0:
key = key + size
if 0 <= key < size:
return key, key
elif axis is not None:
raise IndexError(f"index {orig_key} is out of bounds for "
f"axis {axis} with size {size}")
else: # flat index
raise IndexError(f"index {orig_key} is out of bounds for "
f"GridSpec with size {size}")
if isinstance(key, tuple):
try:
k1, k2 = key
except ValueError:
raise ValueError("unrecognized subplot spec")
num1, num2 = np.ravel_multi_index(
[_normalize(k1, nrows, 0), _normalize(k2, ncols, 1)],
(nrows, ncols))
else: # Single key
num1, num2 = _normalize(key, nrows * ncols, None)
return SubplotSpec(self, num1, num2)
class GridSpec(GridSpecBase):
"""
A class that specifies the geometry of the grid that a subplot
will be placed. The location of grid is determined by similar way
as the SubplotParams.
"""
def __init__(self, nrows, ncols, figure=None,
left=None, bottom=None, right=None, top=None,
wspace=None, hspace=None,
width_ratios=None, height_ratios=None):
"""
The number of rows and number of columns of the grid need to be set.
Optionally, the subplot layout parameters (e.g., left, right, etc.)
can be tuned.
Parameters
----------
nrows : int
Number of rows in grid.
ncols : int
Number or columns in grid.
figure : `~.figure.Figure`, optional
left, right, top, bottom : float, optional
Extent of the subplots as a fraction of figure width or height.
Left cannot be larger than right, and bottom cannot be larger than
top.
wspace : float, optional
The amount of width reserved for space between subplots,
expressed as a fraction of the average axis width.
hspace : float, optional
The amount of height reserved for space between subplots,
expressed as a fraction of the average axis height.
width_ratios : length *ncols* iterable, optional
Width ratios of the columns.
height_ratios : length *nrows* iterable, optional
Height ratios of the rows.
Notes
-----
See `~.figure.SubplotParams` for descriptions of the layout parameters.
"""
self.left = left
self.bottom = bottom
self.right = right
self.top = top
self.wspace = wspace
self.hspace = hspace
self.figure = figure
GridSpecBase.__init__(self, nrows, ncols,
width_ratios=width_ratios,
height_ratios=height_ratios)
if self.figure is None or not self.figure.get_constrained_layout():
self._layoutbox = None
else:
self.figure.init_layoutbox()
self._layoutbox = layoutbox.LayoutBox(
parent=self.figure._layoutbox,
name='gridspec' + layoutbox.seq_id(),
artist=self)
# by default the layoutbox for a gridspec will fill a figure.
# but this can change below if the gridspec is created from a
# subplotspec. (GridSpecFromSubplotSpec)
_AllowedKeys = ["left", "bottom", "right", "top", "wspace", "hspace"]
def __getstate__(self):
state = self.__dict__
try:
state.pop('_layoutbox')
except KeyError:
pass
return state
def __setstate__(self, state):
self.__dict__ = state
# layoutboxes don't survive pickling...
self._layoutbox = None
def update(self, **kwargs):
"""
Update the current values.
Values set to None use the rcParams value.
"""
for k, v in kwargs.items():
if k in self._AllowedKeys:
setattr(self, k, v)
else:
raise AttributeError(f"{k} is an unknown keyword")
for figmanager in _pylab_helpers.Gcf.figs.values():
for ax in figmanager.canvas.figure.axes:
# copied from Figure.subplots_adjust
if not isinstance(ax, mpl.axes.SubplotBase):
# Check if sharing a subplots axis
if isinstance(ax._sharex, mpl.axes.SubplotBase):
if ax._sharex.get_subplotspec().get_gridspec() == self:
ax._sharex.update_params()
ax._set_position(ax._sharex.figbox)
elif isinstance(ax._sharey, mpl.axes.SubplotBase):
if ax._sharey.get_subplotspec().get_gridspec() == self:
ax._sharey.update_params()
ax._set_position(ax._sharey.figbox)
else:
ss = ax.get_subplotspec().get_topmost_subplotspec()
if ss.get_gridspec() == self:
ax.update_params()
ax._set_position(ax.figbox)
def get_subplot_params(self, figure=None):
"""
Return a dictionary of subplot layout parameters. The default
parameters are from rcParams unless a figure attribute is set.
"""
if figure is None:
kw = {k: rcParams["figure.subplot."+k] for k in self._AllowedKeys}
subplotpars = mpl.figure.SubplotParams(**kw)
else:
subplotpars = copy.copy(figure.subplotpars)
subplotpars.update(**{k: getattr(self, k) for k in self._AllowedKeys})
return subplotpars
def locally_modified_subplot_params(self):
return [k for k in self._AllowedKeys if getattr(self, k)]
def tight_layout(self, figure, renderer=None,
pad=1.08, h_pad=None, w_pad=None, rect=None):
"""
Adjust subplot parameters to give specified padding.
Parameters
----------
pad : float
Padding between the figure edge and the edges of subplots, as a
fraction of the font-size.
h_pad, w_pad : float, optional
Padding (height/width) between edges of adjacent subplots.
Defaults to ``pad_inches``.
rect : tuple of 4 floats, optional
(left, bottom, right, top) rectangle in normalized figure
coordinates that the whole subplots area (including labels) will
fit into. Default is (0, 0, 1, 1).
"""
subplotspec_list = tight_layout.get_subplotspec_list(
figure.axes, grid_spec=self)
if None in subplotspec_list:
cbook._warn_external("This figure includes Axes that are not "
"compatible with tight_layout, so results "
"might be incorrect.")
if renderer is None:
renderer = tight_layout.get_renderer(figure)
kwargs = tight_layout.get_tight_layout_figure(
figure, figure.axes, subplotspec_list, renderer,
pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect)
if kwargs:
self.update(**kwargs)
class GridSpecFromSubplotSpec(GridSpecBase):
"""
GridSpec whose subplot layout parameters are inherited from the
location specified by a given SubplotSpec.
"""
def __init__(self, nrows, ncols,
subplot_spec,
wspace=None, hspace=None,
height_ratios=None, width_ratios=None):
"""
The number of rows and number of columns of the grid need to
be set. An instance of SubplotSpec is also needed to be set
from which the layout parameters will be inherited. The wspace
and hspace of the layout can be optionally specified or the
default values (from the figure or rcParams) will be used.
"""
self._wspace = wspace
self._hspace = hspace
self._subplot_spec = subplot_spec
GridSpecBase.__init__(self, nrows, ncols,
width_ratios=width_ratios,
height_ratios=height_ratios)
# do the layoutboxes
subspeclb = subplot_spec._layoutbox
if subspeclb is None:
self._layoutbox = None
else:
# OK, this is needed to divide the figure.
self._layoutbox = subspeclb.layout_from_subplotspec(
subplot_spec,
name=subspeclb.name + '.gridspec' + layoutbox.seq_id(),
artist=self)
def get_subplot_params(self, figure=None):
"""Return a dictionary of subplot layout parameters.
"""
hspace = (self._hspace if self._hspace is not None
else figure.subplotpars.hspace if figure is not None
else rcParams["figure.subplot.hspace"])
wspace = (self._wspace if self._wspace is not None
else figure.subplotpars.wspace if figure is not None
else rcParams["figure.subplot.wspace"])
figbox = self._subplot_spec.get_position(figure)
left, bottom, right, top = figbox.extents
return mpl.figure.SubplotParams(left=left, right=right,
bottom=bottom, top=top,
wspace=wspace, hspace=hspace)
def get_topmost_subplotspec(self):
"""Get the topmost SubplotSpec instance associated with the subplot."""
return self._subplot_spec.get_topmost_subplotspec()
class SubplotSpec(object):
"""Specifies the location of the subplot in the given `GridSpec`.
"""
def __init__(self, gridspec, num1, num2=None):
"""
The subplot will occupy the num1-th cell of the given
gridspec. If num2 is provided, the subplot will span between
num1-th cell and num2-th cell *inclusive*.
The index starts from 0.
"""
self._gridspec = gridspec
self.num1 = num1
self.num2 = num2
if gridspec._layoutbox is not None:
glb = gridspec._layoutbox
# So note that here we don't assign any layout yet,
# just make the layoutbox that will contain all items
# associated w/ this axis. This can include other axes like
# a colorbar or a legend.
self._layoutbox = layoutbox.LayoutBox(
parent=glb,
name=glb.name + '.ss' + layoutbox.seq_id(),
artist=self)
else:
self._layoutbox = None
# num2 is a property only to handle the case where it is None and someone
# mutates num1.
@property
def num2(self):
return self.num1 if self._num2 is None else self._num2
@num2.setter
def num2(self, value):
self._num2 = value
def __getstate__(self):
state = self.__dict__
try:
state.pop('_layoutbox')
except KeyError:
pass
return state
def __setstate__(self, state):
self.__dict__ = state
# layoutboxes don't survive pickling...
self._layoutbox = None
def get_gridspec(self):
return self._gridspec
def get_geometry(self):
"""
Get the subplot geometry (``n_rows, n_cols, start, stop``).
start and stop are the index of the start and stop of the
subplot.
"""
rows, cols = self.get_gridspec().get_geometry()
return rows, cols, self.num1, self.num2
def get_rows_columns(self):
"""
Get the subplot row and column numbers:
(``n_rows, n_cols, row_start, row_stop, col_start, col_stop``)
"""
gridspec = self.get_gridspec()
nrows, ncols = gridspec.get_geometry()
row_start, col_start = divmod(self.num1, ncols)
row_stop, col_stop = divmod(self.num2, ncols)
return nrows, ncols, row_start, row_stop, col_start, col_stop
def get_position(self, figure, return_all=False):
"""Update the subplot position from ``figure.subplotpars``.
"""
gridspec = self.get_gridspec()
nrows, ncols = gridspec.get_geometry()
rows, cols = np.unravel_index([self.num1, self.num2], (nrows, ncols))
fig_bottoms, fig_tops, fig_lefts, fig_rights = \
gridspec.get_grid_positions(figure)
fig_bottom = fig_bottoms[rows].min()
fig_top = fig_tops[rows].max()
fig_left = fig_lefts[cols].min()
fig_right = fig_rights[cols].max()
figbox = Bbox.from_extents(fig_left, fig_bottom, fig_right, fig_top)
if return_all:
return figbox, rows[0], cols[0], nrows, ncols
else:
return figbox
def get_topmost_subplotspec(self):
'get the topmost SubplotSpec instance associated with the subplot'
gridspec = self.get_gridspec()
if hasattr(gridspec, "get_topmost_subplotspec"):
return gridspec.get_topmost_subplotspec()
else:
return self
def __eq__(self, other):
# other may not even have the attributes we are checking.
return ((self._gridspec, self.num1, self.num2)
== (getattr(other, "_gridspec", object()),
getattr(other, "num1", object()),
getattr(other, "num2", object())))
def __hash__(self):
return hash((self._gridspec, self.num1, self.num2))
def subgridspec(self, nrows, ncols, **kwargs):
"""
Return a `.GridSpecFromSubplotSpec` that has this subplotspec as
a parent.
Parameters
----------
nrows : int
Number of rows in grid.
ncols : int
Number or columns in grid.
Returns
-------
gridspec : `.GridSpec`
Other Parameters
----------------
**kwargs
All other parameters are passed to `.GridSpec`.
See Also
--------
matplotlib.pyplot.subplots
Examples
--------
Adding three subplots in the space occupied by a single subplot::
fig = plt.figure()
gs0 = fig.add_gridspec(3, 1)
ax1 = fig.add_subplot(gs0[0])
ax2 = fig.add_subplot(gs0[1])
gssub = gs0[2].subgridspec(1, 3)
for i in range(3):
fig.add_subplot(gssub[0, i])
"""
return GridSpecFromSubplotSpec(nrows, ncols, self, **kwargs)
|
4836874771883bca61c5bffdb85bcae3f4724bf95d80198ecefa7a1d5928626a
|
"""
Classes for including text in a figure.
"""
import contextlib
import logging
import math
import weakref
import numpy as np
from . import artist, cbook, docstring, rcParams
from .artist import Artist
from .font_manager import FontProperties
from .lines import Line2D
from .patches import FancyArrowPatch, FancyBboxPatch, Rectangle
from .textpath import TextPath # Unused, but imported by others.
from .transforms import (
Affine2D, Bbox, BboxBase, BboxTransformTo, IdentityTransform, Transform)
_log = logging.getLogger(__name__)
@contextlib.contextmanager
def _wrap_text(textobj):
"""Temporarily inserts newlines to the text if the wrap option is enabled.
"""
if textobj.get_wrap():
old_text = textobj.get_text()
try:
textobj.set_text(textobj._get_wrapped_text())
yield textobj
finally:
textobj.set_text(old_text)
else:
yield textobj
# Extracted from Text's method to serve as a function
def get_rotation(rotation):
"""
Return the text angle as float between 0 and 360 degrees.
*rotation* may be 'horizontal', 'vertical', or a numeric value in degrees.
"""
try:
return float(rotation) % 360
except (ValueError, TypeError):
if cbook._str_equal(rotation, 'horizontal') or rotation is None:
return 0.
elif cbook._str_equal(rotation, 'vertical'):
return 90.
else:
raise ValueError("rotation is {!r}; expected either 'horizontal', "
"'vertical', numeric value, or None"
.format(rotation))
def _get_textbox(text, renderer):
"""
Calculate the bounding box of the text. Unlike
:meth:`matplotlib.text.Text.get_extents` method, The bbox size of
the text before the rotation is calculated.
"""
# TODO : This function may move into the Text class as a method. As a
# matter of fact, The information from the _get_textbox function
# should be available during the Text._get_layout() call, which is
# called within the _get_textbox. So, it would better to move this
# function as a method with some refactoring of _get_layout method.
projected_xs = []
projected_ys = []
theta = np.deg2rad(text.get_rotation())
tr = Affine2D().rotate(-theta)
_, parts, d = text._get_layout(renderer)
for t, wh, x, y in parts:
w, h = wh
xt1, yt1 = tr.transform_point((x, y))
yt1 -= d
xt2, yt2 = xt1 + w, yt1 + h
projected_xs.extend([xt1, xt2])
projected_ys.extend([yt1, yt2])
xt_box, yt_box = min(projected_xs), min(projected_ys)
w_box, h_box = max(projected_xs) - xt_box, max(projected_ys) - yt_box
x_box, y_box = Affine2D().rotate(theta).transform_point((xt_box, yt_box))
return x_box, y_box, w_box, h_box
@cbook._define_aliases({
"color": ["c"],
"fontfamily": ["family"],
"fontproperties": ["font_properties"],
"horizontalalignment": ["ha"],
"multialignment": ["ma"],
"fontname": ["name"],
"fontsize": ["size"],
"fontstretch": ["stretch"],
"fontstyle": ["style"],
"fontvariant": ["variant"],
"verticalalignment": ["va"],
"fontweight": ["weight"],
})
class Text(Artist):
"""Handle storing and drawing of text in window or data coordinates."""
zorder = 3
_cached = cbook.maxdict(50)
def __repr__(self):
return "Text(%s, %s, %s)" % (self._x, self._y, repr(self._text))
def __init__(self,
x=0, y=0, text='',
color=None, # defaults to rc params
verticalalignment='baseline',
horizontalalignment='left',
multialignment=None,
fontproperties=None, # defaults to FontProperties()
rotation=None,
linespacing=None,
rotation_mode=None,
usetex=None, # defaults to rcParams['text.usetex']
wrap=False,
**kwargs
):
"""
Create a `.Text` instance at *x*, *y* with string *text*.
Valid kwargs are
%(Text)s
"""
Artist.__init__(self)
self._x, self._y = x, y
if color is None:
color = rcParams['text.color']
if fontproperties is None:
fontproperties = FontProperties()
elif isinstance(fontproperties, str):
fontproperties = FontProperties(fontproperties)
self._text = ''
self.set_text(text)
self.set_color(color)
self.set_usetex(usetex)
self.set_wrap(wrap)
self.set_verticalalignment(verticalalignment)
self.set_horizontalalignment(horizontalalignment)
self._multialignment = multialignment
self._rotation = rotation
self._fontproperties = fontproperties
self._bbox_patch = None # a FancyBboxPatch instance
self._renderer = None
if linespacing is None:
linespacing = 1.2 # Maybe use rcParam later.
self._linespacing = linespacing
self.set_rotation_mode(rotation_mode)
self.update(kwargs)
def update(self, kwargs):
"""
Update properties from a dictionary.
"""
# Update bbox last, as it depends on font properties.
sentinel = object() # bbox can be None, so use another sentinel.
bbox = kwargs.pop("bbox", sentinel)
super().update(kwargs)
if bbox is not sentinel:
self.set_bbox(bbox)
def __getstate__(self):
d = super().__getstate__()
# remove the cached _renderer (if it exists)
d['_renderer'] = None
return d
def contains(self, mouseevent):
"""Test whether the mouse event occurred in the patch.
In the case of text, a hit is true anywhere in the
axis-aligned bounding-box containing the text.
Returns
-------
bool : bool
"""
if self._contains is not None:
return self._contains(self, mouseevent)
if not self.get_visible() or self._renderer is None:
return False, {}
l, b, w, h = self.get_window_extent().bounds
r, t = l + w, b + h
x, y = mouseevent.x, mouseevent.y
inside = (l <= x <= r and b <= y <= t)
cattr = {}
# if the text has a surrounding patch, also check containment for it,
# and merge the results with the results for the text.
if self._bbox_patch:
patch_inside, patch_cattr = self._bbox_patch.contains(mouseevent)
inside = inside or patch_inside
cattr["bbox_patch"] = patch_cattr
return inside, cattr
def _get_xy_display(self):
"""
Get the (possibly unit converted) transformed x, y in display coords.
"""
x, y = self.get_unitless_position()
return self.get_transform().transform_point((x, y))
def _get_multialignment(self):
if self._multialignment is not None:
return self._multialignment
else:
return self._horizontalalignment
def get_rotation(self):
"""Return the text angle as float in degrees."""
return get_rotation(self._rotation) # string_or_number -> number
def set_rotation_mode(self, m):
"""
Set text rotation mode.
Parameters
----------
m : {None, 'default', 'anchor'}
If ``None`` or ``"default"``, the text will be first rotated, then
aligned according to their horizontal and vertical alignments. If
``"anchor"``, then alignment occurs before rotation.
"""
if m is None or m in ["anchor", "default"]:
self._rotation_mode = m
else:
raise ValueError("Unknown rotation_mode : %s" % repr(m))
self.stale = True
def get_rotation_mode(self):
"""Get the text rotation mode."""
return self._rotation_mode
def update_from(self, other):
"""Copy properties from other to self."""
Artist.update_from(self, other)
self._color = other._color
self._multialignment = other._multialignment
self._verticalalignment = other._verticalalignment
self._horizontalalignment = other._horizontalalignment
self._fontproperties = other._fontproperties.copy()
self._rotation = other._rotation
self._picker = other._picker
self._linespacing = other._linespacing
self.stale = True
def _get_layout(self, renderer):
"""
return the extent (bbox) of the text together with
multiple-alignment information. Note that it returns an extent
of a rotated text when necessary.
"""
key = self.get_prop_tup(renderer=renderer)
if key in self._cached:
return self._cached[key]
thisx, thisy = 0.0, 0.0
lines = self.get_text().split("\n") # Ensures lines is not empty.
ws = []
hs = []
xs = []
ys = []
# Full vertical extent of font, including ascenders and descenders:
_, lp_h, lp_d = renderer.get_text_width_height_descent(
"lp", self._fontproperties,
ismath="TeX" if self.get_usetex() else False)
min_dy = (lp_h - lp_d) * self._linespacing
for i, line in enumerate(lines):
clean_line, ismath = self._preprocess_math(line)
if clean_line:
w, h, d = renderer.get_text_width_height_descent(
clean_line, self._fontproperties, ismath=ismath)
else:
w = h = d = 0
# For multiline text, increase the line spacing when the text
# net-height (excluding baseline) is larger than that of a "l"
# (e.g., use of superscripts), which seems what TeX does.
h = max(h, lp_h)
d = max(d, lp_d)
ws.append(w)
hs.append(h)
# Metrics of the last line that are needed later:
baseline = (h - d) - thisy
if i == 0:
# position at baseline
thisy = -(h - d)
else:
# put baseline a good distance from bottom of previous line
thisy -= max(min_dy, (h - d) * self._linespacing)
xs.append(thisx) # == 0.
ys.append(thisy)
thisy -= d
# Metrics of the last line that are needed later:
descent = d
# Bounding box definition:
width = max(ws)
xmin = 0
xmax = width
ymax = 0
ymin = ys[-1] - descent # baseline of last line minus its descent
height = ymax - ymin
# get the rotation matrix
M = Affine2D().rotate_deg(self.get_rotation())
# now offset the individual text lines within the box
malign = self._get_multialignment()
if malign == 'left':
offset_layout = [(x, y) for x, y in zip(xs, ys)]
elif malign == 'center':
offset_layout = [(x + width / 2 - w / 2, y)
for x, y, w in zip(xs, ys, ws)]
elif malign == 'right':
offset_layout = [(x + width - w, y)
for x, y, w in zip(xs, ys, ws)]
# the corners of the unrotated bounding box
corners_horiz = np.array(
[(xmin, ymin), (xmin, ymax), (xmax, ymax), (xmax, ymin)])
# now rotate the bbox
corners_rotated = M.transform(corners_horiz)
# compute the bounds of the rotated box
xmin = corners_rotated[:, 0].min()
xmax = corners_rotated[:, 0].max()
ymin = corners_rotated[:, 1].min()
ymax = corners_rotated[:, 1].max()
width = xmax - xmin
height = ymax - ymin
# Now move the box to the target position offset the display
# bbox by alignment
halign = self._horizontalalignment
valign = self._verticalalignment
rotation_mode = self.get_rotation_mode()
if rotation_mode != "anchor":
# compute the text location in display coords and the offsets
# necessary to align the bbox with that location
if halign == 'center':
offsetx = (xmin + xmax) / 2
elif halign == 'right':
offsetx = xmax
else:
offsetx = xmin
if valign == 'center':
offsety = (ymin + ymax) / 2
elif valign == 'top':
offsety = ymax
elif valign == 'baseline':
offsety = ymin + descent
elif valign == 'center_baseline':
offsety = ymin + height - baseline / 2.0
else:
offsety = ymin
else:
xmin1, ymin1 = corners_horiz[0]
xmax1, ymax1 = corners_horiz[2]
if halign == 'center':
offsetx = (xmin1 + xmax1) / 2.0
elif halign == 'right':
offsetx = xmax1
else:
offsetx = xmin1
if valign == 'center':
offsety = (ymin1 + ymax1) / 2.0
elif valign == 'top':
offsety = ymax1
elif valign == 'baseline':
offsety = ymax1 - baseline
elif valign == 'center_baseline':
offsety = ymax1 - baseline / 2.0
else:
offsety = ymin1
offsetx, offsety = M.transform_point((offsetx, offsety))
xmin -= offsetx
ymin -= offsety
bbox = Bbox.from_bounds(xmin, ymin, width, height)
# now rotate the positions around the first x,y position
xys = M.transform(offset_layout) - (offsetx, offsety)
ret = bbox, list(zip(lines, zip(ws, hs), *xys.T)), descent
self._cached[key] = ret
return ret
def set_bbox(self, rectprops):
"""
Draw a bounding box around self.
Parameters
----------
rectprops : dict with properties for `.patches.FancyBboxPatch`
The default boxstyle is 'square'. The mutation
scale of the `.patches.FancyBboxPatch` is set to the fontsize.
Examples
--------
::
t.set_bbox(dict(facecolor='red', alpha=0.5))
"""
if rectprops is not None:
props = rectprops.copy()
boxstyle = props.pop("boxstyle", None)
pad = props.pop("pad", None)
if boxstyle is None:
boxstyle = "square"
if pad is None:
pad = 4 # points
pad /= self.get_size() # to fraction of font size
else:
if pad is None:
pad = 0.3
# boxstyle could be a callable or a string
if isinstance(boxstyle, str) and "pad" not in boxstyle:
boxstyle += ",pad=%0.2f" % pad
bbox_transmuter = props.pop("bbox_transmuter", None)
self._bbox_patch = FancyBboxPatch(
(0., 0.),
1., 1.,
boxstyle=boxstyle,
bbox_transmuter=bbox_transmuter,
transform=IdentityTransform(),
**props)
else:
self._bbox_patch = None
self._update_clip_properties()
def get_bbox_patch(self):
"""
Return the bbox Patch, or None if the `.patches.FancyBboxPatch`
is not made.
"""
return self._bbox_patch
def update_bbox_position_size(self, renderer):
"""
Update the location and the size of the bbox.
This method should be used when the position and size of the bbox needs
to be updated before actually drawing the bbox.
"""
if self._bbox_patch:
trans = self.get_transform()
# don't use self.get_unitless_position here, which refers to text
# position in Text, and dash position in TextWithDash:
posx = float(self.convert_xunits(self._x))
posy = float(self.convert_yunits(self._y))
posx, posy = trans.transform_point((posx, posy))
x_box, y_box, w_box, h_box = _get_textbox(self, renderer)
self._bbox_patch.set_bounds(0., 0., w_box, h_box)
theta = np.deg2rad(self.get_rotation())
tr = Affine2D().rotate(theta)
tr = tr.translate(posx + x_box, posy + y_box)
self._bbox_patch.set_transform(tr)
fontsize_in_pixel = renderer.points_to_pixels(self.get_size())
self._bbox_patch.set_mutation_scale(fontsize_in_pixel)
def _draw_bbox(self, renderer, posx, posy):
"""
Update the location and size of the bbox (`.patches.FancyBboxPatch`),
and draw.
"""
x_box, y_box, w_box, h_box = _get_textbox(self, renderer)
self._bbox_patch.set_bounds(0., 0., w_box, h_box)
theta = np.deg2rad(self.get_rotation())
tr = Affine2D().rotate(theta)
tr = tr.translate(posx + x_box, posy + y_box)
self._bbox_patch.set_transform(tr)
fontsize_in_pixel = renderer.points_to_pixels(self.get_size())
self._bbox_patch.set_mutation_scale(fontsize_in_pixel)
self._bbox_patch.draw(renderer)
def _update_clip_properties(self):
clipprops = dict(clip_box=self.clipbox,
clip_path=self._clippath,
clip_on=self._clipon)
if self._bbox_patch:
self._bbox_patch.update(clipprops)
def set_clip_box(self, clipbox):
# docstring inherited.
super().set_clip_box(clipbox)
self._update_clip_properties()
def set_clip_path(self, path, transform=None):
# docstring inherited.
super().set_clip_path(path, transform)
self._update_clip_properties()
def set_clip_on(self, b):
# docstring inherited.
super().set_clip_on(b)
self._update_clip_properties()
def get_wrap(self):
"""Return the wrapping state for the text."""
return self._wrap
def set_wrap(self, wrap):
"""Set the wrapping state for the text.
Parameters
----------
wrap : bool
"""
self._wrap = wrap
def _get_wrap_line_width(self):
"""
Return the maximum line width for wrapping text based on the current
orientation.
"""
x0, y0 = self.get_transform().transform(self.get_position())
figure_box = self.get_figure().get_window_extent()
# Calculate available width based on text alignment
alignment = self.get_horizontalalignment()
self.set_rotation_mode('anchor')
rotation = self.get_rotation()
left = self._get_dist_to_box(rotation, x0, y0, figure_box)
right = self._get_dist_to_box(
(180 + rotation) % 360, x0, y0, figure_box)
if alignment == 'left':
line_width = left
elif alignment == 'right':
line_width = right
else:
line_width = 2 * min(left, right)
return line_width
def _get_dist_to_box(self, rotation, x0, y0, figure_box):
"""
Return the distance from the given points to the boundaries of a
rotated box, in pixels.
"""
if rotation > 270:
quad = rotation - 270
h1 = y0 / math.cos(math.radians(quad))
h2 = (figure_box.x1 - x0) / math.cos(math.radians(90 - quad))
elif rotation > 180:
quad = rotation - 180
h1 = x0 / math.cos(math.radians(quad))
h2 = y0 / math.cos(math.radians(90 - quad))
elif rotation > 90:
quad = rotation - 90
h1 = (figure_box.y1 - y0) / math.cos(math.radians(quad))
h2 = x0 / math.cos(math.radians(90 - quad))
else:
h1 = (figure_box.x1 - x0) / math.cos(math.radians(rotation))
h2 = (figure_box.y1 - y0) / math.cos(math.radians(90 - rotation))
return min(h1, h2)
def _get_rendered_text_width(self, text):
"""
Return the width of a given text string, in pixels.
"""
w, h, d = self._renderer.get_text_width_height_descent(
text,
self.get_fontproperties(),
False)
return math.ceil(w)
def _get_wrapped_text(self):
"""
Return a copy of the text with new lines added, so that
the text is wrapped relative to the parent figure.
"""
# Not fit to handle breaking up latex syntax correctly, so
# ignore latex for now.
if self.get_usetex():
return self.get_text()
# Build the line incrementally, for a more accurate measure of length
line_width = self._get_wrap_line_width()
wrapped_str = ""
line = ""
for word in self.get_text().split(' '):
# New lines in the user's test need to force a split, so that it's
# not using the longest current line width in the line being built
sub_words = word.split('\n')
for i in range(len(sub_words)):
current_width = self._get_rendered_text_width(
line + ' ' + sub_words[i])
# Split long lines, and each newline found in the current word
if current_width > line_width or i > 0:
wrapped_str += line + '\n'
line = ""
if line == "":
line = sub_words[i]
else:
line += ' ' + sub_words[i]
return wrapped_str + line
@artist.allow_rasterization
def draw(self, renderer):
"""
Draws the `.Text` object to the given *renderer*.
"""
if renderer is not None:
self._renderer = renderer
if not self.get_visible():
return
if self.get_text() == '':
return
renderer.open_group('text', self.get_gid())
with _wrap_text(self) as textobj:
bbox, info, descent = textobj._get_layout(renderer)
trans = textobj.get_transform()
# don't use textobj.get_position here, which refers to text
# position in Text, and dash position in TextWithDash:
posx = float(textobj.convert_xunits(textobj._x))
posy = float(textobj.convert_yunits(textobj._y))
posx, posy = trans.transform_point((posx, posy))
if not np.isfinite(posx) or not np.isfinite(posy):
_log.warning("posx and posy should be finite values")
return
canvasw, canvash = renderer.get_canvas_width_height()
# draw the FancyBboxPatch
if textobj._bbox_patch:
textobj._draw_bbox(renderer, posx, posy)
gc = renderer.new_gc()
gc.set_foreground(textobj.get_color())
gc.set_alpha(textobj.get_alpha())
gc.set_url(textobj._url)
textobj._set_gc_clip(gc)
angle = textobj.get_rotation()
for line, wh, x, y in info:
mtext = textobj if len(info) == 1 else None
x = x + posx
y = y + posy
if renderer.flipy():
y = canvash - y
clean_line, ismath = textobj._preprocess_math(line)
if textobj.get_path_effects():
from matplotlib.patheffects import PathEffectRenderer
textrenderer = PathEffectRenderer(
textobj.get_path_effects(), renderer)
else:
textrenderer = renderer
if textobj.get_usetex():
textrenderer.draw_tex(gc, x, y, clean_line,
textobj._fontproperties, angle,
mtext=mtext)
else:
textrenderer.draw_text(gc, x, y, clean_line,
textobj._fontproperties, angle,
ismath=ismath, mtext=mtext)
gc.restore()
renderer.close_group('text')
self.stale = False
def get_color(self):
"Return the color of the text"
return self._color
def get_fontproperties(self):
"Return the `.font_manager.FontProperties` object"
return self._fontproperties
def get_fontfamily(self):
"""
Return the list of font families used for font lookup
See Also
--------
.font_manager.FontProperties.get_family
"""
return self._fontproperties.get_family()
def get_fontname(self):
"""
Return the font name as string
See Also
--------
.font_manager.FontProperties.get_name
"""
return self._fontproperties.get_name()
def get_fontstyle(self):
"""
Return the font style as string
See Also
--------
.font_manager.FontProperties.get_style
"""
return self._fontproperties.get_style()
def get_fontsize(self):
"""
Return the font size as integer
See Also
--------
.font_manager.FontProperties.get_size_in_points
"""
return self._fontproperties.get_size_in_points()
def get_fontvariant(self):
"""
Return the font variant as a string
See Also
--------
.font_manager.FontProperties.get_variant
"""
return self._fontproperties.get_variant()
def get_fontweight(self):
"""
Get the font weight as string or number
See Also
--------
.font_manager.FontProperties.get_weight
"""
return self._fontproperties.get_weight()
def get_stretch(self):
"""
Get the font stretch as a string or number
See Also
--------
.font_manager.FontProperties.get_stretch
"""
return self._fontproperties.get_stretch()
def get_horizontalalignment(self):
"""
Return the horizontal alignment as string. Will be one of
'left', 'center' or 'right'.
"""
return self._horizontalalignment
def get_unitless_position(self):
"Return the unitless position of the text as a tuple (*x*, *y*)"
# This will get the position with all unit information stripped away.
# This is here for convenience since it is done in several locations.
x = float(self.convert_xunits(self._x))
y = float(self.convert_yunits(self._y))
return x, y
def get_position(self):
"Return the position of the text as a tuple (*x*, *y*)"
# This should return the same data (possible unitized) as was
# specified with 'set_x' and 'set_y'.
return self._x, self._y
def get_prop_tup(self, renderer=None):
"""
Return a hashable tuple of properties.
Not intended to be human readable, but useful for backends who
want to cache derived information about text (e.g., layouts) and
need to know if the text has changed.
"""
x, y = self.get_unitless_position()
renderer = renderer or self._renderer
return (x, y, self.get_text(), self._color,
self._verticalalignment, self._horizontalalignment,
hash(self._fontproperties),
self._rotation, self._rotation_mode,
self.figure.dpi, weakref.ref(renderer),
self._linespacing
)
def get_text(self):
"Get the text as string"
return self._text
def get_verticalalignment(self):
"""
Return the vertical alignment as string. Will be one of
'top', 'center', 'bottom' or 'baseline'.
"""
return self._verticalalignment
def get_window_extent(self, renderer=None, dpi=None):
"""
Return the `Bbox` bounding the text, in display units.
In addition to being used internally, this is useful for specifying
clickable regions in a png file on a web page.
Parameters
----------
renderer : Renderer, optional
A renderer is needed to compute the bounding box. If the artist
has already been drawn, the renderer is cached; thus, it is only
necessary to pass this argument when calling `get_window_extent`
before the first `draw`. In practice, it is usually easier to
trigger a draw first (e.g. by saving the figure).
dpi : float, optional
The dpi value for computing the bbox, defaults to
``self.figure.dpi`` (*not* the renderer dpi); should be set e.g. if
to match regions with a figure saved with a custom dpi value.
"""
#return _unit_box
if not self.get_visible():
return Bbox.unit()
if dpi is not None:
dpi_orig = self.figure.dpi
self.figure.dpi = dpi
if self.get_text() == '':
tx, ty = self._get_xy_display()
return Bbox.from_bounds(tx, ty, 0, 0)
if renderer is not None:
self._renderer = renderer
if self._renderer is None:
self._renderer = self.figure._cachedRenderer
if self._renderer is None:
raise RuntimeError('Cannot get window extent w/o renderer')
bbox, info, descent = self._get_layout(self._renderer)
x, y = self.get_unitless_position()
x, y = self.get_transform().transform_point((x, y))
bbox = bbox.translated(x, y)
if dpi is not None:
self.figure.dpi = dpi_orig
return bbox
def set_backgroundcolor(self, color):
"""
Set the background color of the text by updating the bbox.
Parameters
----------
color : color
See Also
--------
.set_bbox : To change the position of the bounding box
"""
if self._bbox_patch is None:
self.set_bbox(dict(facecolor=color, edgecolor=color))
else:
self._bbox_patch.update(dict(facecolor=color))
self._update_clip_properties()
self.stale = True
def set_color(self, color):
"""
Set the foreground color of the text
Parameters
----------
color : color
"""
# Make sure it is hashable, or get_prop_tup will fail.
try:
hash(color)
except TypeError:
color = tuple(color)
self._color = color
self.stale = True
def set_horizontalalignment(self, align):
"""
Set the horizontal alignment to one of
Parameters
----------
align : {'center', 'right', 'left'}
"""
cbook._check_in_list(['center', 'right', 'left'], align=align)
self._horizontalalignment = align
self.stale = True
def set_multialignment(self, align):
"""
Set the alignment for multiple lines layout. The layout of the
bounding box of all the lines is determined bu the horizontalalignment
and verticalalignment properties, but the multiline text within that
box can be
Parameters
----------
align : {'left', 'right', 'center'}
"""
cbook._check_in_list(['center', 'right', 'left'], align=align)
self._multialignment = align
self.stale = True
def set_linespacing(self, spacing):
"""
Set the line spacing as a multiple of the font size.
Default is 1.2.
Parameters
----------
spacing : float (multiple of font size)
"""
self._linespacing = spacing
self.stale = True
def set_fontfamily(self, fontname):
"""
Set the font family. May be either a single string, or a list of
strings in decreasing priority. Each string may be either a real font
name or a generic font class name. If the latter, the specific font
names will be looked up in the corresponding rcParams.
If a `Text` instance is constructed with ``fontfamily=None``, then the
font is set to :rc:`font.family`, and the
same is done when `set_fontfamily()` is called on an existing
`Text` instance.
Parameters
----------
fontname : {FONTNAME, 'serif', 'sans-serif', 'cursive', 'fantasy', \
'monospace'}
See Also
--------
.font_manager.FontProperties.set_family
"""
self._fontproperties.set_family(fontname)
self.stale = True
def set_fontvariant(self, variant):
"""
Set the font variant, either 'normal' or 'small-caps'.
Parameters
----------
variant : {'normal', 'small-caps'}
See Also
--------
.font_manager.FontProperties.set_variant
"""
self._fontproperties.set_variant(variant)
self.stale = True
def set_fontstyle(self, fontstyle):
"""
Set the font style.
Parameters
----------
fontstyle : {'normal', 'italic', 'oblique'}
See Also
--------
.font_manager.FontProperties.set_style
"""
self._fontproperties.set_style(fontstyle)
self.stale = True
def set_fontsize(self, fontsize):
"""
Set the font size. May be either a size string, relative to
the default font size, or an absolute font size in points.
Parameters
----------
fontsize : {size in points, 'xx-small', 'x-small', 'small', 'medium', \
'large', 'x-large', 'xx-large'}
See Also
--------
.font_manager.FontProperties.set_size
"""
self._fontproperties.set_size(fontsize)
self.stale = True
def set_fontweight(self, weight):
"""
Set the font weight.
Parameters
----------
weight : {a numeric value in range 0-1000, 'ultralight', 'light', \
'normal', 'regular', 'book', 'medium', 'roman', 'semibold', 'demibold', \
'demi', 'bold', 'heavy', 'extra bold', 'black'}
See Also
--------
.font_manager.FontProperties.set_weight
"""
self._fontproperties.set_weight(weight)
self.stale = True
def set_fontstretch(self, stretch):
"""
Set the font stretch (horizontal condensation or expansion).
Parameters
----------
stretch : {a numeric value in range 0-1000, 'ultra-condensed', \
'extra-condensed', 'condensed', 'semi-condensed', 'normal', 'semi-expanded', \
'expanded', 'extra-expanded', 'ultra-expanded'}
See Also
--------
.font_manager.FontProperties.set_stretch
"""
self._fontproperties.set_stretch(stretch)
self.stale = True
def set_position(self, xy):
"""
Set the (*x*, *y*) position of the text.
Parameters
----------
xy : (float, float)
"""
self.set_x(xy[0])
self.set_y(xy[1])
def set_x(self, x):
"""
Set the *x* position of the text.
Parameters
----------
x : float
"""
self._x = x
self.stale = True
def set_y(self, y):
"""
Set the *y* position of the text.
Parameters
----------
y : float
"""
self._y = y
self.stale = True
def set_rotation(self, s):
"""
Set the rotation of the text.
Parameters
----------
s : {angle in degrees, 'vertical', 'horizontal'}
"""
self._rotation = s
self.stale = True
def set_verticalalignment(self, align):
"""
Set the vertical alignment
Parameters
----------
align : {'center', 'top', 'bottom', 'baseline', 'center_baseline'}
"""
cbook._check_in_list(
['top', 'bottom', 'center', 'baseline', 'center_baseline'],
align=align)
self._verticalalignment = align
self.stale = True
def set_text(self, s):
"""
Set the text string *s*.
It may contain newlines (``\\n``) or math in LaTeX syntax.
Parameters
----------
s : object
Any object gets converted to its `str`, except ``None`` which
becomes ``''``.
"""
if s is None:
s = ''
if s != self._text:
self._text = str(s)
self.stale = True
@staticmethod
@cbook.deprecated("3.1")
def is_math_text(s, usetex=None):
"""
Returns a cleaned string and a boolean flag.
The flag indicates if the given string *s* contains any mathtext,
determined by counting unescaped dollar signs. If no mathtext
is present, the cleaned string has its dollar signs unescaped.
If usetex is on, the flag always has the value "TeX".
"""
# Did we find an even number of non-escaped dollar signs?
# If so, treat is as math text.
if usetex is None:
usetex = rcParams['text.usetex']
if usetex:
if s == ' ':
s = r'\ '
return s, 'TeX'
if cbook.is_math_text(s):
return s, True
else:
return s.replace(r'\$', '$'), False
def _preprocess_math(self, s):
"""
Return the string *s* after mathtext preprocessing, and the kind of
mathtext support needed.
- If *self* is configured to use TeX, return *s* unchanged except that
a single space gets escaped, and the flag "TeX".
- Otherwise, if *s* is mathtext (has an even number of unescaped dollar
signs), return *s* and the flag True.
- Otherwise, return *s* with dollar signs unescaped, and the flag
False.
"""
if self.get_usetex():
if s == " ":
s = r"\ "
return s, "TeX"
elif cbook.is_math_text(s):
return s, True
else:
return s.replace(r"\$", "$"), False
def set_fontproperties(self, fp):
"""
Set the font properties that control the text.
Parameters
----------
fp : `.font_manager.FontProperties`
"""
if isinstance(fp, str):
fp = FontProperties(fp)
self._fontproperties = fp.copy()
self.stale = True
def set_usetex(self, usetex):
"""
Parameters
----------
usetex : bool or None
Whether to render using TeX, ``None`` means to use
:rc:`text.usetex`.
"""
if usetex is None:
self._usetex = rcParams['text.usetex']
else:
self._usetex = bool(usetex)
self.stale = True
def get_usetex(self):
"""Return whether this `Text` object uses TeX for rendering."""
return self._usetex
def set_fontname(self, fontname):
"""
Alias for `set_family`.
One-way alias only: the getter differs.
Parameters
----------
fontname : {FONTNAME, 'serif', 'sans-serif', 'cursive', 'fantasy', \
'monospace'}
See Also
--------
.font_manager.FontProperties.set_family
"""
return self.set_family(fontname)
docstring.interpd.update(Text=artist.kwdoc(Text))
docstring.dedent_interpd(Text.__init__)
@cbook.deprecated("3.1", alternative="Annotation")
class TextWithDash(Text):
"""
This is basically a :class:`~matplotlib.text.Text` with a dash
(drawn with a :class:`~matplotlib.lines.Line2D`) before/after
it. It is intended to be a drop-in replacement for
:class:`~matplotlib.text.Text`, and should behave identically to
it when *dashlength* = 0.0.
The dash always comes between the point specified by
:meth:`~matplotlib.text.Text.set_position` and the text. When a
dash exists, the text alignment arguments (*horizontalalignment*,
*verticalalignment*) are ignored.
*dashlength* is the length of the dash in canvas units.
(default = 0.0).
*dashdirection* is one of 0 or 1, where 0 draws the dash after the
text and 1 before. (default = 0).
*dashrotation* specifies the rotation of the dash, and should
generally stay *None*. In this case
:meth:`~matplotlib.text.TextWithDash.get_dashrotation` returns
:meth:`~matplotlib.text.Text.get_rotation`. (i.e., the dash takes
its rotation from the text's rotation). Because the text center is
projected onto the dash, major deviations in the rotation cause
what may be considered visually unappealing results.
(default = *None*)
*dashpad* is a padding length to add (or subtract) space
between the text and the dash, in canvas units.
(default = 3)
*dashpush* "pushes" the dash and text away from the point
specified by :meth:`~matplotlib.text.Text.set_position` by the
amount in canvas units. (default = 0)
.. note::
The alignment of the two objects is based on the bounding box
of the :class:`~matplotlib.text.Text`, as obtained by
:meth:`~matplotlib.artist.Artist.get_window_extent`. This, in
turn, appears to depend on the font metrics as given by the
rendering backend. Hence the quality of the "centering" of the
label text with respect to the dash varies depending on the
backend used.
.. note::
I'm not sure that I got the
:meth:`~matplotlib.text.TextWithDash.get_window_extent` right,
or whether that's sufficient for providing the object bounding
box.
"""
__name__ = 'textwithdash'
def __str__(self):
return "TextWithDash(%g, %g, %r)" % (self._x, self._y, self._text)
def __init__(self,
x=0, y=0, text='',
color=None, # defaults to rc params
verticalalignment='center',
horizontalalignment='center',
multialignment=None,
fontproperties=None, # defaults to FontProperties()
rotation=None,
linespacing=None,
dashlength=0.0,
dashdirection=0,
dashrotation=None,
dashpad=3,
dashpush=0,
):
Text.__init__(self, x=x, y=y, text=text, color=color,
verticalalignment=verticalalignment,
horizontalalignment=horizontalalignment,
multialignment=multialignment,
fontproperties=fontproperties,
rotation=rotation,
linespacing=linespacing,
)
# The position (x,y) values for text and dashline
# are bogus as given in the instantiation; they will
# be set correctly by update_coords() in draw()
self.dashline = Line2D(xdata=(x, x),
ydata=(y, y),
color='k',
linestyle='-')
self._dashx = float(x)
self._dashy = float(y)
self._dashlength = dashlength
self._dashdirection = dashdirection
self._dashrotation = dashrotation
self._dashpad = dashpad
self._dashpush = dashpush
#self.set_bbox(dict(pad=0))
def get_unitless_position(self):
"Return the unitless position of the text as a tuple (*x*, *y*)"
# This will get the position with all unit information stripped away.
# This is here for convenience since it is done in several locations.
x = float(self.convert_xunits(self._dashx))
y = float(self.convert_yunits(self._dashy))
return x, y
def get_position(self):
"Return the position of the text as a tuple (*x*, *y*)"
# This should return the same data (possibly unitized) as was
# specified with set_x and set_y
return self._dashx, self._dashy
def get_prop_tup(self, renderer=None):
"""
Return a hashable tuple of properties.
Not intended to be human readable, but useful for backends who
want to cache derived information about text (e.g., layouts) and
need to know if the text has changed.
"""
props = [p for p in Text.get_prop_tup(self, renderer=renderer)]
props.extend([self._x, self._y, self._dashlength,
self._dashdirection, self._dashrotation, self._dashpad,
self._dashpush])
return tuple(props)
def draw(self, renderer):
"""
Draw the :class:`TextWithDash` object to the given *renderer*.
"""
self.update_coords(renderer)
Text.draw(self, renderer)
if self.get_dashlength() > 0.0:
self.dashline.draw(renderer)
self.stale = False
def update_coords(self, renderer):
"""
Computes the actual *x*, *y* coordinates for text based on the
input *x*, *y* and the *dashlength*. Since the rotation is
with respect to the actual canvas's coordinates we need to map
back and forth.
"""
dashx, dashy = self.get_unitless_position()
dashlength = self.get_dashlength()
# Shortcircuit this process if we don't have a dash
if dashlength == 0.0:
self._x, self._y = dashx, dashy
return
dashrotation = self.get_dashrotation()
dashdirection = self.get_dashdirection()
dashpad = self.get_dashpad()
dashpush = self.get_dashpush()
angle = get_rotation(dashrotation)
theta = np.pi * (angle / 180.0 + dashdirection - 1)
cos_theta, sin_theta = np.cos(theta), np.sin(theta)
transform = self.get_transform()
# Compute the dash end points
# The 'c' prefix is for canvas coordinates
cxy = transform.transform_point((dashx, dashy))
cd = np.array([cos_theta, sin_theta])
c1 = cxy + dashpush * cd
c2 = cxy + (dashpush + dashlength) * cd
inverse = transform.inverted()
(x1, y1) = inverse.transform_point(tuple(c1))
(x2, y2) = inverse.transform_point(tuple(c2))
self.dashline.set_data((x1, x2), (y1, y2))
# We now need to extend this vector out to
# the center of the text area.
# The basic problem here is that we're "rotating"
# two separate objects but want it to appear as
# if they're rotated together.
# This is made non-trivial because of the
# interaction between text rotation and alignment -
# text alignment is based on the bbox after rotation.
# We reset/force both alignments to 'center'
# so we can do something relatively reasonable.
# There's probably a better way to do this by
# embedding all this in the object's transformations,
# but I don't grok the transformation stuff
# well enough yet.
we = Text.get_window_extent(self, renderer=renderer)
w, h = we.width, we.height
# Watch for zeros
if sin_theta == 0.0:
dx = w
dy = 0.0
elif cos_theta == 0.0:
dx = 0.0
dy = h
else:
tan_theta = sin_theta / cos_theta
dx = w
dy = w * tan_theta
if dy > h or dy < -h:
dy = h
dx = h / tan_theta
cwd = np.array([dx, dy]) / 2
cwd *= 1 + dashpad / np.sqrt(np.dot(cwd, cwd))
cw = c2 + (dashdirection * 2 - 1) * cwd
newx, newy = inverse.transform_point(tuple(cw))
self._x, self._y = newx, newy
# Now set the window extent
# I'm not at all sure this is the right way to do this.
we = Text.get_window_extent(self, renderer=renderer)
self._twd_window_extent = we.frozen()
self._twd_window_extent.update_from_data_xy(np.array([c1]), False)
# Finally, make text align center
Text.set_horizontalalignment(self, 'center')
Text.set_verticalalignment(self, 'center')
def get_window_extent(self, renderer=None):
'''
Return a :class:`~matplotlib.transforms.Bbox` object bounding
the text, in display units.
In addition to being used internally, this is useful for
specifying clickable regions in a png file on a web page.
*renderer* defaults to the _renderer attribute of the text
object. This is not assigned until the first execution of
:meth:`draw`, so you must use this kwarg if you want
to call :meth:`get_window_extent` prior to the first
:meth:`draw`. For getting web page regions, it is
simpler to call the method after saving the figure.
'''
self.update_coords(renderer)
if self.get_dashlength() == 0.0:
return Text.get_window_extent(self, renderer=renderer)
else:
return self._twd_window_extent
def get_dashlength(self):
"""
Get the length of the dash.
"""
return self._dashlength
def set_dashlength(self, dl):
"""
Set the length of the dash, in canvas units.
Parameters
----------
dl : float
"""
self._dashlength = dl
self.stale = True
def get_dashdirection(self):
"""
Get the direction dash. 1 is before the text and 0 is after.
"""
return self._dashdirection
def set_dashdirection(self, dd):
"""
Set the direction of the dash following the text. 1 is before the text
and 0 is after. The default is 0, which is what you'd want for the
typical case of ticks below and on the left of the figure.
Parameters
----------
dd : int (1 is before, 0 is after)
"""
self._dashdirection = dd
self.stale = True
def get_dashrotation(self):
"""
Get the rotation of the dash in degrees.
"""
if self._dashrotation is None:
return self.get_rotation()
else:
return self._dashrotation
def set_dashrotation(self, dr):
"""
Set the rotation of the dash, in degrees.
Parameters
----------
dr : float
"""
self._dashrotation = dr
self.stale = True
def get_dashpad(self):
"""
Get the extra spacing between the dash and the text, in canvas units.
"""
return self._dashpad
def set_dashpad(self, dp):
"""
Set the "pad" of the TextWithDash, which is the extra spacing
between the dash and the text, in canvas units.
Parameters
----------
dp : float
"""
self._dashpad = dp
self.stale = True
def get_dashpush(self):
"""
Get the extra spacing between the dash and the specified text
position, in canvas units.
"""
return self._dashpush
def set_dashpush(self, dp):
"""
Set the "push" of the TextWithDash, which is the extra spacing between
the beginning of the dash and the specified position.
Parameters
----------
dp : float
"""
self._dashpush = dp
self.stale = True
def set_position(self, xy):
"""
Set the (*x*, *y*) position of the :class:`TextWithDash`.
Parameters
----------
xy : (float, float)
"""
self.set_x(xy[0])
self.set_y(xy[1])
def set_x(self, x):
"""
Set the *x* position of the :class:`TextWithDash`.
Parameters
----------
x : float
"""
self._dashx = float(x)
self.stale = True
def set_y(self, y):
"""
Set the *y* position of the :class:`TextWithDash`.
Parameters
----------
y : float
"""
self._dashy = float(y)
self.stale = True
def set_transform(self, t):
"""
Set the :class:`matplotlib.transforms.Transform` instance used
by this artist.
Parameters
----------
t : matplotlib.transforms.Transform
"""
Text.set_transform(self, t)
self.dashline.set_transform(t)
self.stale = True
def get_figure(self):
'return the figure instance the artist belongs to'
return self.figure
def set_figure(self, fig):
"""
Set the figure instance the artist belongs to.
Parameters
----------
fig : matplotlib.figure.Figure
"""
Text.set_figure(self, fig)
self.dashline.set_figure(fig)
docstring.interpd.update(TextWithDash=artist.kwdoc(TextWithDash))
class OffsetFrom(object):
'Callable helper class for working with `Annotation`'
def __init__(self, artist, ref_coord, unit="points"):
'''
Parameters
----------
artist : `Artist`, `BboxBase`, or `Transform`
The object to compute the offset from.
ref_coord : length 2 sequence
If `artist` is an `Artist` or `BboxBase`, this values is
the location to of the offset origin in fractions of the
`artist` bounding box.
If `artist` is a transform, the offset origin is the
transform applied to this value.
unit : {'points, 'pixels'}
The screen units to use (pixels or points) for the offset
input.
'''
self._artist = artist
self._ref_coord = ref_coord
self.set_unit(unit)
def set_unit(self, unit):
'''
The unit for input to the transform used by ``__call__``
Parameters
----------
unit : {'points', 'pixels'}
'''
cbook._check_in_list(["points", "pixels"], unit=unit)
self._unit = unit
def get_unit(self):
'The unit for input to the transform used by ``__call__``'
return self._unit
def _get_scale(self, renderer):
unit = self.get_unit()
if unit == "pixels":
return 1.
else:
return renderer.points_to_pixels(1.)
def __call__(self, renderer):
'''
Return the offset transform.
Parameters
----------
renderer : `RendererBase`
The renderer to use to compute the offset
Returns
-------
transform : `Transform`
Maps (x, y) in pixel or point units to screen units
relative to the given artist.
'''
if isinstance(self._artist, Artist):
bbox = self._artist.get_window_extent(renderer)
l, b, w, h = bbox.bounds
xf, yf = self._ref_coord
x, y = l + w * xf, b + h * yf
elif isinstance(self._artist, BboxBase):
l, b, w, h = self._artist.bounds
xf, yf = self._ref_coord
x, y = l + w * xf, b + h * yf
elif isinstance(self._artist, Transform):
x, y = self._artist.transform_point(self._ref_coord)
else:
raise RuntimeError("unknown type")
sc = self._get_scale(renderer)
tr = Affine2D().scale(sc, sc).translate(x, y)
return tr
class _AnnotationBase(object):
def __init__(self,
xy,
xycoords='data',
annotation_clip=None):
self.xy = xy
self.xycoords = xycoords
self.set_annotation_clip(annotation_clip)
self._draggable = None
def _get_xy(self, renderer, x, y, s):
if isinstance(s, tuple):
s1, s2 = s
else:
s1, s2 = s, s
if s1 == 'data':
x = float(self.convert_xunits(x))
if s2 == 'data':
y = float(self.convert_yunits(y))
tr = self._get_xy_transform(renderer, s)
x1, y1 = tr.transform_point((x, y))
return x1, y1
def _get_xy_transform(self, renderer, s):
if isinstance(s, tuple):
s1, s2 = s
from matplotlib.transforms import blended_transform_factory
tr1 = self._get_xy_transform(renderer, s1)
tr2 = self._get_xy_transform(renderer, s2)
tr = blended_transform_factory(tr1, tr2)
return tr
elif callable(s):
tr = s(renderer)
if isinstance(tr, BboxBase):
return BboxTransformTo(tr)
elif isinstance(tr, Transform):
return tr
else:
raise RuntimeError("unknown return type ...")
elif isinstance(s, Artist):
bbox = s.get_window_extent(renderer)
return BboxTransformTo(bbox)
elif isinstance(s, BboxBase):
return BboxTransformTo(s)
elif isinstance(s, Transform):
return s
elif not isinstance(s, str):
raise RuntimeError("unknown coordinate type : %s" % s)
if s == 'data':
return self.axes.transData
elif s == 'polar':
from matplotlib.projections import PolarAxes
tr = PolarAxes.PolarTransform()
trans = tr + self.axes.transData
return trans
s_ = s.split()
if len(s_) != 2:
raise ValueError("%s is not a recognized coordinate" % s)
bbox0, xy0 = None, None
bbox_name, unit = s_
# if unit is offset-like
if bbox_name == "figure":
bbox0 = self.figure.bbox
elif bbox_name == "axes":
bbox0 = self.axes.bbox
# elif bbox_name == "bbox":
# if bbox is None:
# raise RuntimeError("bbox is specified as a coordinate but "
# "never set")
# bbox0 = self._get_bbox(renderer, bbox)
if bbox0 is not None:
xy0 = bbox0.bounds[:2]
elif bbox_name == "offset":
xy0 = self._get_ref_xy(renderer)
if xy0 is not None:
# reference x, y in display coordinate
ref_x, ref_y = xy0
from matplotlib.transforms import Affine2D
if unit == "points":
# dots per points
dpp = self.figure.get_dpi() / 72.
tr = Affine2D().scale(dpp, dpp)
elif unit == "pixels":
tr = Affine2D()
elif unit == "fontsize":
fontsize = self.get_size()
dpp = fontsize * self.figure.get_dpi() / 72.
tr = Affine2D().scale(dpp, dpp)
elif unit == "fraction":
w, h = bbox0.bounds[2:]
tr = Affine2D().scale(w, h)
else:
raise ValueError("%s is not a recognized coordinate" % s)
return tr.translate(ref_x, ref_y)
else:
raise ValueError("%s is not a recognized coordinate" % s)
def _get_ref_xy(self, renderer):
"""
return x, y (in display coordinate) that is to be used for a reference
of any offset coordinate
"""
def is_offset(s):
return isinstance(s, str) and s.split()[0] == "offset"
if isinstance(self.xycoords, tuple):
s1, s2 = self.xycoords
if is_offset(s1) or is_offset(s2):
raise ValueError("xycoords should not be an offset coordinate")
x, y = self.xy
x1, y1 = self._get_xy(renderer, x, y, s1)
x2, y2 = self._get_xy(renderer, x, y, s2)
return x1, y2
elif is_offset(self.xycoords):
raise ValueError("xycoords should not be an offset coordinate")
else:
x, y = self.xy
return self._get_xy(renderer, x, y, self.xycoords)
#raise RuntimeError("must be defined by the derived class")
# def _get_bbox(self, renderer):
# if hasattr(bbox, "bounds"):
# return bbox
# elif hasattr(bbox, "get_window_extent"):
# bbox = bbox.get_window_extent()
# return bbox
# else:
# raise ValueError("A bbox instance is expected but got %s" %
# str(bbox))
def set_annotation_clip(self, b):
"""
set *annotation_clip* attribute.
* True: the annotation will only be drawn when self.xy is inside
the axes.
* False: the annotation will always be drawn regardless of its
position.
* None: the self.xy will be checked only if *xycoords* is "data"
"""
self._annotation_clip = b
def get_annotation_clip(self):
"""
Return *annotation_clip* attribute.
See :meth:`set_annotation_clip` for the meaning of return values.
"""
return self._annotation_clip
def _get_position_xy(self, renderer):
"Return the pixel position of the annotated point."
x, y = self.xy
return self._get_xy(renderer, x, y, self.xycoords)
def _check_xy(self, renderer, xy_pixel):
"""
given the xy pixel coordinate, check if the annotation need to
be drawn.
"""
b = self.get_annotation_clip()
if b or (b is None and self.xycoords == "data"):
# check if self.xy is inside the axes.
if not self.axes.contains_point(xy_pixel):
return False
return True
def draggable(self, state=None, use_blit=False):
"""
Set the draggable state -- if state is
* None : toggle the current state
* True : turn draggable on
* False : turn draggable off
If draggable is on, you can drag the annotation on the canvas with
the mouse. The DraggableAnnotation helper instance is returned if
draggable is on.
"""
from matplotlib.offsetbox import DraggableAnnotation
is_draggable = self._draggable is not None
# if state is None we'll toggle
if state is None:
state = not is_draggable
if state:
if self._draggable is None:
self._draggable = DraggableAnnotation(self, use_blit)
else:
if self._draggable is not None:
self._draggable.disconnect()
self._draggable = None
return self._draggable
class Annotation(Text, _AnnotationBase):
"""
An `.Annotation` is a `.Text` that can refer to a specific position *xy*.
Optionally an arrow pointing from the text to *xy* can be drawn.
Attributes
----------
xy
The annotated position.
xycoords
The coordinate system for *xy*.
arrow_patch
A `.FancyArrowPatch` to point from *xytext* to *xy*.
"""
def __str__(self):
return "Annotation(%g, %g, %r)" % (self.xy[0], self.xy[1], self._text)
@cbook._rename_parameter("3.1", "s", "text")
def __init__(self, text, xy,
xytext=None,
xycoords='data',
textcoords=None,
arrowprops=None,
annotation_clip=None,
**kwargs):
"""
Annotate the point *xy* with text *text*.
In the simplest form, the text is placed at *xy*.
Optionally, the text can be displayed in another position *xytext*.
An arrow pointing from the text to the annotated point *xy* can then
be added by defining *arrowprops*.
Parameters
----------
text : str
The text of the annotation. *s* is a deprecated synonym for this
parameter.
xy : (float, float)
The point *(x,y)* to annotate.
xytext : (float, float), optional
The position *(x,y)* to place the text at.
If *None*, defaults to *xy*.
xycoords : str, `.Artist`, `.Transform`, callable or tuple, optional
The coordinate system that *xy* is given in. The following types
of values are supported:
- One of the following strings:
================= =============================================
Value Description
================= =============================================
'figure points' Points from the lower left of the figure
'figure pixels' Pixels from the lower left of the figure
'figure fraction' Fraction of figure from lower left
'axes points' Points from lower left corner of axes
'axes pixels' Pixels from lower left corner of axes
'axes fraction' Fraction of axes from lower left
'data' Use the coordinate system of the object being
annotated (default)
'polar' *(theta,r)* if not native 'data' coordinates
================= =============================================
- An `.Artist`: *xy* is interpreted as a fraction of the artists
`~matplotlib.transforms.Bbox`. E.g. *(0, 0)* would be the lower
left corner of the bounding box and *(0.5, 1)* would be the
center top of the bounding box.
- A `.Transform` to transform *xy* to screen coordinates.
- A function with one of the following signatures::
def transform(renderer) -> Bbox
def transform(renderer) -> Transform
where *renderer* is a `.RendererBase` subclass.
The result of the function is interpreted like the `.Artist` and
`.Transform` cases above.
- A tuple *(xcoords, ycoords)* specifying separate coordinate
systems for *x* and *y*. *xcoords* and *ycoords* must each be
of one of the above described types.
See :ref:`plotting-guide-annotation` for more details.
Defaults to 'data'.
textcoords : str, `.Artist`, `.Transform`, callable or tuple, optional
The coordinate system that *xytext* is given in.
All *xycoords* values are valid as well as the following
strings:
================= =========================================
Value Description
================= =========================================
'offset points' Offset (in points) from the *xy* value
'offset pixels' Offset (in pixels) from the *xy* value
================= =========================================
Defaults to the value of *xycoords*, i.e. use the same coordinate
system for annotation point and text position.
arrowprops : dict, optional
The properties used to draw a
`~matplotlib.patches.FancyArrowPatch` arrow between the
positions *xy* and *xytext*.
If *arrowprops* does not contain the key 'arrowstyle' the
allowed keys are:
========== ======================================================
Key Description
========== ======================================================
width The width of the arrow in points
headwidth The width of the base of the arrow head in points
headlength The length of the arrow head in points
shrink Fraction of total length to shrink from both ends
? Any key to :class:`matplotlib.patches.FancyArrowPatch`
========== ======================================================
If *arrowprops* contains the key 'arrowstyle' the
above keys are forbidden. The allowed values of
``'arrowstyle'`` are:
============ =============================================
Name Attrs
============ =============================================
``'-'`` None
``'->'`` head_length=0.4,head_width=0.2
``'-['`` widthB=1.0,lengthB=0.2,angleB=None
``'|-|'`` widthA=1.0,widthB=1.0
``'-|>'`` head_length=0.4,head_width=0.2
``'<-'`` head_length=0.4,head_width=0.2
``'<->'`` head_length=0.4,head_width=0.2
``'<|-'`` head_length=0.4,head_width=0.2
``'<|-|>'`` head_length=0.4,head_width=0.2
``'fancy'`` head_length=0.4,head_width=0.4,tail_width=0.4
``'simple'`` head_length=0.5,head_width=0.5,tail_width=0.2
``'wedge'`` tail_width=0.3,shrink_factor=0.5
============ =============================================
Valid keys for `~matplotlib.patches.FancyArrowPatch` are:
=============== ==================================================
Key Description
=============== ==================================================
arrowstyle the arrow style
connectionstyle the connection style
relpos default is (0.5, 0.5)
patchA default is bounding box of the text
patchB default is None
shrinkA default is 2 points
shrinkB default is 2 points
mutation_scale default is text size (in points)
mutation_aspect default is 1.
? any key for :class:`matplotlib.patches.PathPatch`
=============== ==================================================
Defaults to None, i.e. no arrow is drawn.
annotation_clip : bool or None, optional
Whether to draw the annotation when the annotation point *xy* is
outside the axes area.
- If *True*, the annotation will only be drawn when *xy* is
within the axes.
- If *False*, the annotation will always be drawn.
- If *None*, the annotation will only be drawn when *xy* is
within the axes and *xycoords* is 'data'.
Defaults to *None*.
**kwargs
Additional kwargs are passed to `~matplotlib.text.Text`.
Returns
-------
annotation : `.Annotation`
See Also
--------
:ref:`plotting-guide-annotation`.
"""
_AnnotationBase.__init__(self,
xy,
xycoords=xycoords,
annotation_clip=annotation_clip)
# warn about wonky input data
if (xytext is None and
textcoords is not None and
textcoords != xycoords):
cbook._warn_external("You have used the `textcoords` kwarg, but "
"not the `xytext` kwarg. This can lead to "
"surprising results.")
# clean up textcoords and assign default
if textcoords is None:
textcoords = self.xycoords
self._textcoords = textcoords
# cleanup xytext defaults
if xytext is None:
xytext = self.xy
x, y = xytext
Text.__init__(self, x, y, text, **kwargs)
self.arrowprops = arrowprops
if arrowprops is not None:
if "arrowstyle" in arrowprops:
arrowprops = self.arrowprops.copy()
self._arrow_relpos = arrowprops.pop("relpos", (0.5, 0.5))
else:
# modified YAArrow API to be used with FancyArrowPatch
shapekeys = ('width', 'headwidth', 'headlength',
'shrink', 'frac')
arrowprops = dict()
for key, val in self.arrowprops.items():
if key not in shapekeys:
arrowprops[key] = val # basic Patch properties
self.arrow_patch = FancyArrowPatch((0, 0), (1, 1),
**arrowprops)
else:
self.arrow_patch = None
def contains(self, event):
contains, tinfo = Text.contains(self, event)
if self.arrow_patch is not None:
in_patch, _ = self.arrow_patch.contains(event)
contains = contains or in_patch
return contains, tinfo
@property
def xyann(self):
"""
The the text position.
See also *xytext* in `.Annotation`.
"""
return self.get_position()
@xyann.setter
def xyann(self, xytext):
self.set_position(xytext)
@property
def anncoords(self):
"""The coordinate system to use for `.Annotation.xyann`."""
return self._textcoords
@anncoords.setter
def anncoords(self, coords):
self._textcoords = coords
get_anncoords = anncoords.fget
get_anncoords.__doc__ = """
Return the coordinate system to use for `.Annotation.xyann`.
See also *xycoords* in `.Annotation`.
"""
set_anncoords = anncoords.fset
set_anncoords.__doc__ = """
Set the coordinate system to use for `.Annotation.xyann`.
See also *xycoords* in `.Annotation`.
"""
def set_figure(self, fig):
if self.arrow_patch is not None:
self.arrow_patch.set_figure(fig)
Artist.set_figure(self, fig)
def update_positions(self, renderer):
"""Update the pixel positions of the annotated point and the text."""
xy_pixel = self._get_position_xy(renderer)
self._update_position_xytext(renderer, xy_pixel)
def _update_position_xytext(self, renderer, xy_pixel):
"""
Update the pixel positions of the annotation text and the arrow patch.
"""
# generate transformation,
self.set_transform(self._get_xy_transform(renderer, self.anncoords))
ox0, oy0 = self._get_xy_display()
ox1, oy1 = xy_pixel
if self.arrowprops is not None:
x0, y0 = xy_pixel
l, b, w, h = Text.get_window_extent(self, renderer).bounds
r = l + w
t = b + h
xc = 0.5 * (l + r)
yc = 0.5 * (b + t)
d = self.arrowprops.copy()
ms = d.pop("mutation_scale", self.get_size())
self.arrow_patch.set_mutation_scale(ms)
if "arrowstyle" not in d:
# Approximately simulate the YAArrow.
# Pop its kwargs:
shrink = d.pop('shrink', 0.0)
width = d.pop('width', 4)
headwidth = d.pop('headwidth', 12)
# Ignore frac--it is useless.
frac = d.pop('frac', None)
if frac is not None:
cbook._warn_external(
"'frac' option in 'arrowprops' is no longer supported;"
" use 'headlength' to set the head length in points.")
headlength = d.pop('headlength', 12)
# NB: ms is in pts
stylekw = dict(head_length=headlength / ms,
head_width=headwidth / ms,
tail_width=width / ms)
self.arrow_patch.set_arrowstyle('simple', **stylekw)
# using YAArrow style:
# pick the x,y corner of the text bbox closest to point
# annotated
xpos = ((l, 0), (xc, 0.5), (r, 1))
ypos = ((b, 0), (yc, 0.5), (t, 1))
_, (x, relposx) = min((abs(val[0] - x0), val) for val in xpos)
_, (y, relposy) = min((abs(val[0] - y0), val) for val in ypos)
self._arrow_relpos = (relposx, relposy)
r = np.hypot((y - y0), (x - x0))
shrink_pts = shrink * r / renderer.points_to_pixels(1)
self.arrow_patch.shrinkA = shrink_pts
self.arrow_patch.shrinkB = shrink_pts
# adjust the starting point of the arrow relative to
# the textbox.
# TODO : Rotation needs to be accounted.
relpos = self._arrow_relpos
bbox = Text.get_window_extent(self, renderer)
ox0 = bbox.x0 + bbox.width * relpos[0]
oy0 = bbox.y0 + bbox.height * relpos[1]
# The arrow will be drawn from (ox0, oy0) to (ox1,
# oy1). It will be first clipped by patchA and patchB.
# Then it will be shrunk by shrinkA and shrinkB
# (in points). If patch A is not set, self.bbox_patch
# is used.
self.arrow_patch.set_positions((ox0, oy0), (ox1, oy1))
if "patchA" in d:
self.arrow_patch.set_patchA(d.pop("patchA"))
else:
if self._bbox_patch:
self.arrow_patch.set_patchA(self._bbox_patch)
else:
pad = renderer.points_to_pixels(4)
if self.get_text() == "":
self.arrow_patch.set_patchA(None)
return
bbox = Text.get_window_extent(self, renderer)
l, b, w, h = bbox.bounds
l -= pad / 2.
b -= pad / 2.
w += pad
h += pad
r = Rectangle(xy=(l, b),
width=w,
height=h,
)
r.set_transform(IdentityTransform())
r.set_clip_on(False)
self.arrow_patch.set_patchA(r)
@artist.allow_rasterization
def draw(self, renderer):
"""
Draw the :class:`Annotation` object to the given *renderer*.
"""
if renderer is not None:
self._renderer = renderer
if not self.get_visible():
return
xy_pixel = self._get_position_xy(renderer)
if not self._check_xy(renderer, xy_pixel):
return
self._update_position_xytext(renderer, xy_pixel)
self.update_bbox_position_size(renderer)
if self.arrow_patch is not None: # FancyArrowPatch
if self.arrow_patch.figure is None and self.figure is not None:
self.arrow_patch.figure = self.figure
self.arrow_patch.draw(renderer)
# Draw text, including FancyBboxPatch, after FancyArrowPatch.
# Otherwise, a wedge arrowstyle can land partly on top of the Bbox.
Text.draw(self, renderer)
def get_window_extent(self, renderer=None):
"""
Return the `Bbox` bounding the text and arrow, in display units.
Parameters
----------
renderer : Renderer, optional
A renderer is needed to compute the bounding box. If the artist
has already been drawn, the renderer is cached; thus, it is only
necessary to pass this argument when calling `get_window_extent`
before the first `draw`. In practice, it is usually easier to
trigger a draw first (e.g. by saving the figure).
"""
# This block is the same as in Text.get_window_extent, but we need to
# set the renderer before calling update_positions().
if not self.get_visible():
return Bbox.unit()
if renderer is not None:
self._renderer = renderer
if self._renderer is None:
self._renderer = self.figure._cachedRenderer
if self._renderer is None:
raise RuntimeError('Cannot get window extent w/o renderer')
self.update_positions(self._renderer)
text_bbox = Text.get_window_extent(self)
bboxes = [text_bbox]
if self.arrow_patch is not None:
bboxes.append(self.arrow_patch.get_window_extent())
return Bbox.union(bboxes)
arrow = property(
fget=cbook.deprecated("3.0", message="arrow was deprecated in "
"Matplotlib 3.0 and will be removed in 3.2. Use arrow_patch "
"instead.")(lambda self: None),
fset=cbook.deprecated("3.0")(lambda self, value: None))
docstring.interpd.update(Annotation=Annotation.__init__.__doc__)
|
213a22de41859cedf8721c70fb10cd52f1c350d7ebfc89a2e5ac5c04ddf87b59
|
"""
matplotlib includes a framework for arbitrary geometric
transformations that is used determine the final position of all
elements drawn on the canvas.
Transforms are composed into trees of `TransformNode` objects
whose actual value depends on their children. When the contents of
children change, their parents are automatically invalidated. The
next time an invalidated transform is accessed, it is recomputed to
reflect those changes. This invalidation/caching approach prevents
unnecessary recomputations of transforms, and contributes to better
interactive performance.
For example, here is a graph of the transform tree used to plot data
to the graph:
.. image:: ../_static/transforms.png
The framework can be used for both affine and non-affine
transformations. However, for speed, we want use the backend
renderers to perform affine transformations whenever possible.
Therefore, it is possible to perform just the affine or non-affine
part of a transformation on a set of data. The affine is always
assumed to occur after the non-affine. For any transform::
full transform == non-affine part + affine part
The backends are not expected to handle non-affine transformations
themselves.
"""
# Note: There are a number of places in the code where we use `np.min` or
# `np.minimum` instead of the builtin `min`, and likewise for `max`. This is
# done so that `nan`s are propagated, instead of being silently dropped.
import re
import weakref
import numpy as np
from numpy.linalg import inv
from matplotlib import cbook
from matplotlib._path import (
affine_transform, count_bboxes_overlapping_bbox, update_path_extents)
from .path import Path
DEBUG = False
def _indent_str(obj): # textwrap.indent(str(obj), 4) on Py3.
return re.sub("(^|\n)", r"\1 ", str(obj))
class TransformNode(object):
"""
:class:`TransformNode` is the base class for anything that
participates in the transform tree and needs to invalidate its
parents or be invalidated. This includes classes that are not
really transforms, such as bounding boxes, since some transforms
depend on bounding boxes to compute their values.
"""
_gid = 0
# Invalidation may affect only the affine part. If the
# invalidation was "affine-only", the _invalid member is set to
# INVALID_AFFINE_ONLY
INVALID_NON_AFFINE = 1
INVALID_AFFINE = 2
INVALID = INVALID_NON_AFFINE | INVALID_AFFINE
# Some metadata about the transform, used to determine whether an
# invalidation is affine-only
is_affine = False
is_bbox = False
pass_through = False
"""
If pass_through is True, all ancestors will always be
invalidated, even if 'self' is already invalid.
"""
def __init__(self, shorthand_name=None):
"""
Creates a new :class:`TransformNode`.
Parameters
----------
shorthand_name : str
A string representing the "name" of the transform. The name carries
no significance other than to improve the readability of
``str(transform)`` when DEBUG=True.
"""
self._parents = {}
# TransformNodes start out as invalid until their values are
# computed for the first time.
self._invalid = 1
self._shorthand_name = shorthand_name or ''
if DEBUG:
def __str__(self):
# either just return the name of this TransformNode, or its repr
return self._shorthand_name or repr(self)
def __getstate__(self):
# turn the dictionary with weak values into a normal dictionary
return {**self.__dict__,
'_parents': {k: v() for k, v in self._parents.items()}}
def __setstate__(self, data_dict):
self.__dict__ = data_dict
# turn the normal dictionary back into a dictionary with weak values
# The extra lambda is to provide a callback to remove dead
# weakrefs from the dictionary when garbage collection is done.
self._parents = {k: weakref.ref(v, lambda ref, sid=k,
target=self._parents:
target.pop(sid))
for k, v in self._parents.items() if v is not None}
def __copy__(self, *args):
raise NotImplementedError(
"TransformNode instances can not be copied. "
"Consider using frozen() instead.")
__deepcopy__ = __copy__
def invalidate(self):
"""
Invalidate this `TransformNode` and triggers an invalidation of its
ancestors. Should be called any time the transform changes.
"""
value = self.INVALID
if self.is_affine:
value = self.INVALID_AFFINE
return self._invalidate_internal(value, invalidating_node=self)
def _invalidate_internal(self, value, invalidating_node):
"""
Called by :meth:`invalidate` and subsequently ascends the transform
stack calling each TransformNode's _invalidate_internal method.
"""
# determine if this call will be an extension to the invalidation
# status. If not, then a shortcut means that we needn't invoke an
# invalidation up the transform stack as it will already have been
# invalidated.
# N.B This makes the invalidation sticky, once a transform has been
# invalidated as NON_AFFINE, then it will always be invalidated as
# NON_AFFINE even when triggered with a AFFINE_ONLY invalidation.
# In most cases this is not a problem (i.e. for interactive panning and
# zooming) and the only side effect will be on performance.
status_changed = self._invalid < value
if self.pass_through or status_changed:
self._invalid = value
for parent in list(self._parents.values()):
# Dereference the weak reference
parent = parent()
if parent is not None:
parent._invalidate_internal(
value=value, invalidating_node=self)
def set_children(self, *children):
"""
Set the children of the transform, to let the invalidation
system know which transforms can invalidate this transform.
Should be called from the constructor of any transforms that
depend on other transforms.
"""
# Parents are stored as weak references, so that if the
# parents are destroyed, references from the children won't
# keep them alive.
for child in children:
# Use weak references so this dictionary won't keep obsolete nodes
# alive; the callback deletes the dictionary entry. This is a
# performance improvement over using WeakValueDictionary.
ref = weakref.ref(self, lambda ref, sid=id(self),
target=child._parents: target.pop(sid))
child._parents[id(self)] = ref
if DEBUG:
_set_children = set_children
def set_children(self, *children):
self._set_children(*children)
self._children = children
set_children.__doc__ = _set_children.__doc__
def frozen(self):
"""
Returns a frozen copy of this transform node. The frozen copy
will not update when its children change. Useful for storing
a previously known state of a transform where
``copy.deepcopy()`` might normally be used.
"""
return self
if DEBUG:
def write_graphviz(self, fobj, highlight=[]):
"""
For debugging purposes.
Writes the transform tree rooted at 'self' to a graphviz "dot"
format file. This file can be run through the "dot" utility
to produce a graph of the transform tree.
Affine transforms are marked in blue. Bounding boxes are
marked in yellow.
*fobj*: A Python file-like object
Once the "dot" file has been created, it can be turned into a
png easily with::
$> dot -Tpng -o $OUTPUT_FILE $DOT_FILE
"""
seen = set()
def recurse(root):
if root in seen:
return
seen.add(root)
props = {}
label = root.__class__.__name__
if root._invalid:
label = '[%s]' % label
if root in highlight:
props['style'] = 'bold'
props['shape'] = 'box'
props['label'] = '"%s"' % label
props = ' '.join(map('{0[0]}={0[1]}'.format, props.items()))
fobj.write('%s [%s];\n' % (hash(root), props))
if hasattr(root, '_children'):
for child in root._children:
name = next((key for key, val in root.__dict__.items()
if val is child), '?')
fobj.write('"%s" -> "%s" [label="%s", fontsize=10];\n'
% (hash(root),
hash(child),
name))
recurse(child)
fobj.write("digraph G {\n")
recurse(self)
fobj.write("}\n")
class BboxBase(TransformNode):
"""
This is the base class of all bounding boxes, and provides read-only access
to its data. A mutable bounding box is provided by the `Bbox` class.
The canonical representation is as two points, with no
restrictions on their ordering. Convenience properties are
provided to get the left, bottom, right and top edges and width
and height, but these are not stored explicitly.
"""
is_bbox = True
is_affine = True
if DEBUG:
def _check(points):
if isinstance(points, np.ma.MaskedArray):
cbook._warn_external("Bbox bounds are a masked array.")
points = np.asarray(points)
if (points[1, 0] - points[0, 0] == 0 or
points[1, 1] - points[0, 1] == 0):
cbook._warn_external("Singular Bbox.")
_check = staticmethod(_check)
def frozen(self):
return Bbox(self.get_points().copy())
frozen.__doc__ = TransformNode.__doc__
def __array__(self, *args, **kwargs):
return self.get_points()
def is_unit(self):
"""Return whether this is the unit box (from (0, 0) to (1, 1))."""
return self.get_points().tolist() == [[0., 0.], [1., 1.]]
@property
def x0(self):
"""
The first of the pair of *x* coordinates that define the bounding box.
This is not guaranteed to be less than :attr:`x1` (for that, use
:attr:`xmin`).
"""
return self.get_points()[0, 0]
@property
def y0(self):
"""
The first of the pair of *y* coordinates that define the bounding box.
This is not guaranteed to be less than :attr:`y1` (for that, use
:attr:`ymin`).
"""
return self.get_points()[0, 1]
@property
def x1(self):
"""
The second of the pair of *x* coordinates that define the bounding box.
This is not guaranteed to be greater than :attr:`x0` (for that, use
:attr:`xmax`).
"""
return self.get_points()[1, 0]
@property
def y1(self):
"""
The second of the pair of *y* coordinates that define the bounding box.
This is not guaranteed to be greater than :attr:`y0` (for that, use
:attr:`ymax`).
"""
return self.get_points()[1, 1]
@property
def p0(self):
"""
The first pair of (*x*, *y*) coordinates that define the bounding box.
This is not guaranteed to be the bottom-left corner (for that, use
:attr:`min`).
"""
return self.get_points()[0]
@property
def p1(self):
"""
The second pair of (*x*, *y*) coordinates that define the bounding box.
This is not guaranteed to be the top-right corner (for that, use
:attr:`max`).
"""
return self.get_points()[1]
@property
def xmin(self):
"""The left edge of the bounding box."""
return np.min(self.get_points()[:, 0])
@property
def ymin(self):
"""The bottom edge of the bounding box."""
return np.min(self.get_points()[:, 1])
@property
def xmax(self):
"""The right edge of the bounding box."""
return np.max(self.get_points()[:, 0])
@property
def ymax(self):
"""The top edge of the bounding box."""
return np.max(self.get_points()[:, 1])
@property
def min(self):
"""The bottom-left corner of the bounding box."""
return np.min(self.get_points(), axis=0)
@property
def max(self):
"""The top-right corner of the bounding box."""
return np.max(self.get_points(), axis=0)
@property
def intervalx(self):
"""
The pair of *x* coordinates that define the bounding box.
This is not guaranteed to be sorted from left to right.
"""
return self.get_points()[:, 0]
@property
def intervaly(self):
"""
The pair of *y* coordinates that define the bounding box.
This is not guaranteed to be sorted from bottom to top.
"""
return self.get_points()[:, 1]
@property
def width(self):
"""The (signed) width of the bounding box."""
points = self.get_points()
return points[1, 0] - points[0, 0]
@property
def height(self):
"""The (signed) height of the bounding box."""
points = self.get_points()
return points[1, 1] - points[0, 1]
@property
def size(self):
"""The (signed) width and height of the bounding box."""
points = self.get_points()
return points[1] - points[0]
@property
def bounds(self):
"""Return (:attr:`x0`, :attr:`y0`, :attr:`width`, :attr:`height`)."""
(x0, y0), (x1, y1) = self.get_points()
return (x0, y0, x1 - x0, y1 - y0)
@property
def extents(self):
"""Return (:attr:`x0`, :attr:`y0`, :attr:`x1`, :attr:`y1`)."""
return self.get_points().flatten() # flatten returns a copy.
def get_points(self):
raise NotImplementedError
def containsx(self, x):
"""
Return whether *x* is in the closed (:attr:`x0`, :attr:`x1`) interval.
"""
x0, x1 = self.intervalx
return x0 <= x <= x1 or x0 >= x >= x1
def containsy(self, y):
"""
Return whether *y* is in the closed (:attr:`y0`, :attr:`y1`) interval.
"""
y0, y1 = self.intervaly
return y0 <= y <= y1 or y0 >= y >= y1
def contains(self, x, y):
"""
Return whether ``(x, y)`` is in the bounding box or on its edge.
"""
return self.containsx(x) and self.containsy(y)
def overlaps(self, other):
"""
Return whether this bounding box overlaps with the other bounding box.
Parameters
----------
other : BboxBase
"""
ax1, ay1, ax2, ay2 = self.extents
bx1, by1, bx2, by2 = other.extents
if ax2 < ax1:
ax2, ax1 = ax1, ax2
if ay2 < ay1:
ay2, ay1 = ay1, ay2
if bx2 < bx1:
bx2, bx1 = bx1, bx2
if by2 < by1:
by2, by1 = by1, by2
return ax1 <= bx2 and bx1 <= ax2 and ay1 <= by2 and by1 <= ay2
def fully_containsx(self, x):
"""
Return whether *x* is in the open (:attr:`x0`, :attr:`x1`) interval.
"""
x0, x1 = self.intervalx
return x0 < x < x1 or x0 > x > x1
def fully_containsy(self, y):
"""
Return whether *y* is in the open (:attr:`y0`, :attr:`y1`) interval.
"""
y0, y1 = self.intervaly
return y0 < y < y1 or y0 > y > y1
def fully_contains(self, x, y):
"""
Return whether ``x, y`` is in the bounding box, but not on its edge.
"""
return self.fully_containsx(x) and self.fully_containsy(y)
def fully_overlaps(self, other):
"""
Return whether this bounding box overlaps with the other bounding box,
not including the edges.
Parameters
----------
other : BboxBase
"""
ax1, ay1, ax2, ay2 = self.extents
bx1, by1, bx2, by2 = other.extents
if ax2 < ax1:
ax2, ax1 = ax1, ax2
if ay2 < ay1:
ay2, ay1 = ay1, ay2
if bx2 < bx1:
bx2, bx1 = bx1, bx2
if by2 < by1:
by2, by1 = by1, by2
return ax1 < bx2 and bx1 < ax2 and ay1 < by2 and by1 < ay2
def transformed(self, transform):
"""
Construct a `Bbox` by statically transforming this one by *transform*.
"""
pts = self.get_points()
ll, ul, lr = transform.transform(np.array([pts[0],
[pts[0, 0], pts[1, 1]], [pts[1, 0], pts[0, 1]]]))
return Bbox([ll, [lr[0], ul[1]]])
def inverse_transformed(self, transform):
"""
Construct a `Bbox` by statically transforming this one by the inverse
of *transform*.
"""
return self.transformed(transform.inverted())
coefs = {'C': (0.5, 0.5),
'SW': (0, 0),
'S': (0.5, 0),
'SE': (1.0, 0),
'E': (1.0, 0.5),
'NE': (1.0, 1.0),
'N': (0.5, 1.0),
'NW': (0, 1.0),
'W': (0, 0.5)}
def anchored(self, c, container=None):
"""
Return a copy of the `Bbox` shifted to position *c* within *container*.
Parameters
----------
c : (float, float) or str
May be either:
* A sequence (*cx*, *cy*) where *cx* and *cy* range from 0
to 1, where 0 is left or bottom and 1 is right or top
* a string:
- 'C' for centered
- 'S' for bottom-center
- 'SE' for bottom-left
- 'E' for left
- etc.
container : Bbox, optional
The box within which the :class:`Bbox` is positioned; it defaults
to the initial :class:`Bbox`.
"""
if container is None:
container = self
l, b, w, h = container.bounds
if isinstance(c, str):
cx, cy = self.coefs[c]
else:
cx, cy = c
L, B, W, H = self.bounds
return Bbox(self._points +
[(l + cx * (w - W)) - L,
(b + cy * (h - H)) - B])
def shrunk(self, mx, my):
"""
Return a copy of the :class:`Bbox`, shrunk by the factor *mx*
in the *x* direction and the factor *my* in the *y* direction.
The lower left corner of the box remains unchanged. Normally
*mx* and *my* will be less than 1, but this is not enforced.
"""
w, h = self.size
return Bbox([self._points[0],
self._points[0] + [mx * w, my * h]])
def shrunk_to_aspect(self, box_aspect, container=None, fig_aspect=1.0):
"""
Return a copy of the :class:`Bbox`, shrunk so that it is as
large as it can be while having the desired aspect ratio,
*box_aspect*. If the box coordinates are relative---that
is, fractions of a larger box such as a figure---then the
physical aspect ratio of that figure is specified with
*fig_aspect*, so that *box_aspect* can also be given as a
ratio of the absolute dimensions, not the relative dimensions.
"""
if box_aspect <= 0 or fig_aspect <= 0:
raise ValueError("'box_aspect' and 'fig_aspect' must be positive")
if container is None:
container = self
w, h = container.size
H = w * box_aspect / fig_aspect
if H <= h:
W = w
else:
W = h * fig_aspect / box_aspect
H = h
return Bbox([self._points[0],
self._points[0] + (W, H)])
def splitx(self, *args):
"""
Return a list of new `Bbox` objects formed by splitting the original
one with vertical lines at fractional positions given by *args*.
"""
xf = [0, *args, 1]
x0, y0, x1, y1 = self.extents
w = x1 - x0
return [Bbox([[x0 + xf0 * w, y0], [x0 + xf1 * w, y1]])
for xf0, xf1 in zip(xf[:-1], xf[1:])]
def splity(self, *args):
"""
Return a list of new `Bbox` objects formed by splitting the original
one with horizontal lines at fractional positions given by *args*.
"""
yf = [0, *args, 1]
x0, y0, x1, y1 = self.extents
h = y1 - y0
return [Bbox([[x0, y0 + yf0 * h], [x1, y0 + yf1 * h]])
for yf0, yf1 in zip(yf[:-1], yf[1:])]
def count_contains(self, vertices):
"""
Count the number of vertices contained in the :class:`Bbox`.
Any vertices with a non-finite x or y value are ignored.
Parameters
----------
vertices : Nx2 Numpy array.
"""
if len(vertices) == 0:
return 0
vertices = np.asarray(vertices)
with np.errstate(invalid='ignore'):
return (((self.min < vertices) &
(vertices < self.max)).all(axis=1).sum())
def count_overlaps(self, bboxes):
"""
Count the number of bounding boxes that overlap this one.
Parameters
----------
bboxes : sequence of :class:`BboxBase` objects
"""
return count_bboxes_overlapping_bbox(
self, np.atleast_3d([np.array(x) for x in bboxes]))
def expanded(self, sw, sh):
"""
Construct a `Bbox` by expanding this one around its center by the
factors *sw* and *sh*.
"""
width = self.width
height = self.height
deltaw = (sw * width - width) / 2.0
deltah = (sh * height - height) / 2.0
a = np.array([[-deltaw, -deltah], [deltaw, deltah]])
return Bbox(self._points + a)
def padded(self, p):
"""Construct a `Bbox` by padding this one on all four sides by *p*."""
points = self.get_points()
return Bbox(points + [[-p, -p], [p, p]])
def translated(self, tx, ty):
"""Construct a `Bbox` by translating this one by *tx* and *ty*."""
return Bbox(self._points + (tx, ty))
def corners(self):
"""
Return the corners of this rectangle as an array of points.
Specifically, this returns the array
``[[x0, y0], [x0, y1], [x1, y0], [x1, y1]]``.
"""
(x0, y0), (x1, y1) = self.get_points()
return np.array([[x0, y0], [x0, y1], [x1, y0], [x1, y1]])
def rotated(self, radians):
"""
Return a new bounding box that bounds a rotated version of
this bounding box by the given radians. The new bounding box
is still aligned with the axes, of course.
"""
corners = self.corners()
corners_rotated = Affine2D().rotate(radians).transform(corners)
bbox = Bbox.unit()
bbox.update_from_data_xy(corners_rotated, ignore=True)
return bbox
@staticmethod
def union(bboxes):
"""Return a `Bbox` that contains all of the given *bboxes*."""
if not len(bboxes):
raise ValueError("'bboxes' cannot be empty")
x0 = np.min([bbox.xmin for bbox in bboxes])
x1 = np.max([bbox.xmax for bbox in bboxes])
y0 = np.min([bbox.ymin for bbox in bboxes])
y1 = np.max([bbox.ymax for bbox in bboxes])
return Bbox([[x0, y0], [x1, y1]])
@staticmethod
def intersection(bbox1, bbox2):
"""
Return the intersection of *bbox1* and *bbox2* if they intersect, or
None if they don't.
"""
x0 = np.maximum(bbox1.xmin, bbox2.xmin)
x1 = np.minimum(bbox1.xmax, bbox2.xmax)
y0 = np.maximum(bbox1.ymin, bbox2.ymin)
y1 = np.minimum(bbox1.ymax, bbox2.ymax)
return Bbox([[x0, y0], [x1, y1]]) if x0 <= x1 and y0 <= y1 else None
class Bbox(BboxBase):
"""
A mutable bounding box.
"""
def __init__(self, points, **kwargs):
"""
Parameters
----------
points : ndarray
A 2x2 numpy array of the form ``[[x0, y0], [x1, y1]]``.
Notes
-----
If you need to create a :class:`Bbox` object from another form
of data, consider the static methods :meth:`unit`,
:meth:`from_bounds` and :meth:`from_extents`.
"""
BboxBase.__init__(self, **kwargs)
points = np.asarray(points, float)
if points.shape != (2, 2):
raise ValueError('Bbox points must be of the form '
'"[[x0, y0], [x1, y1]]".')
self._points = points
self._minpos = np.array([np.inf, np.inf])
self._ignore = True
# it is helpful in some contexts to know if the bbox is a
# default or has been mutated; we store the orig points to
# support the mutated methods
self._points_orig = self._points.copy()
if DEBUG:
___init__ = __init__
def __init__(self, points, **kwargs):
self._check(points)
self.___init__(points, **kwargs)
def invalidate(self):
self._check(self._points)
TransformNode.invalidate(self)
@staticmethod
def unit():
"""Create a new unit `Bbox` from (0, 0) to (1, 1)."""
return Bbox(np.array([[0.0, 0.0], [1.0, 1.0]], float))
@staticmethod
def null():
"""Create a new null `Bbox` from (inf, inf) to (-inf, -inf)."""
return Bbox(np.array([[np.inf, np.inf], [-np.inf, -np.inf]], float))
@staticmethod
def from_bounds(x0, y0, width, height):
"""
Create a new `Bbox` from *x0*, *y0*, *width* and *height*.
*width* and *height* may be negative.
"""
return Bbox.from_extents(x0, y0, x0 + width, y0 + height)
@staticmethod
def from_extents(*args):
"""
Create a new Bbox from *left*, *bottom*, *right* and *top*.
The *y*-axis increases upwards.
"""
points = np.array(args, dtype=float).reshape(2, 2)
return Bbox(points)
def __format__(self, fmt):
return (
'Bbox(x0={0.x0:{1}}, y0={0.y0:{1}}, x1={0.x1:{1}}, y1={0.y1:{1}})'.
format(self, fmt))
def __str__(self):
return format(self, '')
def __repr__(self):
return 'Bbox([[{0.x0}, {0.y0}], [{0.x1}, {0.y1}]])'.format(self)
def ignore(self, value):
"""
Set whether the existing bounds of the box should be ignored
by subsequent calls to :meth:`update_from_data_xy`.
value : bool
- When ``True``, subsequent calls to :meth:`update_from_data_xy`
will ignore the existing bounds of the :class:`Bbox`.
- When ``False``, subsequent calls to :meth:`update_from_data_xy`
will include the existing bounds of the :class:`Bbox`.
"""
self._ignore = value
def update_from_path(self, path, ignore=None, updatex=True, updatey=True):
"""
Update the bounds of the :class:`Bbox` based on the passed in
data. After updating, the bounds will have positive *width*
and *height*; *x0* and *y0* will be the minimal values.
Parameters
----------
path : :class:`~matplotlib.path.Path`
ignore : bool, optional
- when ``True``, ignore the existing bounds of the :class:`Bbox`.
- when ``False``, include the existing bounds of the :class:`Bbox`.
- when ``None``, use the last value passed to :meth:`ignore`.
updatex, updatey : bool, optional
When ``True``, update the x/y values.
"""
if ignore is None:
ignore = self._ignore
if path.vertices.size == 0:
return
points, minpos, changed = update_path_extents(
path, None, self._points, self._minpos, ignore)
if changed:
self.invalidate()
if updatex:
self._points[:, 0] = points[:, 0]
self._minpos[0] = minpos[0]
if updatey:
self._points[:, 1] = points[:, 1]
self._minpos[1] = minpos[1]
def update_from_data_xy(self, xy, ignore=None, updatex=True, updatey=True):
"""
Update the bounds of the :class:`Bbox` based on the passed in
data. After updating, the bounds will have positive *width*
and *height*; *x0* and *y0* will be the minimal values.
Parameters
----------
xy : ndarray
A numpy array of 2D points.
ignore : bool, optional
- When ``True``, ignore the existing bounds of the :class:`Bbox`.
- When ``False``, include the existing bounds of the :class:`Bbox`.
- When ``None``, use the last value passed to :meth:`ignore`.
updatex, updatey : bool, optional
When ``True``, update the x/y values.
"""
if len(xy) == 0:
return
path = Path(xy)
self.update_from_path(path, ignore=ignore,
updatex=updatex, updatey=updatey)
@BboxBase.x0.setter
def x0(self, val):
self._points[0, 0] = val
self.invalidate()
@BboxBase.y0.setter
def y0(self, val):
self._points[0, 1] = val
self.invalidate()
@BboxBase.x1.setter
def x1(self, val):
self._points[1, 0] = val
self.invalidate()
@BboxBase.y1.setter
def y1(self, val):
self._points[1, 1] = val
self.invalidate()
@BboxBase.p0.setter
def p0(self, val):
self._points[0] = val
self.invalidate()
@BboxBase.p1.setter
def p1(self, val):
self._points[1] = val
self.invalidate()
@BboxBase.intervalx.setter
def intervalx(self, interval):
self._points[:, 0] = interval
self.invalidate()
@BboxBase.intervaly.setter
def intervaly(self, interval):
self._points[:, 1] = interval
self.invalidate()
@BboxBase.bounds.setter
def bounds(self, bounds):
l, b, w, h = bounds
points = np.array([[l, b], [l + w, b + h]], float)
if np.any(self._points != points):
self._points = points
self.invalidate()
@property
def minpos(self):
return self._minpos
@property
def minposx(self):
return self._minpos[0]
@property
def minposy(self):
return self._minpos[1]
def get_points(self):
"""
Get the points of the bounding box directly as a numpy array
of the form: ``[[x0, y0], [x1, y1]]``.
"""
self._invalid = 0
return self._points
def set_points(self, points):
"""
Set the points of the bounding box directly from a numpy array
of the form: ``[[x0, y0], [x1, y1]]``. No error checking is
performed, as this method is mainly for internal use.
"""
if np.any(self._points != points):
self._points = points
self.invalidate()
def set(self, other):
"""
Set this bounding box from the "frozen" bounds of another `Bbox`.
"""
if np.any(self._points != other.get_points()):
self._points = other.get_points()
self.invalidate()
def mutated(self):
'Return whether the bbox has changed since init.'
return self.mutatedx() or self.mutatedy()
def mutatedx(self):
'Return whether the x-limits have changed since init.'
return (self._points[0, 0] != self._points_orig[0, 0] or
self._points[1, 0] != self._points_orig[1, 0])
def mutatedy(self):
'Return whether the y-limits have changed since init.'
return (self._points[0, 1] != self._points_orig[0, 1] or
self._points[1, 1] != self._points_orig[1, 1])
class TransformedBbox(BboxBase):
"""
A :class:`Bbox` that is automatically transformed by a given
transform. When either the child bounding box or transform
changes, the bounds of this bbox will update accordingly.
"""
def __init__(self, bbox, transform, **kwargs):
"""
Parameters
----------
bbox : :class:`Bbox`
transform : :class:`Transform`
"""
if not bbox.is_bbox:
raise ValueError("'bbox' is not a bbox")
if not isinstance(transform, Transform):
raise ValueError("'transform' must be an instance of "
"'matplotlib.transform.Transform'")
if transform.input_dims != 2 or transform.output_dims != 2:
raise ValueError(
"The input and output dimensions of 'transform' must be 2")
BboxBase.__init__(self, **kwargs)
self._bbox = bbox
self._transform = transform
self.set_children(bbox, transform)
self._points = None
def __str__(self):
return ("{}(\n"
"{},\n"
"{})"
.format(type(self).__name__,
_indent_str(self._bbox),
_indent_str(self._transform)))
def get_points(self):
# docstring inherited
if self._invalid:
p = self._bbox.get_points()
# Transform all four points, then make a new bounding box
# from the result, taking care to make the orientation the
# same.
points = self._transform.transform(
[[p[0, 0], p[0, 1]],
[p[1, 0], p[0, 1]],
[p[0, 0], p[1, 1]],
[p[1, 0], p[1, 1]]])
points = np.ma.filled(points, 0.0)
xs = min(points[:, 0]), max(points[:, 0])
if p[0, 0] > p[1, 0]:
xs = xs[::-1]
ys = min(points[:, 1]), max(points[:, 1])
if p[0, 1] > p[1, 1]:
ys = ys[::-1]
self._points = np.array([
[xs[0], ys[0]],
[xs[1], ys[1]]
])
self._invalid = 0
return self._points
if DEBUG:
_get_points = get_points
def get_points(self):
points = self._get_points()
self._check(points)
return points
class LockableBbox(BboxBase):
"""
A :class:`Bbox` where some elements may be locked at certain values.
When the child bounding box changes, the bounds of this bbox will update
accordingly with the exception of the locked elements.
"""
def __init__(self, bbox, x0=None, y0=None, x1=None, y1=None, **kwargs):
"""
Parameters
----------
bbox : Bbox
The child bounding box to wrap.
x0 : float or None
The locked value for x0, or None to leave unlocked.
y0 : float or None
The locked value for y0, or None to leave unlocked.
x1 : float or None
The locked value for x1, or None to leave unlocked.
y1 : float or None
The locked value for y1, or None to leave unlocked.
"""
if not bbox.is_bbox:
raise ValueError("'bbox' is not a bbox")
BboxBase.__init__(self, **kwargs)
self._bbox = bbox
self.set_children(bbox)
self._points = None
fp = [x0, y0, x1, y1]
mask = [val is None for val in fp]
self._locked_points = np.ma.array(fp, float, mask=mask).reshape((2, 2))
def __str__(self):
return ("{}(\n"
"{},\n"
"{})"
.format(type(self).__name__,
_indent_str(self._bbox),
_indent_str(self._locked_points)))
def get_points(self):
# docstring inherited
if self._invalid:
points = self._bbox.get_points()
self._points = np.where(self._locked_points.mask,
points,
self._locked_points)
self._invalid = 0
return self._points
if DEBUG:
_get_points = get_points
def get_points(self):
points = self._get_points()
self._check(points)
return points
@property
def locked_x0(self):
"""
float or None: The value used for the locked x0.
"""
if self._locked_points.mask[0, 0]:
return None
else:
return self._locked_points[0, 0]
@locked_x0.setter
def locked_x0(self, x0):
self._locked_points.mask[0, 0] = x0 is None
self._locked_points.data[0, 0] = x0
self.invalidate()
@property
def locked_y0(self):
"""
float or None: The value used for the locked y0.
"""
if self._locked_points.mask[0, 1]:
return None
else:
return self._locked_points[0, 1]
@locked_y0.setter
def locked_y0(self, y0):
self._locked_points.mask[0, 1] = y0 is None
self._locked_points.data[0, 1] = y0
self.invalidate()
@property
def locked_x1(self):
"""
float or None: The value used for the locked x1.
"""
if self._locked_points.mask[1, 0]:
return None
else:
return self._locked_points[1, 0]
@locked_x1.setter
def locked_x1(self, x1):
self._locked_points.mask[1, 0] = x1 is None
self._locked_points.data[1, 0] = x1
self.invalidate()
@property
def locked_y1(self):
"""
float or None: The value used for the locked y1.
"""
if self._locked_points.mask[1, 1]:
return None
else:
return self._locked_points[1, 1]
@locked_y1.setter
def locked_y1(self, y1):
self._locked_points.mask[1, 1] = y1 is None
self._locked_points.data[1, 1] = y1
self.invalidate()
class Transform(TransformNode):
"""
The base class of all :class:`TransformNode` instances that
actually perform a transformation.
All non-affine transformations should be subclasses of this class.
New affine transformations should be subclasses of `Affine2D`.
Subclasses of this class should override the following members (at
minimum):
- :attr:`input_dims`
- :attr:`output_dims`
- :meth:`transform`
- :attr:`is_separable`
- :attr:`has_inverse`
- :meth:`inverted` (if :attr:`has_inverse` is True)
If the transform needs to do something non-standard with
:class:`matplotlib.path.Path` objects, such as adding curves
where there were once line segments, it should override:
- :meth:`transform_path`
"""
input_dims = None
"""
The number of input dimensions of this transform.
Must be overridden (with integers) in the subclass.
"""
output_dims = None
"""
The number of output dimensions of this transform.
Must be overridden (with integers) in the subclass.
"""
has_inverse = False
"""True if this transform has a corresponding inverse transform."""
is_separable = False
"""True if this transform is separable in the x- and y- dimensions."""
def __add__(self, other):
"""
Composes two transforms together such that *self* is followed
by *other*.
"""
if isinstance(other, Transform):
return composite_transform_factory(self, other)
raise TypeError(
"Can not add Transform to object of type '%s'" % type(other))
def __radd__(self, other):
"""
Composes two transforms together such that *self* is followed
by *other*.
"""
if isinstance(other, Transform):
return composite_transform_factory(other, self)
raise TypeError(
"Can not add Transform to object of type '%s'" % type(other))
# Equality is based on object identity for `Transform`s (so we don't
# override `__eq__`), but some subclasses, such as TransformWrapper &
# AffineBase, override this behavior.
def _iter_break_from_left_to_right(self):
"""
Returns an iterator breaking down this transform stack from left to
right recursively. If self == ((A, N), A) then the result will be an
iterator which yields I : ((A, N), A), followed by A : (N, A),
followed by (A, N) : (A), but not ((A, N), A) : I.
This is equivalent to flattening the stack then yielding
``flat_stack[:i], flat_stack[i:]`` where i=0..(n-1).
"""
yield IdentityTransform(), self
@property
def depth(self):
"""
Returns the number of transforms which have been chained
together to form this Transform instance.
.. note::
For the special case of a Composite transform, the maximum depth
of the two is returned.
"""
return 1
def contains_branch(self, other):
"""
Return whether the given transform is a sub-tree of this transform.
This routine uses transform equality to identify sub-trees, therefore
in many situations it is object id which will be used.
For the case where the given transform represents the whole
of this transform, returns True.
"""
if self.depth < other.depth:
return False
# check that a subtree is equal to other (starting from self)
for _, sub_tree in self._iter_break_from_left_to_right():
if sub_tree == other:
return True
return False
def contains_branch_seperately(self, other_transform):
"""
Returns whether the given branch is a sub-tree of this transform on
each separate dimension.
A common use for this method is to identify if a transform is a blended
transform containing an axes' data transform. e.g.::
x_isdata, y_isdata = trans.contains_branch_seperately(ax.transData)
"""
if self.output_dims != 2:
raise ValueError('contains_branch_seperately only supports '
'transforms with 2 output dimensions')
# for a non-blended transform each separate dimension is the same, so
# just return the appropriate shape.
return [self.contains_branch(other_transform)] * 2
def __sub__(self, other):
"""
Returns a transform stack which goes all the way down self's transform
stack, and then ascends back up other's stack. If it can, this is
optimised::
# normally
A - B == a + b.inverted()
# sometimes, when A contains the tree B there is no need to
# descend all the way down to the base of A (via B), instead we
# can just stop at B.
(A + B) - (B)^-1 == A
# similarly, when B contains tree A, we can avoid descending A at
# all, basically:
A - (A + B) == ((B + A) - A).inverted() or B^-1
For clarity, the result of ``(A + B) - B + B == (A + B)``.
"""
# we only know how to do this operation if other is a Transform.
if not isinstance(other, Transform):
return NotImplemented
for remainder, sub_tree in self._iter_break_from_left_to_right():
if sub_tree == other:
return remainder
for remainder, sub_tree in other._iter_break_from_left_to_right():
if sub_tree == self:
if not remainder.has_inverse:
raise ValueError(
"The shortcut cannot be computed since 'other' "
"includes a non-invertible component")
return remainder.inverted()
# if we have got this far, then there was no shortcut possible
if other.has_inverse:
return self + other.inverted()
else:
raise ValueError('It is not possible to compute transA - transB '
'since transB cannot be inverted and there is no '
'shortcut possible.')
def __array__(self, *args, **kwargs):
"""
Array interface to get at this Transform's affine matrix.
"""
return self.get_affine().get_matrix()
def transform(self, values):
"""
Performs the transformation on the given array of values.
Accepts a numpy array of shape (N x :attr:`input_dims`) and
returns a numpy array of shape (N x :attr:`output_dims`).
Alternatively, accepts a numpy array of length :attr:`input_dims`
and returns a numpy array of length :attr:`output_dims`.
"""
# Ensure that values is a 2d array (but remember whether
# we started with a 1d or 2d array).
values = np.asanyarray(values)
ndim = values.ndim
values = values.reshape((-1, self.input_dims))
# Transform the values
res = self.transform_affine(self.transform_non_affine(values))
# Convert the result back to the shape of the input values.
if ndim == 0:
assert not np.ma.is_masked(res) # just to be on the safe side
return res[0, 0]
if ndim == 1:
return res.reshape(-1)
elif ndim == 2:
return res
raise ValueError(
"Input values must have shape (N x {dims}) "
"or ({dims}).".format(dims=self.input_dims))
def transform_affine(self, values):
"""
Performs only the affine part of this transformation on the
given array of values.
``transform(values)`` is always equivalent to
``transform_affine(transform_non_affine(values))``.
In non-affine transformations, this is generally a no-op. In
affine transformations, this is equivalent to
``transform(values)``.
Accepts a numpy array of shape (N x :attr:`input_dims`) and
returns a numpy array of shape (N x :attr:`output_dims`).
Alternatively, accepts a numpy array of length :attr:`input_dims`
and returns a numpy array of length :attr:`output_dims`.
"""
return self.get_affine().transform(values)
def transform_non_affine(self, values):
"""
Performs only the non-affine part of the transformation.
``transform(values)`` is always equivalent to
``transform_affine(transform_non_affine(values))``.
In non-affine transformations, this is generally equivalent to
``transform(values)``. In affine transformations, this is
always a no-op.
Accepts a numpy array of shape (N x :attr:`input_dims`) and
returns a numpy array of shape (N x :attr:`output_dims`).
Alternatively, accepts a numpy array of length :attr:`input_dims`
and returns a numpy array of length :attr:`output_dims`.
"""
return values
def transform_bbox(self, bbox):
"""
Transform the given bounding box.
Note, for smarter transforms including caching (a common
requirement for matplotlib figures), see :class:`TransformedBbox`.
"""
return Bbox(self.transform(bbox.get_points()))
def get_affine(self):
"""
Get the affine part of this transform.
"""
return IdentityTransform()
def get_matrix(self):
"""
Get the Affine transformation array for the affine part
of this transform.
"""
return self.get_affine().get_matrix()
def transform_point(self, point):
"""
A convenience function that returns the transformed copy of a
single point.
The point is given as a sequence of length :attr:`input_dims`.
The transformed point is returned as a sequence of length
:attr:`output_dims`.
"""
if len(point) != self.input_dims:
raise ValueError("The length of 'point' must be 'self.input_dims'")
return self.transform(np.asarray([point]))[0]
def transform_path(self, path):
"""
Returns a transformed path.
*path*: a :class:`~matplotlib.path.Path` instance.
In some cases, this transform may insert curves into the path
that began as line segments.
"""
return self.transform_path_affine(self.transform_path_non_affine(path))
def transform_path_affine(self, path):
"""
Returns a path, transformed only by the affine part of
this transform.
*path*: a :class:`~matplotlib.path.Path` instance.
``transform_path(path)`` is equivalent to
``transform_path_affine(transform_path_non_affine(values))``.
"""
return self.get_affine().transform_path_affine(path)
def transform_path_non_affine(self, path):
"""
Returns a path, transformed only by the non-affine
part of this transform.
*path*: a :class:`~matplotlib.path.Path` instance.
``transform_path(path)`` is equivalent to
``transform_path_affine(transform_path_non_affine(values))``.
"""
x = self.transform_non_affine(path.vertices)
return Path._fast_from_codes_and_verts(x, path.codes, path)
def transform_angles(self, angles, pts, radians=False, pushoff=1e-5):
"""
Transforms a set of angles anchored at specific locations.
Parameters
----------
angles : (N,) array-like
The angles to transform.
pts : (N, 2) array-like
The points where the angles are anchored.
radians : bool, default: False
Whether *angles* are radians or degrees.
pushoff : float
For each point in *pts* and angle in *angles*, the transformed
angle is computed by transforming a segment of length *pushoff*
starting at that point and making that angle relative to the
horizontal axis, and measuring the angle between the horizontal
axis and the transformed segment.
Returns
-------
transformed_angles : (N,) array
"""
# Must be 2D
if self.input_dims != 2 or self.output_dims != 2:
raise NotImplementedError('Only defined in 2D')
if pts.shape[1] != 2:
raise ValueError("'pts' must be array with 2 columns for x,y")
if angles.ndim != 1 or angles.shape[0] != pts.shape[0]:
raise ValueError("'angles' must be a column vector and have same "
"number of rows as 'pts'")
# Convert to radians if desired
if not radians:
angles = angles / 180.0 * np.pi
# Move a short distance away
pts2 = pts + pushoff * np.c_[np.cos(angles), np.sin(angles)]
# Transform both sets of points
tpts = self.transform(pts)
tpts2 = self.transform(pts2)
# Calculate transformed angles
d = tpts2 - tpts
a = np.arctan2(d[:, 1], d[:, 0])
# Convert back to degrees if desired
if not radians:
a = np.rad2deg(a)
return a
def inverted(self):
"""
Return the corresponding inverse transformation.
The return value of this method should be treated as
temporary. An update to *self* does not cause a corresponding
update to its inverted copy.
``x === self.inverted().transform(self.transform(x))``
"""
raise NotImplementedError()
class TransformWrapper(Transform):
"""
A helper class that holds a single child transform and acts
equivalently to it.
This is useful if a node of the transform tree must be replaced at
run time with a transform of a different type. This class allows
that replacement to correctly trigger invalidation.
Note that :class:`TransformWrapper` instances must have the same
input and output dimensions during their entire lifetime, so the
child transform may only be replaced with another child transform
of the same dimensions.
"""
pass_through = True
def __init__(self, child):
"""
*child*: A class:`Transform` instance. This child may later
be replaced with :meth:`set`.
"""
if not isinstance(child, Transform):
raise ValueError("'child' must be an instance of "
"'matplotlib.transform.Transform'")
self._init(child)
self.set_children(child)
def _init(self, child):
Transform.__init__(self)
self.input_dims = child.input_dims
self.output_dims = child.output_dims
self._set(child)
self._invalid = 0
def __eq__(self, other):
return self._child.__eq__(other)
def __str__(self):
return ("{}(\n"
"{})"
.format(type(self).__name__,
_indent_str(self._child)))
def frozen(self):
# docstring inherited
return self._child.frozen()
def _set(self, child):
self._child = child
self.transform = child.transform
self.transform_affine = child.transform_affine
self.transform_non_affine = child.transform_non_affine
self.transform_path = child.transform_path
self.transform_path_affine = child.transform_path_affine
self.transform_path_non_affine = child.transform_path_non_affine
self.get_affine = child.get_affine
self.inverted = child.inverted
self.get_matrix = child.get_matrix
# note we do not wrap other properties here since the transform's
# child can be changed with WrappedTransform.set and so checking
# is_affine and other such properties may be dangerous.
def set(self, child):
"""
Replace the current child of this transform with another one.
The new child must have the same number of input and output
dimensions as the current child.
"""
if (child.input_dims != self.input_dims or
child.output_dims != self.output_dims):
raise ValueError(
"The new child must have the same number of input and output "
"dimensions as the current child")
self.set_children(child)
self._set(child)
self._invalid = 0
self.invalidate()
self._invalid = 0
is_affine = property(lambda self: self._child.is_affine)
is_separable = property(lambda self: self._child.is_separable)
has_inverse = property(lambda self: self._child.has_inverse)
class AffineBase(Transform):
"""
The base class of all affine transformations of any number of
dimensions.
"""
is_affine = True
def __init__(self, *args, **kwargs):
Transform.__init__(self, *args, **kwargs)
self._inverted = None
def __array__(self, *args, **kwargs):
# optimises the access of the transform matrix vs the superclass
return self.get_matrix()
def __eq__(self, other):
if getattr(other, "is_affine", False):
return np.all(self.get_matrix() == other.get_matrix())
return NotImplemented
def transform(self, values):
# docstring inherited
return self.transform_affine(values)
def transform_affine(self, values):
# docstring inherited
raise NotImplementedError('Affine subclasses should override this '
'method.')
def transform_non_affine(self, points):
# docstring inherited
return points
def transform_path(self, path):
# docstring inherited
return self.transform_path_affine(path)
def transform_path_affine(self, path):
# docstring inherited
return Path(self.transform_affine(path.vertices),
path.codes, path._interpolation_steps)
def transform_path_non_affine(self, path):
# docstring inherited
return path
def get_affine(self):
# docstring inherited
return self
class Affine2DBase(AffineBase):
"""
The base class of all 2D affine transformations.
2D affine transformations are performed using a 3x3 numpy array::
a c e
b d f
0 0 1
This class provides the read-only interface. For a mutable 2D
affine transformation, use :class:`Affine2D`.
Subclasses of this class will generally only need to override a
constructor and :meth:`get_matrix` that generates a custom 3x3 matrix.
"""
has_inverse = True
input_dims = 2
output_dims = 2
def frozen(self):
# docstring inherited
return Affine2D(self.get_matrix().copy())
@property
def is_separable(self):
mtx = self.get_matrix()
return mtx[0, 1] == mtx[1, 0] == 0.0
def to_values(self):
"""
Return the values of the matrix as an ``(a, b, c, d, e, f)`` tuple.
"""
mtx = self.get_matrix()
return tuple(mtx[:2].swapaxes(0, 1).flat)
@staticmethod
def matrix_from_values(a, b, c, d, e, f):
"""
Create a new transformation matrix as a 3x3 numpy array of the form::
a c e
b d f
0 0 1
"""
return np.array([[a, c, e], [b, d, f], [0.0, 0.0, 1.0]], float)
def transform_affine(self, points):
mtx = self.get_matrix()
if isinstance(points, np.ma.MaskedArray):
tpoints = affine_transform(points.data, mtx)
return np.ma.MaskedArray(tpoints, mask=np.ma.getmask(points))
return affine_transform(points, mtx)
def transform_point(self, point):
# docstring inherited
mtx = self.get_matrix()
return affine_transform([point], mtx)[0]
if DEBUG:
_transform_affine = transform_affine
def transform_affine(self, points):
# docstring inherited
# The major speed trap here is just converting to the
# points to an array in the first place. If we can use
# more arrays upstream, that should help here.
if not isinstance(points, (np.ma.MaskedArray, np.ndarray)):
cbook._warn_external(
f'A non-numpy array of type {type(points)} was passed in '
f'for transformation, which results in poor performance.')
return self._transform_affine(points)
def inverted(self):
# docstring inherited
if self._inverted is None or self._invalid:
mtx = self.get_matrix()
shorthand_name = None
if self._shorthand_name:
shorthand_name = '(%s)-1' % self._shorthand_name
self._inverted = Affine2D(inv(mtx), shorthand_name=shorthand_name)
self._invalid = 0
return self._inverted
class Affine2D(Affine2DBase):
"""
A mutable 2D affine transformation.
"""
def __init__(self, matrix=None, **kwargs):
"""
Initialize an Affine transform from a 3x3 numpy float array::
a c e
b d f
0 0 1
If *matrix* is None, initialize with the identity transform.
"""
Affine2DBase.__init__(self, **kwargs)
if matrix is None:
# A bit faster than np.identity(3).
matrix = IdentityTransform._mtx.copy()
self._mtx = matrix
self._invalid = 0
def __str__(self):
return ("{}(\n"
"{})"
.format(type(self).__name__,
_indent_str(self._mtx)))
@staticmethod
def from_values(a, b, c, d, e, f):
"""
Create a new Affine2D instance from the given values::
a c e
b d f
0 0 1
.
"""
return Affine2D(
np.array([a, c, e, b, d, f, 0.0, 0.0, 1.0], float).reshape((3, 3)))
def get_matrix(self):
"""
Get the underlying transformation matrix as a 3x3 numpy array::
a c e
b d f
0 0 1
.
"""
self._invalid = 0
return self._mtx
def set_matrix(self, mtx):
"""
Set the underlying transformation matrix from a 3x3 numpy array::
a c e
b d f
0 0 1
.
"""
self._mtx = mtx
self.invalidate()
def set(self, other):
"""
Set this transformation from the frozen copy of another
:class:`Affine2DBase` object.
"""
if not isinstance(other, Affine2DBase):
raise ValueError("'other' must be an instance of "
"'matplotlib.transform.Affine2DBase'")
self._mtx = other.get_matrix()
self.invalidate()
@staticmethod
def identity():
"""
Return a new `Affine2D` object that is the identity transform.
Unless this transform will be mutated later on, consider using
the faster :class:`IdentityTransform` class instead.
"""
return Affine2D()
def clear(self):
"""
Reset the underlying matrix to the identity transform.
"""
# A bit faster than np.identity(3).
self._mtx = IdentityTransform._mtx.copy()
self.invalidate()
return self
def rotate(self, theta):
"""
Add a rotation (in radians) to this transform in place.
Returns *self*, so this method can easily be chained with more
calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate`
and :meth:`scale`.
"""
a = np.cos(theta)
b = np.sin(theta)
rotate_mtx = np.array([[a, -b, 0.0], [b, a, 0.0], [0.0, 0.0, 1.0]],
float)
self._mtx = np.dot(rotate_mtx, self._mtx)
self.invalidate()
return self
def rotate_deg(self, degrees):
"""
Add a rotation (in degrees) to this transform in place.
Returns *self*, so this method can easily be chained with more
calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate`
and :meth:`scale`.
"""
return self.rotate(np.deg2rad(degrees))
def rotate_around(self, x, y, theta):
"""
Add a rotation (in radians) around the point (x, y) in place.
Returns *self*, so this method can easily be chained with more
calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate`
and :meth:`scale`.
"""
return self.translate(-x, -y).rotate(theta).translate(x, y)
def rotate_deg_around(self, x, y, degrees):
"""
Add a rotation (in degrees) around the point (x, y) in place.
Returns *self*, so this method can easily be chained with more
calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate`
and :meth:`scale`.
"""
# Cast to float to avoid wraparound issues with uint8's
x, y = float(x), float(y)
return self.translate(-x, -y).rotate_deg(degrees).translate(x, y)
def translate(self, tx, ty):
"""
Adds a translation in place.
Returns *self*, so this method can easily be chained with more
calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate`
and :meth:`scale`.
"""
translate_mtx = np.array(
[[1.0, 0.0, tx], [0.0, 1.0, ty], [0.0, 0.0, 1.0]], float)
self._mtx = np.dot(translate_mtx, self._mtx)
self.invalidate()
return self
def scale(self, sx, sy=None):
"""
Adds a scale in place.
If *sy* is None, the same scale is applied in both the *x*- and
*y*-directions.
Returns *self*, so this method can easily be chained with more
calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate`
and :meth:`scale`.
"""
if sy is None:
sy = sx
scale_mtx = np.array(
[[sx, 0.0, 0.0], [0.0, sy, 0.0], [0.0, 0.0, 1.0]], float)
self._mtx = np.dot(scale_mtx, self._mtx)
self.invalidate()
return self
def skew(self, xShear, yShear):
"""
Adds a skew in place.
*xShear* and *yShear* are the shear angles along the *x*- and
*y*-axes, respectively, in radians.
Returns *self*, so this method can easily be chained with more
calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate`
and :meth:`scale`.
"""
rotX = np.tan(xShear)
rotY = np.tan(yShear)
skew_mtx = np.array(
[[1.0, rotX, 0.0], [rotY, 1.0, 0.0], [0.0, 0.0, 1.0]], float)
self._mtx = np.dot(skew_mtx, self._mtx)
self.invalidate()
return self
def skew_deg(self, xShear, yShear):
"""
Adds a skew in place.
*xShear* and *yShear* are the shear angles along the *x*- and
*y*-axes, respectively, in degrees.
Returns *self*, so this method can easily be chained with more
calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate`
and :meth:`scale`.
"""
return self.skew(np.deg2rad(xShear), np.deg2rad(yShear))
class IdentityTransform(Affine2DBase):
"""
A special class that does one thing, the identity transform, in a
fast way.
"""
_mtx = np.identity(3)
def frozen(self):
# docstring inherited
return self
def __str__(self):
return ("{}()"
.format(type(self).__name__))
def get_matrix(self):
# docstring inherited
return self._mtx
def transform(self, points):
# docstring inherited
return np.asanyarray(points)
def transform_affine(self, points):
# docstring inherited
return np.asanyarray(points)
def transform_non_affine(self, points):
# docstring inherited
return np.asanyarray(points)
def transform_path(self, path):
# docstring inherited
return path
def transform_path_affine(self, path):
# docstring inherited
return path
def transform_path_non_affine(self, path):
# docstring inherited
return path
def get_affine(self):
# docstring inherited
return self
def inverted(self):
# docstring inherited
return self
class BlendedGenericTransform(Transform):
"""
A "blended" transform uses one transform for the *x*-direction, and
another transform for the *y*-direction.
This "generic" version can handle any given child transform in the
*x*- and *y*-directions.
"""
input_dims = 2
output_dims = 2
is_separable = True
pass_through = True
def __init__(self, x_transform, y_transform, **kwargs):
"""
Create a new "blended" transform using *x_transform* to
transform the *x*-axis and *y_transform* to transform the
*y*-axis.
You will generally not call this constructor directly but use the
`blended_transform_factory` function instead, which can determine
automatically which kind of blended transform to create.
"""
# Here we ask: "Does it blend?"
Transform.__init__(self, **kwargs)
self._x = x_transform
self._y = y_transform
self.set_children(x_transform, y_transform)
self._affine = None
def __eq__(self, other):
# Note, this is an exact copy of BlendedAffine2D.__eq__
if isinstance(other, (BlendedAffine2D, BlendedGenericTransform)):
return (self._x == other._x) and (self._y == other._y)
elif self._x == self._y:
return self._x == other
else:
return NotImplemented
def contains_branch_seperately(self, transform):
# Note, this is an exact copy of BlendedAffine2D.contains_branch_seperately
return self._x.contains_branch(transform), self._y.contains_branch(transform)
@property
def depth(self):
return max(self._x.depth, self._y.depth)
def contains_branch(self, other):
# a blended transform cannot possibly contain a branch from two different transforms.
return False
is_affine = property(lambda self: self._x.is_affine and self._y.is_affine)
has_inverse = property(
lambda self: self._x.has_inverse and self._y.has_inverse)
def frozen(self):
# docstring inherited
return blended_transform_factory(self._x.frozen(), self._y.frozen())
def __str__(self):
return ("{}(\n"
"{},\n"
"{})"
.format(type(self).__name__,
_indent_str(self._x),
_indent_str(self._y)))
def transform_non_affine(self, points):
# docstring inherited
if self._x.is_affine and self._y.is_affine:
return points
x = self._x
y = self._y
if x == y and x.input_dims == 2:
return x.transform_non_affine(points)
if x.input_dims == 2:
x_points = x.transform_non_affine(points)[:, 0:1]
else:
x_points = x.transform_non_affine(points[:, 0])
x_points = x_points.reshape((len(x_points), 1))
if y.input_dims == 2:
y_points = y.transform_non_affine(points)[:, 1:]
else:
y_points = y.transform_non_affine(points[:, 1])
y_points = y_points.reshape((len(y_points), 1))
if (isinstance(x_points, np.ma.MaskedArray) or
isinstance(y_points, np.ma.MaskedArray)):
return np.ma.concatenate((x_points, y_points), 1)
else:
return np.concatenate((x_points, y_points), 1)
def inverted(self):
# docstring inherited
return BlendedGenericTransform(self._x.inverted(), self._y.inverted())
def get_affine(self):
# docstring inherited
if self._invalid or self._affine is None:
if self._x == self._y:
self._affine = self._x.get_affine()
else:
x_mtx = self._x.get_affine().get_matrix()
y_mtx = self._y.get_affine().get_matrix()
# This works because we already know the transforms are
# separable, though normally one would want to set b and
# c to zero.
mtx = np.vstack((x_mtx[0], y_mtx[1], [0.0, 0.0, 1.0]))
self._affine = Affine2D(mtx)
self._invalid = 0
return self._affine
class BlendedAffine2D(Affine2DBase):
"""
A "blended" transform uses one transform for the *x*-direction, and
another transform for the *y*-direction.
This version is an optimization for the case where both child
transforms are of type :class:`Affine2DBase`.
"""
is_separable = True
def __init__(self, x_transform, y_transform, **kwargs):
"""
Create a new "blended" transform using *x_transform* to
transform the *x*-axis and *y_transform* to transform the
*y*-axis.
Both *x_transform* and *y_transform* must be 2D affine
transforms.
You will generally not call this constructor directly but use the
`blended_transform_factory` function instead, which can determine
automatically which kind of blended transform to create.
"""
is_affine = x_transform.is_affine and y_transform.is_affine
is_separable = x_transform.is_separable and y_transform.is_separable
is_correct = is_affine and is_separable
if not is_correct:
raise ValueError("Both *x_transform* and *y_transform* must be 2D "
"affine transforms")
Transform.__init__(self, **kwargs)
self._x = x_transform
self._y = y_transform
self.set_children(x_transform, y_transform)
Affine2DBase.__init__(self)
self._mtx = None
def __eq__(self, other):
# Note, this is an exact copy of BlendedGenericTransform.__eq__
if isinstance(other, (BlendedAffine2D, BlendedGenericTransform)):
return (self._x == other._x) and (self._y == other._y)
elif self._x == self._y:
return self._x == other
else:
return NotImplemented
def contains_branch_seperately(self, transform):
# Note, this is an exact copy of BlendedTransform.contains_branch_seperately
return self._x.contains_branch(transform), self._y.contains_branch(transform)
def __str__(self):
return ("{}(\n"
"{},\n"
"{})"
.format(type(self).__name__,
_indent_str(self._x),
_indent_str(self._y)))
def get_matrix(self):
# docstring inherited
if self._invalid:
if self._x == self._y:
self._mtx = self._x.get_matrix()
else:
x_mtx = self._x.get_matrix()
y_mtx = self._y.get_matrix()
# This works because we already know the transforms are
# separable, though normally one would want to set b and
# c to zero.
self._mtx = np.vstack((x_mtx[0], y_mtx[1], [0.0, 0.0, 1.0]))
self._inverted = None
self._invalid = 0
return self._mtx
def blended_transform_factory(x_transform, y_transform):
"""
Create a new "blended" transform using *x_transform* to transform
the *x*-axis and *y_transform* to transform the *y*-axis.
A faster version of the blended transform is returned for the case
where both child transforms are affine.
"""
if (isinstance(x_transform, Affine2DBase)
and isinstance(y_transform, Affine2DBase)):
return BlendedAffine2D(x_transform, y_transform)
return BlendedGenericTransform(x_transform, y_transform)
class CompositeGenericTransform(Transform):
"""
A composite transform formed by applying transform *a* then
transform *b*.
This "generic" version can handle any two arbitrary
transformations.
"""
pass_through = True
def __init__(self, a, b, **kwargs):
"""
Create a new composite transform that is the result of
applying transform *a* then transform *b*.
You will generally not call this constructor directly but use the
`composite_transform_factory` function instead, which can automatically
choose the best kind of composite transform instance to create.
"""
if a.output_dims != b.input_dims:
raise ValueError("The output dimension of 'a' must be equal to "
"the input dimensions of 'b'")
self.input_dims = a.input_dims
self.output_dims = b.output_dims
Transform.__init__(self, **kwargs)
self._a = a
self._b = b
self.set_children(a, b)
def frozen(self):
# docstring inherited
self._invalid = 0
frozen = composite_transform_factory(self._a.frozen(), self._b.frozen())
if not isinstance(frozen, CompositeGenericTransform):
return frozen.frozen()
return frozen
def _invalidate_internal(self, value, invalidating_node):
# In some cases for a composite transform, an invalidating call to AFFINE_ONLY needs
# to be extended to invalidate the NON_AFFINE part too. These cases are when the right
# hand transform is non-affine and either:
# (a) the left hand transform is non affine
# (b) it is the left hand node which has triggered the invalidation
if value == Transform.INVALID_AFFINE \
and not self._b.is_affine \
and (not self._a.is_affine or invalidating_node is self._a):
value = Transform.INVALID
Transform._invalidate_internal(self, value=value,
invalidating_node=invalidating_node)
def __eq__(self, other):
if isinstance(other, (CompositeGenericTransform, CompositeAffine2D)):
return self is other or (self._a == other._a
and self._b == other._b)
else:
return False
def _iter_break_from_left_to_right(self):
for left, right in self._a._iter_break_from_left_to_right():
yield left, right + self._b
for left, right in self._b._iter_break_from_left_to_right():
yield self._a + left, right
depth = property(lambda self: self._a.depth + self._b.depth)
is_affine = property(lambda self: self._a.is_affine and self._b.is_affine)
is_separable = property(
lambda self: self._a.is_separable and self._b.is_separable)
has_inverse = property(
lambda self: self._a.has_inverse and self._b.has_inverse)
def __str__(self):
return ("{}(\n"
"{},\n"
"{})"
.format(type(self).__name__,
_indent_str(self._a),
_indent_str(self._b)))
def transform_affine(self, points):
# docstring inherited
return self.get_affine().transform(points)
def transform_non_affine(self, points):
# docstring inherited
if self._a.is_affine and self._b.is_affine:
return points
elif not self._a.is_affine and self._b.is_affine:
return self._a.transform_non_affine(points)
else:
return self._b.transform_non_affine(
self._a.transform(points))
def transform_path_non_affine(self, path):
# docstring inherited
if self._a.is_affine and self._b.is_affine:
return path
elif not self._a.is_affine and self._b.is_affine:
return self._a.transform_path_non_affine(path)
else:
return self._b.transform_path_non_affine(
self._a.transform_path(path))
def get_affine(self):
# docstring inherited
if not self._b.is_affine:
return self._b.get_affine()
else:
return Affine2D(np.dot(self._b.get_affine().get_matrix(),
self._a.get_affine().get_matrix()))
def inverted(self):
# docstring inherited
return CompositeGenericTransform(self._b.inverted(), self._a.inverted())
class CompositeAffine2D(Affine2DBase):
"""
A composite transform formed by applying transform *a* then transform *b*.
This version is an optimization that handles the case where both *a*
and *b* are 2D affines.
"""
def __init__(self, a, b, **kwargs):
"""
Create a new composite transform that is the result of
applying transform *a* then transform *b*.
Both *a* and *b* must be instances of :class:`Affine2DBase`.
You will generally not call this constructor directly but use the
`composite_transform_factory` function instead, which can automatically
choose the best kind of composite transform instance to create.
"""
if not a.is_affine or not b.is_affine:
raise ValueError("'a' and 'b' must be affine transforms")
if a.output_dims != b.input_dims:
raise ValueError("The output dimension of 'a' must be equal to "
"the input dimensions of 'b'")
self.input_dims = a.input_dims
self.output_dims = b.output_dims
Affine2DBase.__init__(self, **kwargs)
self._a = a
self._b = b
self.set_children(a, b)
self._mtx = None
@property
def depth(self):
return self._a.depth + self._b.depth
def _iter_break_from_left_to_right(self):
for left, right in self._a._iter_break_from_left_to_right():
yield left, right + self._b
for left, right in self._b._iter_break_from_left_to_right():
yield self._a + left, right
def __str__(self):
return ("{}(\n"
"{},\n"
"{})"
.format(type(self).__name__,
_indent_str(self._a),
_indent_str(self._b)))
def get_matrix(self):
# docstring inherited
if self._invalid:
self._mtx = np.dot(
self._b.get_matrix(),
self._a.get_matrix())
self._inverted = None
self._invalid = 0
return self._mtx
def composite_transform_factory(a, b):
"""
Create a new composite transform that is the result of applying
transform a then transform b.
Shortcut versions of the blended transform are provided for the
case where both child transforms are affine, or one or the other
is the identity transform.
Composite transforms may also be created using the '+' operator,
e.g.::
c = a + b
"""
# check to see if any of a or b are IdentityTransforms. We use
# isinstance here to guarantee that the transforms will *always*
# be IdentityTransforms. Since TransformWrappers are mutable,
# use of equality here would be wrong.
if isinstance(a, IdentityTransform):
return b
elif isinstance(b, IdentityTransform):
return a
elif isinstance(a, Affine2D) and isinstance(b, Affine2D):
return CompositeAffine2D(a, b)
return CompositeGenericTransform(a, b)
class BboxTransform(Affine2DBase):
"""
`BboxTransform` linearly transforms points from one `Bbox` to another.
"""
is_separable = True
def __init__(self, boxin, boxout, **kwargs):
"""
Create a new :class:`BboxTransform` that linearly transforms
points from *boxin* to *boxout*.
"""
if not boxin.is_bbox or not boxout.is_bbox:
raise ValueError("'boxin' and 'boxout' must be bbox")
Affine2DBase.__init__(self, **kwargs)
self._boxin = boxin
self._boxout = boxout
self.set_children(boxin, boxout)
self._mtx = None
self._inverted = None
def __str__(self):
return ("{}(\n"
"{},\n"
"{})"
.format(type(self).__name__,
_indent_str(self._boxin),
_indent_str(self._boxout)))
def get_matrix(self):
# docstring inherited
if self._invalid:
inl, inb, inw, inh = self._boxin.bounds
outl, outb, outw, outh = self._boxout.bounds
x_scale = outw / inw
y_scale = outh / inh
if DEBUG and (x_scale == 0 or y_scale == 0):
raise ValueError("Transforming from or to a singular bounding box.")
self._mtx = np.array([[x_scale, 0.0 , (-inl*x_scale+outl)],
[0.0 , y_scale, (-inb*y_scale+outb)],
[0.0 , 0.0 , 1.0 ]],
float)
self._inverted = None
self._invalid = 0
return self._mtx
class BboxTransformTo(Affine2DBase):
"""
`BboxTransformTo` is a transformation that linearly transforms points from
the unit bounding box to a given `Bbox`.
"""
is_separable = True
def __init__(self, boxout, **kwargs):
"""
Create a new :class:`BboxTransformTo` that linearly transforms
points from the unit bounding box to *boxout*.
"""
if not boxout.is_bbox:
raise ValueError("'boxout' must be bbox")
Affine2DBase.__init__(self, **kwargs)
self._boxout = boxout
self.set_children(boxout)
self._mtx = None
self._inverted = None
def __str__(self):
return ("{}(\n"
"{})"
.format(type(self).__name__,
_indent_str(self._boxout)))
def get_matrix(self):
# docstring inherited
if self._invalid:
outl, outb, outw, outh = self._boxout.bounds
if DEBUG and (outw == 0 or outh == 0):
raise ValueError("Transforming to a singular bounding box.")
self._mtx = np.array([[outw, 0.0, outl],
[ 0.0, outh, outb],
[ 0.0, 0.0, 1.0]],
float)
self._inverted = None
self._invalid = 0
return self._mtx
class BboxTransformToMaxOnly(BboxTransformTo):
"""
`BboxTransformTo` is a transformation that linearly transforms points from
the unit bounding box to a given `Bbox` with a fixed upper left of (0, 0).
"""
def get_matrix(self):
# docstring inherited
if self._invalid:
xmax, ymax = self._boxout.max
if DEBUG and (xmax == 0 or ymax == 0):
raise ValueError("Transforming to a singular bounding box.")
self._mtx = np.array([[xmax, 0.0, 0.0],
[ 0.0, ymax, 0.0],
[ 0.0, 0.0, 1.0]],
float)
self._inverted = None
self._invalid = 0
return self._mtx
class BboxTransformFrom(Affine2DBase):
"""
`BboxTransformFrom` linearly transforms points from a given `Bbox` to the
unit bounding box.
"""
is_separable = True
def __init__(self, boxin, **kwargs):
if not boxin.is_bbox:
raise ValueError("'boxin' must be bbox")
Affine2DBase.__init__(self, **kwargs)
self._boxin = boxin
self.set_children(boxin)
self._mtx = None
self._inverted = None
def __str__(self):
return ("{}(\n"
"{})"
.format(type(self).__name__,
_indent_str(self._boxin)))
def get_matrix(self):
# docstring inherited
if self._invalid:
inl, inb, inw, inh = self._boxin.bounds
if DEBUG and (inw == 0 or inh == 0):
raise ValueError("Transforming from a singular bounding box.")
x_scale = 1.0 / inw
y_scale = 1.0 / inh
self._mtx = np.array([[x_scale, 0.0 , (-inl*x_scale)],
[0.0 , y_scale, (-inb*y_scale)],
[0.0 , 0.0 , 1.0 ]],
float)
self._inverted = None
self._invalid = 0
return self._mtx
class ScaledTranslation(Affine2DBase):
"""
A transformation that translates by *xt* and *yt*, after *xt* and *yt*
have been transformed by *scale_trans*.
"""
def __init__(self, xt, yt, scale_trans, **kwargs):
Affine2DBase.__init__(self, **kwargs)
self._t = (xt, yt)
self._scale_trans = scale_trans
self.set_children(scale_trans)
self._mtx = None
self._inverted = None
def __str__(self):
return ("{}(\n"
"{})"
.format(type(self).__name__,
_indent_str(self._t)))
def get_matrix(self):
# docstring inherited
if self._invalid:
xt, yt = self._scale_trans.transform_point(self._t)
self._mtx = np.array([[1.0, 0.0, xt],
[0.0, 1.0, yt],
[0.0, 0.0, 1.0]],
float)
self._invalid = 0
self._inverted = None
return self._mtx
class TransformedPath(TransformNode):
"""
A `TransformedPath` caches a non-affine transformed copy of the
`~.path.Path`. This cached copy is automatically updated when the
non-affine part of the transform changes.
.. note::
Paths are considered immutable by this class. Any update to the
path's vertices/codes will not trigger a transform recomputation.
"""
def __init__(self, path, transform):
"""
Parameters
----------
path : `~.path.Path`
transform : `Transform`
"""
if not isinstance(transform, Transform):
raise ValueError("'transform' must be an instance of "
"'matplotlib.transform.Transform'")
TransformNode.__init__(self)
self._path = path
self._transform = transform
self.set_children(transform)
self._transformed_path = None
self._transformed_points = None
def _revalidate(self):
# only recompute if the invalidation includes the non_affine part of the transform
if ((self._invalid & self.INVALID_NON_AFFINE == self.INVALID_NON_AFFINE)
or self._transformed_path is None):
self._transformed_path = \
self._transform.transform_path_non_affine(self._path)
self._transformed_points = \
Path._fast_from_codes_and_verts(
self._transform.transform_non_affine(self._path.vertices),
None, self._path)
self._invalid = 0
def get_transformed_points_and_affine(self):
"""
Return a copy of the child path, with the non-affine part of
the transform already applied, along with the affine part of
the path necessary to complete the transformation. Unlike
:meth:`get_transformed_path_and_affine`, no interpolation will
be performed.
"""
self._revalidate()
return self._transformed_points, self.get_affine()
def get_transformed_path_and_affine(self):
"""
Return a copy of the child path, with the non-affine part of
the transform already applied, along with the affine part of
the path necessary to complete the transformation.
"""
self._revalidate()
return self._transformed_path, self.get_affine()
def get_fully_transformed_path(self):
"""
Return a fully-transformed copy of the child path.
"""
self._revalidate()
return self._transform.transform_path_affine(self._transformed_path)
def get_affine(self):
return self._transform.get_affine()
class TransformedPatchPath(TransformedPath):
"""
A `TransformedPatchPath` caches a non-affine transformed copy of the
`~.patch.Patch`. This cached copy is automatically updated when the
non-affine part of the transform or the patch changes.
"""
def __init__(self, patch):
"""
Parameters
----------
patch : `~.patches.Patch`
"""
TransformNode.__init__(self)
transform = patch.get_transform()
self._patch = patch
self._transform = transform
self.set_children(transform)
self._path = patch.get_path()
self._transformed_path = None
self._transformed_points = None
def _revalidate(self):
patch_path = self._patch.get_path()
# Only recompute if the invalidation includes the non_affine part of
# the transform, or the Patch's Path has changed.
if (self._transformed_path is None or self._path != patch_path or
(self._invalid & self.INVALID_NON_AFFINE ==
self.INVALID_NON_AFFINE)):
self._path = patch_path
self._transformed_path = \
self._transform.transform_path_non_affine(patch_path)
self._transformed_points = \
Path._fast_from_codes_and_verts(
self._transform.transform_non_affine(patch_path.vertices),
None, patch_path)
self._invalid = 0
def nonsingular(vmin, vmax, expander=0.001, tiny=1e-15, increasing=True):
"""
Modify the endpoints of a range as needed to avoid singularities.
Parameters
----------
vmin, vmax : float
The initial endpoints.
expander : float, optional, default: 0.001
Fractional amount by which *vmin* and *vmax* are expanded if
the original interval is too small, based on *tiny*.
tiny : float, optional, default: 1e-15
Threshold for the ratio of the interval to the maximum absolute
value of its endpoints. If the interval is smaller than
this, it will be expanded. This value should be around
1e-15 or larger; otherwise the interval will be approaching
the double precision resolution limit.
increasing : bool, optional, default: True
If True, swap *vmin*, *vmax* if *vmin* > *vmax*.
Returns
-------
vmin, vmax : float
Endpoints, expanded and/or swapped if necessary.
If either input is inf or NaN, or if both inputs are 0 or very
close to zero, it returns -*expander*, *expander*.
"""
if (not np.isfinite(vmin)) or (not np.isfinite(vmax)):
return -expander, expander
swapped = False
if vmax < vmin:
vmin, vmax = vmax, vmin
swapped = True
maxabsvalue = max(abs(vmin), abs(vmax))
if maxabsvalue < (1e6 / tiny) * np.finfo(float).tiny:
vmin = -expander
vmax = expander
elif vmax - vmin <= maxabsvalue * tiny:
if vmax == 0 and vmin == 0:
vmin = -expander
vmax = expander
else:
vmin -= expander*abs(vmin)
vmax += expander*abs(vmax)
if swapped and not increasing:
vmin, vmax = vmax, vmin
return vmin, vmax
def interval_contains(interval, val):
"""
Check, inclusively, whether an interval includes a given value.
Parameters
----------
interval : sequence of scalar
A 2-length sequence, endpoints that define the interval.
val : scalar
Value to check is within interval.
Returns
-------
bool
Returns *True* if given *val* is within the *interval*.
"""
a, b = interval
if a > b:
a, b = b, a
return a <= val <= b
def _interval_contains_close(interval, val, rtol=1e-10):
"""
Check, inclusively, whether an interval includes a given value, with the
interval expanded by a small tolerance to admit floating point errors.
Parameters
----------
interval : sequence of scalar
A 2-length sequence, endpoints that define the interval.
val : scalar
Value to check is within interval.
rtol : scalar
Tolerance slippage allowed outside of this interval. Default
1e-10 * (b - a).
Returns
-------
bool
Returns *True* if given *val* is within the *interval* (with tolerance)
"""
a, b = interval
if a > b:
a, b = b, a
rtol = (b - a) * rtol
return a - rtol <= val <= b + rtol
def interval_contains_open(interval, val):
"""
Check, excluding endpoints, whether an interval includes a given value.
Parameters
----------
interval : sequence of scalar
A 2-length sequence, endpoints that define the interval.
val : scalar
Value to check is within interval.
Returns
-------
bool
Returns true if given val is within the interval.
"""
a, b = interval
return a < val < b or a > val > b
def offset_copy(trans, fig=None, x=0.0, y=0.0, units='inches'):
"""
Return a new transform with an added offset.
Parameters
----------
trans : :class:`Transform` instance
Any transform, to which offset will be applied.
fig : :class:`~matplotlib.figure.Figure`, optional, default: None
Current figure. It can be None if *units* are 'dots'.
x, y : float, optional, default: 0.0
Specifies the offset to apply.
units : {'inches', 'points', 'dots'}, optional
Units of the offset.
Returns
-------
trans : :class:`Transform` instance
Transform with applied offset.
"""
if units == 'dots':
return trans + Affine2D().translate(x, y)
if fig is None:
raise ValueError('For units of inches or points a fig kwarg is needed')
if units == 'points':
x /= 72.0
y /= 72.0
elif not units == 'inches':
raise ValueError('units must be dots, points, or inches')
return trans + ScaledTranslation(x, y, fig.dpi_scale_trans)
|
ac205ad7a6cb4775cd0236363633825db4c579f51c0e99b372c475c8f6137e34
|
"""
Plotting of string "category" data: ``plot(['d', 'f', 'a'], [1, 2, 3])`` will
plot three points with x-axis values of 'd', 'f', 'a'.
See :doc:`/gallery/lines_bars_and_markers/categorical_variables` for an
example.
The module uses Matplotlib's `matplotlib.units` mechanism to convert from
strings to integers and provides a tick locator, a tick formatter, and the
`.UnitData` class that creates and stores the string-to-integer mapping.
"""
from collections import OrderedDict
import dateutil.parser
import itertools
import logging
import numpy as np
import matplotlib.cbook as cbook
import matplotlib.units as units
import matplotlib.ticker as ticker
_log = logging.getLogger(__name__)
class StrCategoryConverter(units.ConversionInterface):
@staticmethod
def convert(value, unit, axis):
"""
Convert strings in *value* to floats using mapping information stored
in the *unit* object.
Parameters
----------
value : string or iterable
Value or list of values to be converted.
unit : `.UnitData`
An object mapping strings to integers.
axis : `~matplotlib.axis.Axis`
The axis on which the converted value is plotted.
.. note:: *axis* is unused.
Returns
-------
mapped_value : float or ndarray[float]
"""
if unit is None:
raise ValueError(
'Missing category information for StrCategoryConverter; '
'this might be caused by unintendedly mixing categorical and '
'numeric data')
# dtype = object preserves numerical pass throughs
values = np.atleast_1d(np.array(value, dtype=object))
# pass through sequence of non binary numbers
if all(units.ConversionInterface.is_numlike(v)
and not isinstance(v, (str, bytes))
for v in values):
return np.asarray(values, dtype=float)
# force an update so it also does type checking
unit.update(values)
return np.vectorize(unit._mapping.__getitem__, otypes=[float])(values)
@staticmethod
def axisinfo(unit, axis):
"""
Set the default axis ticks and labels.
Parameters
----------
unit : `.UnitData`
object string unit information for value
axis : `~matplotlib.axis.Axis`
axis for which information is being set
Returns
-------
axisinfo : `~matplotlib.units.AxisInfo`
Information to support default tick labeling
.. note: axis is not used
"""
# locator and formatter take mapping dict because
# args need to be pass by reference for updates
majloc = StrCategoryLocator(unit._mapping)
majfmt = StrCategoryFormatter(unit._mapping)
return units.AxisInfo(majloc=majloc, majfmt=majfmt)
@staticmethod
def default_units(data, axis):
"""
Set and update the `~matplotlib.axis.Axis` units.
Parameters
----------
data : string or iterable of strings
axis : `~matplotlib.axis.Axis`
axis on which the data is plotted
Returns
-------
class : `.UnitData`
object storing string to integer mapping
"""
# the conversion call stack is default_units -> axis_info -> convert
if axis.units is None:
axis.set_units(UnitData(data))
else:
axis.units.update(data)
return axis.units
class StrCategoryLocator(ticker.Locator):
"""Tick at every integer mapping of the string data."""
def __init__(self, units_mapping):
"""
Parameters
-----------
units_mapping : Dict[str, int]
"""
self._units = units_mapping
def __call__(self):
return list(self._units.values())
def tick_values(self, vmin, vmax):
return self()
class StrCategoryFormatter(ticker.Formatter):
"""String representation of the data at every tick."""
def __init__(self, units_mapping):
"""
Parameters
----------
units_mapping : Dict[Str, int]
"""
self._units = units_mapping
def __call__(self, x, pos=None):
return '' if pos is None else self.format_ticks([x])[0]
def format_ticks(self, values):
r_mapping = {v: self._text(k) for k, v in self._units.items()}
return [r_mapping.get(round(val), '') for val in values]
@staticmethod
def _text(value):
"""Convert text values into utf-8 or ascii strings."""
if isinstance(value, bytes):
value = value.decode(encoding='utf-8')
elif not isinstance(value, str):
value = str(value)
return value
class UnitData(object):
def __init__(self, data=None):
"""
Create mapping between unique categorical values and integer ids.
Parameters
----------
data : iterable
sequence of string values
"""
self._mapping = OrderedDict()
self._counter = itertools.count()
if data is not None:
self.update(data)
@staticmethod
def _str_is_convertible(val):
"""
Helper method to check whether a string can be parsed as float or date.
"""
try:
float(val)
except ValueError:
try:
dateutil.parser.parse(val)
except ValueError:
return False
return True
def update(self, data):
"""
Map new values to integer identifiers.
Parameters
----------
data : iterable
sequence of string values
Raises
------
TypeError
If the value in data is not a string, unicode, bytes type
"""
data = np.atleast_1d(np.array(data, dtype=object))
# check if convertible to number:
convertible = True
for val in OrderedDict.fromkeys(data):
# OrderedDict just iterates over unique values in data.
if not isinstance(val, (str, bytes)):
raise TypeError("{val!r} is not a string".format(val=val))
if convertible:
# this will only be called so long as convertible is True.
convertible = self._str_is_convertible(val)
if val not in self._mapping:
self._mapping[val] = next(self._counter)
if convertible:
_log.info('Using categorical units to plot a list of strings '
'that are all parsable as floats or dates. If these '
'strings should be plotted as numbers, cast to the '
'appropriate data type before plotting.')
# Register the converter with Matplotlib's unit framework
units.registry[str] = StrCategoryConverter()
units.registry[np.str_] = StrCategoryConverter()
units.registry[bytes] = StrCategoryConverter()
units.registry[np.bytes_] = StrCategoryConverter()
|
23773054cb0c4bcc6a575f414f673136736ff2592592a372f372e0856c6dd247
|
"""
A module for parsing and generating `fontconfig patterns`_.
.. _fontconfig patterns:
https://www.freedesktop.org/software/fontconfig/fontconfig-user.html
"""
# This class is defined here because it must be available in:
# - The old-style config framework (:file:`rcsetup.py`)
# - The font manager (:file:`font_manager.py`)
# It probably logically belongs in :file:`font_manager.py`, but placing it
# there would have created cyclical dependency problems.
from functools import lru_cache
import re
from pyparsing import (Literal, ZeroOrMore, Optional, Regex, StringEnd,
ParseException, Suppress)
family_punc = r'\\\-:,'
family_unescape = re.compile(r'\\([%s])' % family_punc).sub
family_escape = re.compile(r'([%s])' % family_punc).sub
value_punc = r'\\=_:,'
value_unescape = re.compile(r'\\([%s])' % value_punc).sub
value_escape = re.compile(r'([%s])' % value_punc).sub
class FontconfigPatternParser(object):
"""
A simple pyparsing-based parser for `fontconfig patterns`_.
.. _fontconfig patterns:
https://www.freedesktop.org/software/fontconfig/fontconfig-user.html
"""
_constants = {
'thin' : ('weight', 'light'),
'extralight' : ('weight', 'light'),
'ultralight' : ('weight', 'light'),
'light' : ('weight', 'light'),
'book' : ('weight', 'book'),
'regular' : ('weight', 'regular'),
'normal' : ('weight', 'normal'),
'medium' : ('weight', 'medium'),
'demibold' : ('weight', 'demibold'),
'semibold' : ('weight', 'semibold'),
'bold' : ('weight', 'bold'),
'extrabold' : ('weight', 'extra bold'),
'black' : ('weight', 'black'),
'heavy' : ('weight', 'heavy'),
'roman' : ('slant', 'normal'),
'italic' : ('slant', 'italic'),
'oblique' : ('slant', 'oblique'),
'ultracondensed' : ('width', 'ultra-condensed'),
'extracondensed' : ('width', 'extra-condensed'),
'condensed' : ('width', 'condensed'),
'semicondensed' : ('width', 'semi-condensed'),
'expanded' : ('width', 'expanded'),
'extraexpanded' : ('width', 'extra-expanded'),
'ultraexpanded' : ('width', 'ultra-expanded')
}
def __init__(self):
family = Regex(r'([^%s]|(\\[%s]))*' %
(family_punc, family_punc)) \
.setParseAction(self._family)
size = Regex(r"([0-9]+\.?[0-9]*|\.[0-9]+)") \
.setParseAction(self._size)
name = Regex(r'[a-z]+') \
.setParseAction(self._name)
value = Regex(r'([^%s]|(\\[%s]))*' %
(value_punc, value_punc)) \
.setParseAction(self._value)
families =(family
+ ZeroOrMore(
Literal(',')
+ family)
).setParseAction(self._families)
point_sizes =(size
+ ZeroOrMore(
Literal(',')
+ size)
).setParseAction(self._point_sizes)
property =( (name
+ Suppress(Literal('='))
+ value
+ ZeroOrMore(
Suppress(Literal(','))
+ value)
)
| name
).setParseAction(self._property)
pattern =(Optional(
families)
+ Optional(
Literal('-')
+ point_sizes)
+ ZeroOrMore(
Literal(':')
+ property)
+ StringEnd()
)
self._parser = pattern
self.ParseException = ParseException
def parse(self, pattern):
"""
Parse the given fontconfig *pattern* and return a dictionary
of key/value pairs useful for initializing a
:class:`font_manager.FontProperties` object.
"""
props = self._properties = {}
try:
self._parser.parseString(pattern)
except self.ParseException as e:
raise ValueError(
"Could not parse font string: '%s'\n%s" % (pattern, e))
self._properties = None
self._parser.resetCache()
return props
def _family(self, s, loc, tokens):
return [family_unescape(r'\1', str(tokens[0]))]
def _size(self, s, loc, tokens):
return [float(tokens[0])]
def _name(self, s, loc, tokens):
return [str(tokens[0])]
def _value(self, s, loc, tokens):
return [value_unescape(r'\1', str(tokens[0]))]
def _families(self, s, loc, tokens):
self._properties['family'] = [str(x) for x in tokens]
return []
def _point_sizes(self, s, loc, tokens):
self._properties['size'] = [str(x) for x in tokens]
return []
def _property(self, s, loc, tokens):
if len(tokens) == 1:
if tokens[0] in self._constants:
key, val = self._constants[tokens[0]]
self._properties.setdefault(key, []).append(val)
else:
key = tokens[0]
val = tokens[1:]
self._properties.setdefault(key, []).extend(val)
return []
# `parse_fontconfig_pattern` is a bottleneck during the tests because it is
# repeatedly called when the rcParams are reset (to validate the default
# fonts). In practice, the cache size doesn't grow beyond a few dozen entries
# during the test suite.
parse_fontconfig_pattern = lru_cache()(FontconfigPatternParser().parse)
def generate_fontconfig_pattern(d):
"""
Given a dictionary of key/value pairs, generates a fontconfig
pattern string.
"""
props = []
for key in 'family style variant weight stretch file size'.split():
val = getattr(d, 'get_' + key)()
if val is not None and val != []:
if type(val) == list:
val = [value_escape(r'\\\1', str(x)) for x in val
if x is not None]
if val != []:
val = ','.join(val)
props.append(":%s=%s" % (key, val))
return ''.join(props)
|
1d7dac4b9b846bdc445e01c9b661432c429d01e9b3ab105ef24f4ef05bbcc245
|
"""
Classes for the efficient drawing of large collections of objects that
share most properties, e.g., a large number of line segments or
polygons.
The classes are not meant to be as flexible as their single element
counterparts (e.g., you may not be able to select all line styles) but
they are meant to be fast for common use cases (e.g., a large set of solid
line segments).
"""
import math
from numbers import Number
import numpy as np
import matplotlib as mpl
from . import (_path, artist, cbook, cm, colors as mcolors, docstring,
lines as mlines, path as mpath, transforms)
import warnings
@cbook._define_aliases({
"antialiased": ["antialiaseds", "aa"],
"edgecolor": ["edgecolors", "ec"],
"facecolor": ["facecolors", "fc"],
"linestyle": ["linestyles", "dashes", "ls"],
"linewidth": ["linewidths", "lw"],
})
class Collection(artist.Artist, cm.ScalarMappable):
"""
Base class for Collections. Must be subclassed to be usable.
All properties in a collection must be sequences or scalars;
if scalars, they will be converted to sequences. The
property of the ith element of the collection is::
prop[i % len(props)]
Exceptions are *capstyle* and *joinstyle* properties, these can
only be set globally for the whole collection.
Keyword arguments and default values:
* *edgecolors*: None
* *facecolors*: None
* *linewidths*: None
* *capstyle*: None
* *joinstyle*: None
* *antialiaseds*: None
* *offsets*: None
* *transOffset*: transforms.IdentityTransform()
* *offset_position*: 'screen' (default) or 'data'
* *norm*: None (optional for
:class:`matplotlib.cm.ScalarMappable`)
* *cmap*: None (optional for
:class:`matplotlib.cm.ScalarMappable`)
* *hatch*: None
* *zorder*: 1
*offsets* and *transOffset* are used to translate the patch after
rendering (default no offsets). If offset_position is 'screen'
(default) the offset is applied after the master transform has
been applied, that is, the offsets are in screen coordinates. If
offset_position is 'data', the offset is applied before the master
transform, i.e., the offsets are in data coordinates.
If any of *edgecolors*, *facecolors*, *linewidths*, *antialiaseds*
are None, they default to their :data:`matplotlib.rcParams` patch
setting, in sequence form.
The use of :class:`~matplotlib.cm.ScalarMappable` is optional. If
the :class:`~matplotlib.cm.ScalarMappable` matrix _A is not None
(i.e., a call to set_array has been made), at draw time a call to
scalar mappable will be made to set the face colors.
"""
_offsets = np.zeros((0, 2))
_transOffset = transforms.IdentityTransform()
#: Either a list of 3x3 arrays or an Nx3x3 array of transforms, suitable
#: for the `all_transforms` argument to
#: :meth:`~matplotlib.backend_bases.RendererBase.draw_path_collection`;
#: each 3x3 array is used to initialize an
#: :class:`~matplotlib.transforms.Affine2D` object.
#: Each kind of collection defines this based on its arguments.
_transforms = np.empty((0, 3, 3))
# Whether to draw an edge by default. Set on a
# subclass-by-subclass basis.
_edge_default = False
def __init__(self,
edgecolors=None,
facecolors=None,
linewidths=None,
linestyles='solid',
capstyle=None,
joinstyle=None,
antialiaseds=None,
offsets=None,
transOffset=None,
norm=None, # optional for ScalarMappable
cmap=None, # ditto
pickradius=5.0,
hatch=None,
urls=None,
offset_position='screen',
zorder=1,
**kwargs
):
"""
Create a Collection
%(Collection)s
"""
artist.Artist.__init__(self)
cm.ScalarMappable.__init__(self, norm, cmap)
# list of un-scaled dash patterns
# this is needed scaling the dash pattern by linewidth
self._us_linestyles = [(None, None)]
# list of dash patterns
self._linestyles = [(None, None)]
# list of unbroadcast/scaled linewidths
self._us_lw = [0]
self._linewidths = [0]
self._is_filled = True # May be modified by set_facecolor().
self._hatch_color = mcolors.to_rgba(mpl.rcParams['hatch.color'])
self.set_facecolor(facecolors)
self.set_edgecolor(edgecolors)
self.set_linewidth(linewidths)
self.set_linestyle(linestyles)
self.set_antialiased(antialiaseds)
self.set_pickradius(pickradius)
self.set_urls(urls)
self.set_hatch(hatch)
self.set_offset_position(offset_position)
self.set_zorder(zorder)
if capstyle:
self.set_capstyle(capstyle)
else:
self._capstyle = None
if joinstyle:
self.set_joinstyle(joinstyle)
else:
self._joinstyle = None
self._offsets = np.zeros((1, 2))
self._uniform_offsets = None
if offsets is not None:
offsets = np.asanyarray(offsets, float)
# Broadcast (2,) -> (1, 2) but nothing else.
if offsets.shape == (2,):
offsets = offsets[None, :]
if transOffset is not None:
self._offsets = offsets
self._transOffset = transOffset
else:
self._uniform_offsets = offsets
self._path_effects = None
self.update(kwargs)
self._paths = None
def get_paths(self):
return self._paths
def set_paths(self):
raise NotImplementedError
def get_transforms(self):
return self._transforms
def get_offset_transform(self):
t = self._transOffset
if (not isinstance(t, transforms.Transform)
and hasattr(t, '_as_mpl_transform')):
t = t._as_mpl_transform(self.axes)
return t
def get_datalim(self, transData):
transform = self.get_transform()
transOffset = self.get_offset_transform()
offsets = self._offsets
paths = self.get_paths()
if not transform.is_affine:
paths = [transform.transform_path_non_affine(p) for p in paths]
transform = transform.get_affine()
if not transOffset.is_affine:
offsets = transOffset.transform_non_affine(offsets)
transOffset = transOffset.get_affine()
if isinstance(offsets, np.ma.MaskedArray):
offsets = offsets.filled(np.nan)
# get_path_collection_extents handles nan but not masked arrays
if len(paths) and len(offsets):
result = mpath.get_path_collection_extents(
transform.frozen(), paths, self.get_transforms(),
offsets, transOffset.frozen())
result = result.inverse_transformed(transData)
else:
result = transforms.Bbox.null()
return result
def get_window_extent(self, renderer):
# TODO: check to ensure that this does not fail for
# cases other than scatter plot legend
return self.get_datalim(transforms.IdentityTransform())
def _prepare_points(self):
# Helper for drawing and hit testing.
transform = self.get_transform()
transOffset = self.get_offset_transform()
offsets = self._offsets
paths = self.get_paths()
if self.have_units():
paths = []
for path in self.get_paths():
vertices = path.vertices
xs, ys = vertices[:, 0], vertices[:, 1]
xs = self.convert_xunits(xs)
ys = self.convert_yunits(ys)
paths.append(mpath.Path(np.column_stack([xs, ys]), path.codes))
if offsets.size:
xs = self.convert_xunits(offsets[:, 0])
ys = self.convert_yunits(offsets[:, 1])
offsets = np.column_stack([xs, ys])
if not transform.is_affine:
paths = [transform.transform_path_non_affine(path)
for path in paths]
transform = transform.get_affine()
if not transOffset.is_affine:
offsets = transOffset.transform_non_affine(offsets)
# This might have changed an ndarray into a masked array.
transOffset = transOffset.get_affine()
if isinstance(offsets, np.ma.MaskedArray):
offsets = offsets.filled(np.nan)
# Changing from a masked array to nan-filled ndarray
# is probably most efficient at this point.
return transform, transOffset, offsets, paths
@artist.allow_rasterization
def draw(self, renderer):
if not self.get_visible():
return
renderer.open_group(self.__class__.__name__, self.get_gid())
self.update_scalarmappable()
transform, transOffset, offsets, paths = self._prepare_points()
gc = renderer.new_gc()
self._set_gc_clip(gc)
gc.set_snap(self.get_snap())
if self._hatch:
gc.set_hatch(self._hatch)
try:
gc.set_hatch_color(self._hatch_color)
except AttributeError:
# if we end up with a GC that does not have this method
cbook.warn_deprecated(
"3.1", message="Your backend does not support setting the "
"hatch color; such backends will become unsupported in "
"Matplotlib 3.3.")
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)
# If the collection is made up of a single shape/color/stroke,
# it can be rendered once and blitted multiple times, using
# `draw_markers` rather than `draw_path_collection`. This is
# *much* faster for Agg, and results in smaller file sizes in
# PDF/SVG/PS.
trans = self.get_transforms()
facecolors = self.get_facecolor()
edgecolors = self.get_edgecolor()
do_single_path_optimization = False
if (len(paths) == 1 and len(trans) <= 1 and
len(facecolors) == 1 and len(edgecolors) == 1 and
len(self._linewidths) == 1 and
self._linestyles == [(None, None)] and
len(self._antialiaseds) == 1 and len(self._urls) == 1 and
self.get_hatch() is None):
if len(trans):
combined_transform = (transforms.Affine2D(trans[0]) +
transform)
else:
combined_transform = transform
extents = paths[0].get_extents(combined_transform)
width, height = renderer.get_canvas_width_height()
if extents.width < width and extents.height < height:
do_single_path_optimization = True
if self._joinstyle:
gc.set_joinstyle(self._joinstyle)
if self._capstyle:
gc.set_capstyle(self._capstyle)
if do_single_path_optimization:
gc.set_foreground(tuple(edgecolors[0]))
gc.set_linewidth(self._linewidths[0])
gc.set_dashes(*self._linestyles[0])
gc.set_antialiased(self._antialiaseds[0])
gc.set_url(self._urls[0])
renderer.draw_markers(
gc, paths[0], combined_transform.frozen(),
mpath.Path(offsets), transOffset, tuple(facecolors[0]))
else:
renderer.draw_path_collection(
gc, transform.frozen(), paths,
self.get_transforms(), offsets, transOffset,
self.get_facecolor(), self.get_edgecolor(),
self._linewidths, self._linestyles,
self._antialiaseds, self._urls,
self._offset_position)
gc.restore()
renderer.close_group(self.__class__.__name__)
self.stale = False
def set_pickradius(self, pr):
"""
Set the pick radius used for containment tests.
Parameters
----------
d : float
Pick radius, in points.
"""
self._pickradius = pr
def get_pickradius(self):
return self._pickradius
def contains(self, mouseevent):
"""
Test whether the mouse event occurred in the collection.
Returns ``bool, dict(ind=itemlist)``, where every item in itemlist
contains the event.
"""
if self._contains is not None:
return self._contains(self, mouseevent)
if not self.get_visible():
return False, {}
pickradius = (
float(self._picker)
if isinstance(self._picker, Number) and
self._picker is not True # the bool, not just nonzero or 1
else self._pickradius)
transform, transOffset, offsets, paths = self._prepare_points()
ind = _path.point_in_path_collection(
mouseevent.x, mouseevent.y, pickradius,
transform.frozen(), paths, self.get_transforms(),
offsets, transOffset, pickradius <= 0,
self.get_offset_position())
return len(ind) > 0, dict(ind=ind)
def set_urls(self, urls):
"""
Parameters
----------
urls : List[str] or None
"""
self._urls = urls if urls is not None else [None]
self.stale = True
def get_urls(self):
return self._urls
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.
Hatching is supported in the PostScript, PDF, SVG and Agg
backends only.
Unlike other properties such as linewidth and colors, hatching
can only be specified for the collection as a whole, not separately
for each member.
Parameters
----------
hatch : {'/', '\\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
"""
self._hatch = hatch
self.stale = True
def get_hatch(self):
"""Return the current hatching pattern."""
return self._hatch
def set_offsets(self, offsets):
"""
Set the offsets for the collection.
Parameters
----------
offsets : float or sequence of floats
"""
offsets = np.asanyarray(offsets, float)
if offsets.shape == (2,): # Broadcast (2,) -> (1, 2) but nothing else.
offsets = offsets[None, :]
# This decision is based on how they are initialized above in __init__.
if self._uniform_offsets is None:
self._offsets = offsets
else:
self._uniform_offsets = offsets
self.stale = True
def get_offsets(self):
"""Return the offsets for the collection."""
# This decision is based on how they are initialized above in __init__.
if self._uniform_offsets is None:
return self._offsets
else:
return self._uniform_offsets
def set_offset_position(self, offset_position):
"""
Set how offsets are applied. If *offset_position* is 'screen'
(default) the offset is applied after the master transform has
been applied, that is, the offsets are in screen coordinates.
If offset_position is 'data', the offset is applied before the
master transform, i.e., the offsets are in data coordinates.
Parameters
----------
offset_position : {'screen', 'data'}
"""
cbook._check_in_list(['screen', 'data'],
offset_position=offset_position)
self._offset_position = offset_position
self.stale = True
def get_offset_position(self):
"""
Returns how offsets are applied for the collection. If
*offset_position* is 'screen', the offset is applied after the
master transform has been applied, that is, the offsets are in
screen coordinates. If offset_position is 'data', the offset
is applied before the master transform, i.e., the offsets are
in data coordinates.
"""
return self._offset_position
def set_linewidth(self, lw):
"""
Set the linewidth(s) for the collection. *lw* can be a scalar
or a sequence; if it is a sequence the patches will cycle
through the sequence
Parameters
----------
lw : float or sequence of floats
"""
if lw is None:
lw = mpl.rcParams['patch.linewidth']
if lw is None:
lw = mpl.rcParams['lines.linewidth']
# get the un-scaled/broadcast lw
self._us_lw = np.atleast_1d(np.asarray(lw))
# scale all of the dash patterns.
self._linewidths, self._linestyles = self._bcast_lwls(
self._us_lw, self._us_linestyles)
self.stale = True
def set_linestyle(self, ls):
"""
Set the linestyle(s) for the collection.
=========================== =================
linestyle description
=========================== =================
``'-'`` or ``'solid'`` solid line
``'--'`` or ``'dashed'`` dashed line
``'-.'`` or ``'dashdot'`` dash-dotted line
``':'`` or ``'dotted'`` dotted line
=========================== =================
Alternatively a dash tuple of the following form can be provided::
(offset, onoffseq),
where ``onoffseq`` is an even length tuple of on and off ink in points.
Parameters
----------
ls : {'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
The line style.
"""
try:
if isinstance(ls, str):
ls = cbook.ls_mapper.get(ls, ls)
dashes = [mlines._get_dash_pattern(ls)]
else:
try:
dashes = [mlines._get_dash_pattern(ls)]
except ValueError:
dashes = [mlines._get_dash_pattern(x) for x in ls]
except ValueError:
raise ValueError(
'Do not know how to convert {!r} to dashes'.format(ls))
# get the list of raw 'unscaled' dash patterns
self._us_linestyles = dashes
# broadcast and scale the lw and dash patterns
self._linewidths, self._linestyles = self._bcast_lwls(
self._us_lw, self._us_linestyles)
def set_capstyle(self, cs):
"""
Set the capstyle for the collection (for all its elements).
Parameters
----------
cs : {'butt', 'round', 'projecting'}
The capstyle
"""
if cs in ('butt', 'round', 'projecting'):
self._capstyle = cs
else:
raise ValueError('Unrecognized cap style. Found %s' % cs)
def get_capstyle(self):
return self._capstyle
def set_joinstyle(self, js):
"""
Set the joinstyle for the collection (for all its elements).
Parameters
----------
js : {'miter', 'round', 'bevel'}
The joinstyle
"""
if js in ('miter', 'round', 'bevel'):
self._joinstyle = js
else:
raise ValueError('Unrecognized join style. Found %s' % js)
def get_joinstyle(self):
return self._joinstyle
@staticmethod
def _bcast_lwls(linewidths, dashes):
"""
Internal helper function to broadcast + scale ls/lw
In the collection drawing code, the linewidth and linestyle are cycled
through as circular buffers (via ``v[i % len(v)]``). Thus, if we are
going to scale the dash pattern at set time (not draw time) we need to
do the broadcasting now and expand both lists to be the same length.
Parameters
----------
linewidths : list
line widths of collection
dashes : list
dash specification (offset, (dash pattern tuple))
Returns
-------
linewidths, dashes : list
Will be the same length, dashes are scaled by paired linewidth
"""
if mpl.rcParams['_internal.classic_mode']:
return linewidths, dashes
# make sure they are the same length so we can zip them
if len(dashes) != len(linewidths):
l_dashes = len(dashes)
l_lw = len(linewidths)
gcd = math.gcd(l_dashes, l_lw)
dashes = list(dashes) * (l_lw // gcd)
linewidths = list(linewidths) * (l_dashes // gcd)
# scale the dash patters
dashes = [mlines._scale_dashes(o, d, lw)
for (o, d), lw in zip(dashes, linewidths)]
return linewidths, dashes
def set_antialiased(self, aa):
"""
Set the antialiasing state for rendering.
Parameters
----------
aa : bool or sequence of bools
"""
if aa is None:
aa = mpl.rcParams['patch.antialiased']
self._antialiaseds = np.atleast_1d(np.asarray(aa, bool))
self.stale = True
def set_color(self, c):
"""
Set both the edgecolor and the facecolor.
Parameters
----------
c : color or sequence of rgba tuples
See Also
--------
Collection.set_facecolor, Collection.set_edgecolor
For setting the edge or face color individually.
"""
self.set_facecolor(c)
self.set_edgecolor(c)
def _set_facecolor(self, c):
if c is None:
c = mpl.rcParams['patch.facecolor']
self._is_filled = True
try:
if c.lower() == 'none':
self._is_filled = False
except AttributeError:
pass
self._facecolors = mcolors.to_rgba_array(c, self._alpha)
self.stale = True
def set_facecolor(self, c):
"""
Set the facecolor(s) of the collection. *c* can be a
matplotlib color spec (all patches have same color), or a
sequence of specs; if it is a sequence the patches will
cycle through the sequence.
If *c* is 'none', the patch will not be filled.
Parameters
----------
c : color or sequence of colors
"""
self._original_facecolor = c
self._set_facecolor(c)
def get_facecolor(self):
return self._facecolors
def get_edgecolor(self):
if cbook._str_equal(self._edgecolors, 'face'):
return self.get_facecolor()
else:
return self._edgecolors
def _set_edgecolor(self, c):
set_hatch_color = True
if c is None:
if (mpl.rcParams['patch.force_edgecolor'] or
not self._is_filled or self._edge_default):
c = mpl.rcParams['patch.edgecolor']
else:
c = 'none'
set_hatch_color = False
self._is_stroked = True
try:
if c.lower() == 'none':
self._is_stroked = False
except AttributeError:
pass
try:
if c.lower() == 'face': # Special case: lookup in "get" method.
self._edgecolors = 'face'
return
except AttributeError:
pass
self._edgecolors = mcolors.to_rgba_array(c, self._alpha)
if set_hatch_color and len(self._edgecolors):
self._hatch_color = tuple(self._edgecolors[0])
self.stale = True
def set_edgecolor(self, c):
"""
Set the edgecolor(s) of the collection.
Parameters
----------
c : color or sequence of colors or 'face'
The collection edgecolor(s). If a sequence, the patches cycle
through it. If 'face', match the facecolor.
"""
self._original_edgecolor = c
self._set_edgecolor(c)
def set_alpha(self, alpha):
# docstring inherited
super().set_alpha(alpha)
self.update_dict['array'] = True
self._set_facecolor(self._original_facecolor)
self._set_edgecolor(self._original_edgecolor)
def get_linewidth(self):
return self._linewidths
def get_linestyle(self):
return self._linestyles
def update_scalarmappable(self):
"""Update colors from the scalar mappable array, if it is not None."""
if self._A is None:
return
if self._A.ndim > 1:
raise ValueError('Collections can only map rank 1 arrays')
if not self.check_update("array"):
return
if self._is_filled:
self._facecolors = self.to_rgba(self._A, self._alpha)
elif self._is_stroked:
self._edgecolors = self.to_rgba(self._A, self._alpha)
self.stale = True
def get_fill(self):
'return whether fill is set'
return self._is_filled
def update_from(self, other):
'copy properties from other to self'
artist.Artist.update_from(self, other)
self._antialiaseds = other._antialiaseds
self._original_edgecolor = other._original_edgecolor
self._edgecolors = other._edgecolors
self._original_facecolor = other._original_facecolor
self._facecolors = other._facecolors
self._linewidths = other._linewidths
self._linestyles = other._linestyles
self._us_linestyles = other._us_linestyles
self._pickradius = other._pickradius
self._hatch = other._hatch
# update_from for scalarmappable
self._A = other._A
self.norm = other.norm
self.cmap = other.cmap
# self.update_dict = other.update_dict # do we need to copy this? -JJL
self.stale = True
# these are not available for the object inspector until after the
# class is built so we define an initial set here for the init
# function and they will be overridden after object defn
docstring.interpd.update(Collection="""\
Valid Collection keyword arguments:
* *edgecolors*: None
* *facecolors*: None
* *linewidths*: None
* *antialiaseds*: None
* *offsets*: None
* *transOffset*: transforms.IdentityTransform()
* *norm*: None (optional for
:class:`matplotlib.cm.ScalarMappable`)
* *cmap*: None (optional for
:class:`matplotlib.cm.ScalarMappable`)
*offsets* and *transOffset* are used to translate the patch after
rendering (default no offsets)
If any of *edgecolors*, *facecolors*, *linewidths*, *antialiaseds*
are None, they default to their :data:`matplotlib.rcParams` patch
setting, in sequence form.
""")
class _CollectionWithSizes(Collection):
"""
Base class for collections that have an array of sizes.
"""
_factor = 1.0
def get_sizes(self):
"""
Returns the sizes of the elements in the collection. The
value represents the 'area' of the element.
Returns
-------
sizes : array
The 'area' of each element.
"""
return self._sizes
def set_sizes(self, sizes, dpi=72.0):
"""
Set the sizes of each member of the collection.
Parameters
----------
sizes : ndarray or None
The size to set for each element of the collection. The
value is the 'area' of the element.
dpi : float
The dpi of the canvas. Defaults to 72.0.
"""
if sizes is None:
self._sizes = np.array([])
self._transforms = np.empty((0, 3, 3))
else:
self._sizes = np.asarray(sizes)
self._transforms = np.zeros((len(self._sizes), 3, 3))
scale = np.sqrt(self._sizes) * dpi / 72.0 * self._factor
self._transforms[:, 0, 0] = scale
self._transforms[:, 1, 1] = scale
self._transforms[:, 2, 2] = 1.0
self.stale = True
@artist.allow_rasterization
def draw(self, renderer):
self.set_sizes(self._sizes, self.figure.dpi)
Collection.draw(self, renderer)
class PathCollection(_CollectionWithSizes):
"""
This is the most basic :class:`Collection` subclass.
A :class:`PathCollection` is e.g. created by a :meth:`~.Axes.scatter` plot.
"""
@docstring.dedent_interpd
def __init__(self, paths, sizes=None, **kwargs):
"""
*paths* is a sequence of :class:`matplotlib.path.Path`
instances.
%(Collection)s
"""
Collection.__init__(self, **kwargs)
self.set_paths(paths)
self.set_sizes(sizes)
self.stale = True
def set_paths(self, paths):
self._paths = paths
self.stale = True
def get_paths(self):
return self._paths
def legend_elements(self, prop="colors", num="auto",
fmt=None, func=lambda x: x, **kwargs):
"""
Creates legend handles and labels for a PathCollection. This is useful
for obtaining a legend for a :meth:`~.Axes.scatter` plot. E.g.::
scatter = plt.scatter([1,2,3], [4,5,6], c=[7,2,3])
plt.legend(*scatter.legend_elements())
Also see the :ref:`automatedlegendcreation` example.
Parameters
----------
prop : string, optional, default *"colors"*
Can be *"colors"* or *"sizes"*. In case of *"colors"*, the legend
handles will show the different colors of the collection. In case
of "sizes", the legend will show the different sizes.
num : int, None, "auto" (default), array-like, or `~.ticker.Locator`,
optional
Target number of elements to create.
If None, use all unique elements of the mappable array. If an
integer, target to use *num* elements in the normed range.
If *"auto"*, try to determine which option better suits the nature
of the data.
The number of created elements may slightly deviate from *num* due
to a `~.ticker.Locator` being used to find useful locations.
If a list or array, use exactly those elements for the legend.
Finally, a `~.ticker.Locator` can be provided.
fmt : string, `~matplotlib.ticker.Formatter`, or None (default)
The format or formatter to use for the labels. If a string must be
a valid input for a `~.StrMethodFormatter`. If None (the default),
use a `~.ScalarFormatter`.
func : function, default *lambda x: x*
Function to calculate the labels. Often the size (or color)
argument to :meth:`~.Axes.scatter` will have been pre-processed
by the user using a function *s = f(x)* to make the markers
visible; e.g. *size = np.log10(x)*. Providing the inverse of this
function here allows that pre-processing to be inverted, so that
the legend labels have the correct values;
e.g. *func = np.exp(x, 10)*.
kwargs : further parameters
Allowed kwargs are *color* and *size*. E.g. it may be useful to
set the color of the markers if *prop="sizes"* is used; similarly
to set the size of the markers if *prop="colors"* is used.
Any further parameters are passed onto the `.Line2D` instance.
This may be useful to e.g. specify a different *markeredgecolor* or
*alpha* for the legend handles.
Returns
-------
tuple (handles, labels)
with *handles* being a list of `.Line2D` objects
and *labels* a matching list of strings.
"""
handles = []
labels = []
hasarray = self.get_array() is not None
if fmt is None:
fmt = mpl.ticker.ScalarFormatter(useOffset=False, useMathText=True)
elif isinstance(fmt, str):
fmt = mpl.ticker.StrMethodFormatter(fmt)
fmt.create_dummy_axis()
if prop == "colors":
if not hasarray:
warnings.warn("Collection without array used. Make sure to "
"specify the values to be colormapped via the "
"`c` argument.")
return handles, labels
u = np.unique(self.get_array())
size = kwargs.pop("size", mpl.rcParams["lines.markersize"])
elif prop == "sizes":
u = np.unique(self.get_sizes())
color = kwargs.pop("color", "k")
else:
raise ValueError("Valid values for `prop` are 'colors' or "
f"'sizes'. You supplied '{prop}' instead.")
fmt.set_bounds(func(u).min(), func(u).max())
if num == "auto":
num = 9
if len(u) <= num:
num = None
if num is None:
values = u
label_values = func(values)
else:
if prop == "colors":
arr = self.get_array()
elif prop == "sizes":
arr = self.get_sizes()
if isinstance(num, mpl.ticker.Locator):
loc = num
elif np.iterable(num):
loc = mpl.ticker.FixedLocator(num)
else:
num = int(num)
loc = mpl.ticker.MaxNLocator(nbins=num, min_n_ticks=num-1,
steps=[1, 2, 2.5, 3, 5, 6, 8, 10])
label_values = loc.tick_values(func(arr).min(), func(arr).max())
cond = ((label_values >= func(arr).min()) &
(label_values <= func(arr).max()))
label_values = label_values[cond]
xarr = np.linspace(arr.min(), arr.max(), 256)
values = np.interp(label_values, func(xarr), xarr)
kw = dict(markeredgewidth=self.get_linewidths()[0],
alpha=self.get_alpha())
kw.update(kwargs)
for val, lab in zip(values, label_values):
if prop == "colors":
color = self.cmap(self.norm(val))
elif prop == "sizes":
size = np.sqrt(val)
if np.isclose(size, 0.0):
continue
h = mlines.Line2D([0], [0], ls="", color=color, ms=size,
marker=self.get_paths()[0], **kw)
handles.append(h)
if hasattr(fmt, "set_locs"):
fmt.set_locs(label_values)
l = fmt(lab)
labels.append(l)
return handles, labels
class PolyCollection(_CollectionWithSizes):
@docstring.dedent_interpd
def __init__(self, verts, sizes=None, closed=True, **kwargs):
"""
*verts* is a sequence of ( *verts0*, *verts1*, ...) where
*verts_i* is a sequence of *xy* tuples of vertices, or an
equivalent :mod:`numpy` array of shape (*nv*, 2).
*sizes* is *None* (default) or a sequence of floats that
scale the corresponding *verts_i*. The scaling is applied
before the Artist master transform; if the latter is an identity
transform, then the overall scaling is such that if
*verts_i* specify a unit square, then *sizes_i* is the area
of that square in points^2.
If len(*sizes*) < *nv*, the additional values will be
taken cyclically from the array.
*closed*, when *True*, will explicitly close the polygon.
%(Collection)s
"""
Collection.__init__(self, **kwargs)
self.set_sizes(sizes)
self.set_verts(verts, closed)
self.stale = True
def set_verts(self, verts, closed=True):
'''This allows one to delay initialization of the vertices.'''
if isinstance(verts, np.ma.MaskedArray):
verts = verts.astype(float).filled(np.nan)
# This is much faster than having Path do it one at a time.
if closed:
self._paths = []
for xy in verts:
if len(xy):
if isinstance(xy, np.ma.MaskedArray):
xy = np.ma.concatenate([xy, xy[0:1]])
else:
xy = np.asarray(xy)
xy = np.concatenate([xy, xy[0:1]])
codes = np.empty(xy.shape[0], dtype=mpath.Path.code_type)
codes[:] = mpath.Path.LINETO
codes[0] = mpath.Path.MOVETO
codes[-1] = mpath.Path.CLOSEPOLY
self._paths.append(mpath.Path(xy, codes))
else:
self._paths.append(mpath.Path(xy))
else:
self._paths = [mpath.Path(xy) for xy in verts]
self.stale = True
set_paths = set_verts
def set_verts_and_codes(self, verts, codes):
"""This allows one to initialize vertices with path codes."""
if len(verts) != len(codes):
raise ValueError("'codes' must be a 1D list or array "
"with the same length of 'verts'")
self._paths = []
for xy, cds in zip(verts, codes):
if len(xy):
self._paths.append(mpath.Path(xy, cds))
else:
self._paths.append(mpath.Path(xy))
self.stale = True
class BrokenBarHCollection(PolyCollection):
"""
A collection of horizontal bars spanning *yrange* with a sequence of
*xranges*.
"""
@docstring.dedent_interpd
def __init__(self, xranges, yrange, **kwargs):
"""
*xranges*
sequence of (*xmin*, *xwidth*)
*yrange*
*ymin*, *ywidth*
%(Collection)s
"""
ymin, ywidth = yrange
ymax = ymin + ywidth
verts = [[(xmin, ymin),
(xmin, ymax),
(xmin + xwidth, ymax),
(xmin + xwidth, ymin),
(xmin, ymin)] for xmin, xwidth in xranges]
PolyCollection.__init__(self, verts, **kwargs)
@staticmethod
def span_where(x, ymin, ymax, where, **kwargs):
"""
Create a BrokenBarHCollection to plot horizontal bars from
over the regions in *x* where *where* is True. The bars range
on the y-axis from *ymin* to *ymax*
A :class:`BrokenBarHCollection` is returned. *kwargs* are
passed on to the collection.
"""
xranges = []
for ind0, ind1 in cbook.contiguous_regions(where):
xslice = x[ind0:ind1]
if not len(xslice):
continue
xranges.append((xslice[0], xslice[-1] - xslice[0]))
collection = BrokenBarHCollection(
xranges, [ymin, ymax - ymin], **kwargs)
return collection
class RegularPolyCollection(_CollectionWithSizes):
"""Draw a collection of regular polygons with *numsides*."""
_path_generator = mpath.Path.unit_regular_polygon
_factor = np.pi ** (-1/2)
@docstring.dedent_interpd
def __init__(self,
numsides,
rotation=0,
sizes=(1,),
**kwargs):
"""
*numsides*
the number of sides of the polygon
*rotation*
the rotation of the polygon in radians
*sizes*
gives the area of the circle circumscribing the
regular polygon in points^2
%(Collection)s
Example: see :doc:`/gallery/event_handling/lasso_demo` for a
complete example::
offsets = np.random.rand(20,2)
facecolors = [cm.jet(x) for x in np.random.rand(20)]
black = (0,0,0,1)
collection = RegularPolyCollection(
numsides=5, # a pentagon
rotation=0, sizes=(50,),
facecolors=facecolors,
edgecolors=(black,),
linewidths=(1,),
offsets=offsets,
transOffset=ax.transData,
)
"""
Collection.__init__(self, **kwargs)
self.set_sizes(sizes)
self._numsides = numsides
self._paths = [self._path_generator(numsides)]
self._rotation = rotation
self.set_transform(transforms.IdentityTransform())
def get_numsides(self):
return self._numsides
def get_rotation(self):
return self._rotation
@artist.allow_rasterization
def draw(self, renderer):
self.set_sizes(self._sizes, self.figure.dpi)
self._transforms = [
transforms.Affine2D(x).rotate(-self._rotation).get_matrix()
for x in self._transforms
]
Collection.draw(self, renderer)
class StarPolygonCollection(RegularPolyCollection):
"""Draw a collection of regular stars with *numsides* points."""
_path_generator = mpath.Path.unit_regular_star
class AsteriskPolygonCollection(RegularPolyCollection):
"""Draw a collection of regular asterisks with *numsides* points."""
_path_generator = mpath.Path.unit_regular_asterisk
class LineCollection(Collection):
"""
All parameters must be sequences or scalars; if scalars, they will
be converted to sequences. The property of the ith line
segment is::
prop[i % len(props)]
i.e., the properties cycle if the ``len`` of props is less than the
number of segments.
"""
_edge_default = True
def __init__(self, segments, # Can be None.
linewidths=None,
colors=None,
antialiaseds=None,
linestyles='solid',
offsets=None,
transOffset=None,
norm=None,
cmap=None,
pickradius=5,
zorder=2,
facecolors='none',
**kwargs
):
"""
Parameters
----------
segments
A sequence of (*line0*, *line1*, *line2*), where::
linen = (x0, y0), (x1, y1), ... (xm, ym)
or the equivalent numpy array with two columns. Each line
can be a different length.
colors : sequence, optional
A sequence of RGBA tuples (e.g., arbitrary color
strings, etc, not allowed).
antialiaseds : sequence, optional
A sequence of ones or zeros.
linestyles : string, tuple, optional
Either one of [ 'solid' | 'dashed' | 'dashdot' | 'dotted' ], or
a dash tuple. The dash tuple is::
(offset, onoffseq)
where ``onoffseq`` is an even length tuple of on and off ink
in points.
norm : Normalize, optional
`~.colors.Normalize` instance.
cmap : string or Colormap, optional
Colormap name or `~.colors.Colormap` instance.
pickradius : float, optional
The tolerance in points for mouse clicks picking a line.
Default is 5 pt.
zorder : int, optional
zorder of the LineCollection. Default is 2.
facecolors : optional
The facecolors of the LineCollection. Default is 'none'.
Setting to a value other than 'none' will lead to a filled
polygon being drawn between points on each line.
Notes
-----
If *linewidths*, *colors*, or *antialiaseds* is None, they
default to their rcParams setting, in sequence form.
If *offsets* and *transOffset* are not None, then
*offsets* are transformed by *transOffset* and applied after
the segments have been transformed to display coordinates.
If *offsets* is not None but *transOffset* is None, then the
*offsets* are added to the segments before any transformation.
In this case, a single offset can be specified as::
offsets=(xo,yo)
and this value will be added cumulatively to each successive
segment, so as to produce a set of successively offset curves.
The use of :class:`~matplotlib.cm.ScalarMappable` is optional.
If the :class:`~matplotlib.cm.ScalarMappable` array
:attr:`~matplotlib.cm.ScalarMappable._A` is not None (i.e., a call to
:meth:`~matplotlib.cm.ScalarMappable.set_array` has been made), at
draw time a call to scalar mappable will be made to set the colors.
"""
if colors is None:
colors = mpl.rcParams['lines.color']
if linewidths is None:
linewidths = (mpl.rcParams['lines.linewidth'],)
if antialiaseds is None:
antialiaseds = (mpl.rcParams['lines.antialiased'],)
colors = mcolors.to_rgba_array(colors)
Collection.__init__(
self,
edgecolors=colors,
facecolors=facecolors,
linewidths=linewidths,
linestyles=linestyles,
antialiaseds=antialiaseds,
offsets=offsets,
transOffset=transOffset,
norm=norm,
cmap=cmap,
pickradius=pickradius,
zorder=zorder,
**kwargs)
self.set_segments(segments)
def set_segments(self, segments):
if segments is None:
return
_segments = []
for seg in segments:
if not isinstance(seg, np.ma.MaskedArray):
seg = np.asarray(seg, float)
_segments.append(seg)
if self._uniform_offsets is not None:
_segments = self._add_offsets(_segments)
self._paths = [mpath.Path(_seg) for _seg in _segments]
self.stale = True
set_verts = set_segments # for compatibility with PolyCollection
set_paths = set_segments
def get_segments(self):
"""
Returns
-------
segments : list
List of segments in the LineCollection. Each list item contains an
array of vertices.
"""
segments = []
for path in self._paths:
vertices = [vertex for vertex, _ in path.iter_segments()]
vertices = np.asarray(vertices)
segments.append(vertices)
return segments
def _add_offsets(self, segs):
offsets = self._uniform_offsets
Nsegs = len(segs)
Noffs = offsets.shape[0]
if Noffs == 1:
for i in range(Nsegs):
segs[i] = segs[i] + i * offsets
else:
for i in range(Nsegs):
io = i % Noffs
segs[i] = segs[i] + offsets[io:io + 1]
return segs
def set_color(self, c):
"""
Set the color(s) of the LineCollection.
Parameters
----------
c : color or list of colors
Matplotlib color argument (all patches have same color), or a
sequence or rgba tuples; if it is a sequence the patches will
cycle through the sequence.
"""
self.set_edgecolor(c)
self.stale = True
def get_color(self):
return self._edgecolors
get_colors = get_color # for compatibility with old versions
class EventCollection(LineCollection):
"""
A collection of discrete events.
The events are given by a 1-dimensional array, usually the position of
something along an axis, such as time or length. They do not have an
amplitude and are displayed as vertical or horizontal parallel bars.
"""
_edge_default = True
def __init__(self,
positions, # Cannot be None.
orientation=None,
lineoffset=0,
linelength=1,
linewidth=None,
color=None,
linestyle='solid',
antialiased=None,
**kwargs
):
"""
Parameters
----------
positions : 1D array-like object
Each value is an event.
orientation : {None, 'horizontal', 'vertical'}, optional
The orientation of the **collection** (the event bars are along
the orthogonal direction). Defaults to 'horizontal' if not
specified or None.
lineoffset : scalar, optional, default: 0
The offset of the center of the markers from the origin, in the
direction orthogonal to *orientation*.
linelength : scalar, optional, default: 1
The total height of the marker (i.e. the marker stretches from
``lineoffset - linelength/2`` to ``lineoffset + linelength/2``).
linewidth : scalar or None, optional, default: None
If it is None, defaults to its rcParams setting, in sequence form.
color : color, sequence of colors or None, optional, default: None
If it is None, defaults to its rcParams setting, in sequence form.
linestyle : str or tuple, optional, default: 'solid'
Valid strings are ['solid', 'dashed', 'dashdot', 'dotted',
'-', '--', '-.', ':']. Dash tuples should be of the form::
(offset, onoffseq),
where *onoffseq* is an even length tuple of on and off ink
in points.
antialiased : {None, 1, 2}, optional
If it is None, defaults to its rcParams setting, in sequence form.
**kwargs : optional
Other keyword arguments are line collection properties. See
:class:`~matplotlib.collections.LineCollection` for a list of
the valid properties.
Examples
--------
.. plot:: gallery/lines_bars_and_markers/eventcollection_demo.py
"""
segment = (lineoffset + linelength / 2.,
lineoffset - linelength / 2.)
if positions is None or len(positions) == 0:
segments = []
elif hasattr(positions, 'ndim') and positions.ndim > 1:
raise ValueError('positions cannot be an array with more than '
'one dimension.')
elif (orientation is None or orientation.lower() == 'none' or
orientation.lower() == 'horizontal'):
positions.sort()
segments = [[(coord1, coord2) for coord2 in segment] for
coord1 in positions]
self._is_horizontal = True
elif orientation.lower() == 'vertical':
positions.sort()
segments = [[(coord2, coord1) for coord2 in segment] for
coord1 in positions]
self._is_horizontal = False
else:
cbook._check_in_list(['horizontal', 'vertical'],
orientation=orientation)
LineCollection.__init__(self,
segments,
linewidths=linewidth,
colors=color,
antialiaseds=antialiased,
linestyles=linestyle,
**kwargs)
self._linelength = linelength
self._lineoffset = lineoffset
def get_positions(self):
'''
return an array containing the floating-point values of the positions
'''
segments = self.get_segments()
pos = 0 if self.is_horizontal() else 1
return [segment[0, pos] for segment in self.get_segments()]
def set_positions(self, positions):
'''
set the positions of the events to the specified value
'''
if positions is None or (hasattr(positions, 'len') and
len(positions) == 0):
self.set_segments([])
return
lineoffset = self.get_lineoffset()
linelength = self.get_linelength()
segment = (lineoffset + linelength / 2.,
lineoffset - linelength / 2.)
positions = np.asanyarray(positions)
positions.sort()
if self.is_horizontal():
segments = [[(coord1, coord2) for coord2 in segment] for
coord1 in positions]
else:
segments = [[(coord2, coord1) for coord2 in segment] for
coord1 in positions]
self.set_segments(segments)
def add_positions(self, position):
'''
add one or more events at the specified positions
'''
if position is None or (hasattr(position, 'len') and
len(position) == 0):
return
positions = self.get_positions()
positions = np.hstack([positions, np.asanyarray(position)])
self.set_positions(positions)
extend_positions = append_positions = add_positions
def is_horizontal(self):
'''
True if the eventcollection is horizontal, False if vertical
'''
return self._is_horizontal
def get_orientation(self):
'''
get the orientation of the event line, may be:
[ 'horizontal' | 'vertical' ]
'''
return 'horizontal' if self.is_horizontal() else 'vertical'
def switch_orientation(self):
'''
switch the orientation of the event line, either from vertical to
horizontal or vice versus
'''
segments = self.get_segments()
for i, segment in enumerate(segments):
segments[i] = np.fliplr(segment)
self.set_segments(segments)
self._is_horizontal = not self.is_horizontal()
self.stale = True
def set_orientation(self, orientation=None):
'''
set the orientation of the event line
[ 'horizontal' | 'vertical' | None ]
defaults to 'horizontal' if not specified or None
'''
if (orientation is None or orientation.lower() == 'none' or
orientation.lower() == 'horizontal'):
is_horizontal = True
elif orientation.lower() == 'vertical':
is_horizontal = False
else:
cbook._check_in_list(['horizontal', 'vertical'],
orientation=orientation)
if is_horizontal == self.is_horizontal():
return
self.switch_orientation()
def get_linelength(self):
'''
get the length of the lines used to mark each event
'''
return self._linelength
def set_linelength(self, linelength):
'''
set the length of the lines used to mark each event
'''
if linelength == self.get_linelength():
return
lineoffset = self.get_lineoffset()
segments = self.get_segments()
pos = 1 if self.is_horizontal() else 0
for segment in segments:
segment[0, pos] = lineoffset + linelength / 2.
segment[1, pos] = lineoffset - linelength / 2.
self.set_segments(segments)
self._linelength = linelength
def get_lineoffset(self):
'''
get the offset of the lines used to mark each event
'''
return self._lineoffset
def set_lineoffset(self, lineoffset):
'''
set the offset of the lines used to mark each event
'''
if lineoffset == self.get_lineoffset():
return
linelength = self.get_linelength()
segments = self.get_segments()
pos = 1 if self.is_horizontal() else 0
for segment in segments:
segment[0, pos] = lineoffset + linelength / 2.
segment[1, pos] = lineoffset - linelength / 2.
self.set_segments(segments)
self._lineoffset = lineoffset
def get_linewidth(self):
"""Get the width of the lines used to mark each event."""
return super(EventCollection, self).get_linewidth()[0]
def get_linewidths(self):
return super(EventCollection, self).get_linewidth()
def get_color(self):
'''
get the color of the lines used to mark each event
'''
return self.get_colors()[0]
class CircleCollection(_CollectionWithSizes):
"""A collection of circles, drawn using splines."""
_factor = np.pi ** (-1/2)
@docstring.dedent_interpd
def __init__(self, sizes, **kwargs):
"""
*sizes*
Gives the area of the circle in points^2
%(Collection)s
"""
Collection.__init__(self, **kwargs)
self.set_sizes(sizes)
self.set_transform(transforms.IdentityTransform())
self._paths = [mpath.Path.unit_circle()]
class EllipseCollection(Collection):
"""A collection of ellipses, drawn using splines."""
@docstring.dedent_interpd
def __init__(self, widths, heights, angles, units='points', **kwargs):
"""
Parameters
----------
widths : array-like
The lengths of the first axes (e.g., major axis lengths).
heights : array-like
The lengths of second axes.
angles : array-like
The angles of the first axes, degrees CCW from the x-axis.
units : {'points', 'inches', 'dots', 'width', 'height', 'x', 'y', 'xy'}
The units in which majors and minors are given; 'width' and
'height' refer to the dimensions of the axes, while 'x'
and 'y' refer to the *offsets* data units. 'xy' differs
from all others in that the angle as plotted varies with
the aspect ratio, and equals the specified angle only when
the aspect ratio is unity. Hence it behaves the same as
the :class:`~matplotlib.patches.Ellipse` with
``axes.transData`` as its transform.
Other Parameters
----------------
**kwargs
Additional kwargs inherited from the base :class:`Collection`.
%(Collection)s
"""
Collection.__init__(self, **kwargs)
self._widths = 0.5 * np.asarray(widths).ravel()
self._heights = 0.5 * np.asarray(heights).ravel()
self._angles = np.deg2rad(angles).ravel()
self._units = units
self.set_transform(transforms.IdentityTransform())
self._transforms = np.empty((0, 3, 3))
self._paths = [mpath.Path.unit_circle()]
def _set_transforms(self):
"""Calculate transforms immediately before drawing."""
ax = self.axes
fig = self.figure
if self._units == 'xy':
sc = 1
elif self._units == 'x':
sc = ax.bbox.width / ax.viewLim.width
elif self._units == 'y':
sc = ax.bbox.height / ax.viewLim.height
elif self._units == 'inches':
sc = fig.dpi
elif self._units == 'points':
sc = fig.dpi / 72.0
elif self._units == 'width':
sc = ax.bbox.width
elif self._units == 'height':
sc = ax.bbox.height
elif self._units == 'dots':
sc = 1.0
else:
raise ValueError('unrecognized units: %s' % self._units)
self._transforms = np.zeros((len(self._widths), 3, 3))
widths = self._widths * sc
heights = self._heights * sc
sin_angle = np.sin(self._angles)
cos_angle = np.cos(self._angles)
self._transforms[:, 0, 0] = widths * cos_angle
self._transforms[:, 0, 1] = heights * -sin_angle
self._transforms[:, 1, 0] = widths * sin_angle
self._transforms[:, 1, 1] = heights * cos_angle
self._transforms[:, 2, 2] = 1.0
_affine = transforms.Affine2D
if self._units == 'xy':
m = ax.transData.get_affine().get_matrix().copy()
m[:2, 2:] = 0
self.set_transform(_affine(m))
@artist.allow_rasterization
def draw(self, renderer):
self._set_transforms()
Collection.draw(self, renderer)
class PatchCollection(Collection):
"""
A generic collection of patches.
This makes it easier to assign a color map to a heterogeneous
collection of patches.
This also may improve plotting speed, since PatchCollection will
draw faster than a large number of patches.
"""
def __init__(self, patches, match_original=False, **kwargs):
"""
*patches*
a sequence of Patch objects. This list may include
a heterogeneous assortment of different patch types.
*match_original*
If True, use the colors and linewidths of the original
patches. If False, new colors may be assigned by
providing the standard collection arguments, facecolor,
edgecolor, linewidths, norm or cmap.
If any of *edgecolors*, *facecolors*, *linewidths*,
*antialiaseds* are None, they default to their
:data:`matplotlib.rcParams` patch setting, in sequence form.
The use of :class:`~matplotlib.cm.ScalarMappable` is optional.
If the :class:`~matplotlib.cm.ScalarMappable` matrix _A is not
None (i.e., a call to set_array has been made), at draw time a
call to scalar mappable will be made to set the face colors.
"""
if match_original:
def determine_facecolor(patch):
if patch.get_fill():
return patch.get_facecolor()
return [0, 0, 0, 0]
kwargs['facecolors'] = [determine_facecolor(p) for p in patches]
kwargs['edgecolors'] = [p.get_edgecolor() for p in patches]
kwargs['linewidths'] = [p.get_linewidth() for p in patches]
kwargs['linestyles'] = [p.get_linestyle() for p in patches]
kwargs['antialiaseds'] = [p.get_antialiased() for p in patches]
Collection.__init__(self, **kwargs)
self.set_paths(patches)
def set_paths(self, patches):
paths = [p.get_transform().transform_path(p.get_path())
for p in patches]
self._paths = paths
class TriMesh(Collection):
"""
Class for the efficient drawing of a triangular mesh using Gouraud shading.
A triangular mesh is a `~matplotlib.tri.Triangulation` object.
"""
def __init__(self, triangulation, **kwargs):
Collection.__init__(self, **kwargs)
self._triangulation = triangulation
self._shading = 'gouraud'
self._is_filled = True
self._bbox = transforms.Bbox.unit()
# Unfortunately this requires a copy, unless Triangulation
# was rewritten.
xy = np.hstack((triangulation.x.reshape(-1, 1),
triangulation.y.reshape(-1, 1)))
self._bbox.update_from_data_xy(xy)
def get_paths(self):
if self._paths is None:
self.set_paths()
return self._paths
def set_paths(self):
self._paths = self.convert_mesh_to_paths(self._triangulation)
@staticmethod
def convert_mesh_to_paths(tri):
"""
Converts a given mesh into a sequence of `~.Path` objects.
This function is primarily of use to implementers of backends that do
not directly support meshes.
"""
triangles = tri.get_masked_triangles()
verts = np.stack((tri.x[triangles], tri.y[triangles]), axis=-1)
return [mpath.Path(x) for x in verts]
@artist.allow_rasterization
def draw(self, renderer):
if not self.get_visible():
return
renderer.open_group(self.__class__.__name__)
transform = self.get_transform()
# Get a list of triangles and the color at each vertex.
tri = self._triangulation
triangles = tri.get_masked_triangles()
verts = np.stack((tri.x[triangles], tri.y[triangles]), axis=-1)
self.update_scalarmappable()
colors = self._facecolors[triangles]
gc = renderer.new_gc()
self._set_gc_clip(gc)
gc.set_linewidth(self.get_linewidth()[0])
renderer.draw_gouraud_triangles(gc, verts, colors, transform.frozen())
gc.restore()
renderer.close_group(self.__class__.__name__)
class QuadMesh(Collection):
"""
Class for the efficient drawing of a quadrilateral mesh.
A quadrilateral mesh consists of a grid of vertices. The
dimensions of this array are (*meshWidth* + 1, *meshHeight* +
1). Each vertex in the mesh has a different set of "mesh
coordinates" representing its position in the topology of the
mesh. For any values (*m*, *n*) such that 0 <= *m* <= *meshWidth*
and 0 <= *n* <= *meshHeight*, the vertices at mesh coordinates
(*m*, *n*), (*m*, *n* + 1), (*m* + 1, *n* + 1), and (*m* + 1, *n*)
form one of the quadrilaterals in the mesh. There are thus
(*meshWidth* * *meshHeight*) quadrilaterals in the mesh. The mesh
need not be regular and the polygons need not be convex.
A quadrilateral mesh is represented by a (2 x ((*meshWidth* + 1) *
(*meshHeight* + 1))) numpy array *coordinates*, where each row is
the *x* and *y* coordinates of one of the vertices. To define the
function that maps from a data point to its corresponding color,
use the :meth:`set_cmap` method. Each of these arrays is indexed in
row-major order by the mesh coordinates of the vertex (or the mesh
coordinates of the lower left vertex, in the case of the
colors).
For example, the first entry in *coordinates* is the
coordinates of the vertex at mesh coordinates (0, 0), then the one
at (0, 1), then at (0, 2) .. (0, meshWidth), (1, 0), (1, 1), and
so on.
*shading* may be 'flat', or 'gouraud'
"""
def __init__(self, meshWidth, meshHeight, coordinates,
antialiased=True, shading='flat', **kwargs):
Collection.__init__(self, **kwargs)
self._meshWidth = meshWidth
self._meshHeight = meshHeight
# By converting to floats now, we can avoid that on every draw.
self._coordinates = np.asarray(coordinates, float).reshape(
(meshHeight + 1, meshWidth + 1, 2))
self._antialiased = antialiased
self._shading = shading
self._bbox = transforms.Bbox.unit()
self._bbox.update_from_data_xy(coordinates.reshape(
((meshWidth + 1) * (meshHeight + 1), 2)))
def get_paths(self):
if self._paths is None:
self.set_paths()
return self._paths
def set_paths(self):
self._paths = self.convert_mesh_to_paths(
self._meshWidth, self._meshHeight, self._coordinates)
self.stale = True
def get_datalim(self, transData):
return (self.get_transform() - transData).transform_bbox(self._bbox)
@staticmethod
def convert_mesh_to_paths(meshWidth, meshHeight, coordinates):
"""
Converts a given mesh into a sequence of `~.Path` objects.
This function is primarily of use to implementers of backends that do
not directly support quadmeshes.
"""
if isinstance(coordinates, np.ma.MaskedArray):
c = coordinates.data
else:
c = coordinates
points = np.concatenate((
c[:-1, :-1],
c[:-1, 1:],
c[1:, 1:],
c[1:, :-1],
c[:-1, :-1]
), axis=2)
points = points.reshape((meshWidth * meshHeight, 5, 2))
return [mpath.Path(x) for x in points]
def convert_mesh_to_triangles(self, meshWidth, meshHeight, coordinates):
"""
Converts a given mesh into a sequence of triangles, each point
with its own color. This is useful for experiments using
`draw_gouraud_triangle`.
"""
if isinstance(coordinates, np.ma.MaskedArray):
p = coordinates.data
else:
p = coordinates
p_a = p[:-1, :-1]
p_b = p[:-1, 1:]
p_c = p[1:, 1:]
p_d = p[1:, :-1]
p_center = (p_a + p_b + p_c + p_d) / 4.0
triangles = np.concatenate((
p_a, p_b, p_center,
p_b, p_c, p_center,
p_c, p_d, p_center,
p_d, p_a, p_center,
), axis=2)
triangles = triangles.reshape((meshWidth * meshHeight * 4, 3, 2))
c = self.get_facecolor().reshape((meshHeight + 1, meshWidth + 1, 4))
c_a = c[:-1, :-1]
c_b = c[:-1, 1:]
c_c = c[1:, 1:]
c_d = c[1:, :-1]
c_center = (c_a + c_b + c_c + c_d) / 4.0
colors = np.concatenate((
c_a, c_b, c_center,
c_b, c_c, c_center,
c_c, c_d, c_center,
c_d, c_a, c_center,
), axis=2)
colors = colors.reshape((meshWidth * meshHeight * 4, 3, 4))
return triangles, colors
@artist.allow_rasterization
def draw(self, renderer):
if not self.get_visible():
return
renderer.open_group(self.__class__.__name__, self.get_gid())
transform = self.get_transform()
transOffset = self.get_offset_transform()
offsets = self._offsets
if self.have_units():
if len(self._offsets):
xs = self.convert_xunits(self._offsets[:, 0])
ys = self.convert_yunits(self._offsets[:, 1])
offsets = np.column_stack([xs, ys])
self.update_scalarmappable()
if not transform.is_affine:
coordinates = self._coordinates.reshape((-1, 2))
coordinates = transform.transform(coordinates)
coordinates = coordinates.reshape(self._coordinates.shape)
transform = transforms.IdentityTransform()
else:
coordinates = self._coordinates
if not transOffset.is_affine:
offsets = transOffset.transform_non_affine(offsets)
transOffset = transOffset.get_affine()
gc = renderer.new_gc()
self._set_gc_clip(gc)
gc.set_linewidth(self.get_linewidth()[0])
if self._shading == 'gouraud':
triangles, colors = self.convert_mesh_to_triangles(
self._meshWidth, self._meshHeight, coordinates)
renderer.draw_gouraud_triangles(
gc, triangles, colors, transform.frozen())
else:
renderer.draw_quad_mesh(
gc, transform.frozen(), self._meshWidth, self._meshHeight,
coordinates, offsets, transOffset, self.get_facecolor(),
self._antialiased, self.get_edgecolors())
gc.restore()
renderer.close_group(self.__class__.__name__)
self.stale = False
patchstr = artist.kwdoc(Collection)
for k in ('QuadMesh', 'TriMesh', 'PolyCollection', 'BrokenBarHCollection',
'RegularPolyCollection', 'PathCollection',
'StarPolygonCollection', 'PatchCollection',
'CircleCollection', 'Collection',):
docstring.interpd.update({k: patchstr})
docstring.interpd.update(LineCollection=artist.kwdoc(LineCollection))
|
891c4d3f13d56291d41f55de89f5d0ccb28c461e4a686e1870076a79731c5988
|
'''
Colorbar toolkit with two classes and a function:
:class:`ColorbarBase`
the base class with full colorbar drawing functionality.
It can be used as-is to make a colorbar for a given colormap;
a mappable object (e.g., image) is not needed.
:class:`Colorbar`
the derived class for use with images or contour plots.
:func:`make_axes`
a function for resizing an axes and adding a second axes
suitable for a colorbar
The :meth:`~matplotlib.figure.Figure.colorbar` method uses :func:`make_axes`
and :class:`Colorbar`; the :func:`~matplotlib.pyplot.colorbar` function
is a thin wrapper over :meth:`~matplotlib.figure.Figure.colorbar`.
'''
import logging
import numpy as np
import matplotlib as mpl
import matplotlib.artist as martist
import matplotlib.cbook as cbook
import matplotlib.collections as collections
import matplotlib.colors as colors
import matplotlib.contour as contour
import matplotlib.cm as cm
import matplotlib.gridspec as gridspec
import matplotlib.patches as mpatches
import matplotlib.path as mpath
import matplotlib.ticker as ticker
import matplotlib.transforms as mtransforms
import matplotlib._layoutbox as layoutbox
import matplotlib._constrained_layout as constrained_layout
from matplotlib import docstring
_log = logging.getLogger(__name__)
make_axes_kw_doc = '''
============= ====================================================
Property Description
============= ====================================================
*orientation* vertical or horizontal
*fraction* 0.15; fraction of original axes to use for colorbar
*pad* 0.05 if vertical, 0.15 if horizontal; fraction
of original axes between colorbar and new image axes
*shrink* 1.0; fraction by which to multiply the size of the colorbar
*aspect* 20; ratio of long to short dimensions
*anchor* (0.0, 0.5) if vertical; (0.5, 1.0) if horizontal;
the anchor point of the colorbar axes
*panchor* (1.0, 0.5) if vertical; (0.5, 0.0) if horizontal;
the anchor point of the colorbar parent axes. If
False, the parent axes' anchor will be unchanged
============= ====================================================
'''
colormap_kw_doc = '''
============ ====================================================
Property Description
============ ====================================================
*extend* [ 'neither' | 'both' | 'min' | 'max' ]
If not 'neither', make pointed end(s) for out-of-
range values. These are set for a given colormap
using the colormap set_under and set_over methods.
*extendfrac* [ *None* | 'auto' | length | lengths ]
If set to *None*, both the minimum and maximum
triangular colorbar extensions with have a length of
5% of the interior colorbar length (this is the
default setting). If set to 'auto', makes the
triangular colorbar extensions the same lengths as
the interior boxes (when *spacing* is set to
'uniform') or the same lengths as the respective
adjacent interior boxes (when *spacing* is set to
'proportional'). If a scalar, indicates the length
of both the minimum and maximum triangular colorbar
extensions as a fraction of the interior colorbar
length. A two-element sequence of fractions may also
be given, indicating the lengths of the minimum and
maximum colorbar extensions respectively as a
fraction of the interior colorbar length.
*extendrect* bool
If *False* the minimum and maximum colorbar extensions
will be triangular (the default). If *True* the
extensions will be rectangular.
*spacing* [ 'uniform' | 'proportional' ]
Uniform spacing gives each discrete color the same
space; proportional makes the space proportional to
the data interval.
*ticks* [ None | list of ticks | Locator object ]
If None, ticks are determined automatically from the
input.
*format* [ None | format string | Formatter object ]
If None, the
:class:`~matplotlib.ticker.ScalarFormatter` is used.
If a format string is given, e.g., '%.3f', that is
used. An alternative
:class:`~matplotlib.ticker.Formatter` object may be
given instead.
*drawedges* bool
Whether to draw lines at color boundaries.
============ ====================================================
The following will probably be useful only in the context of
indexed colors (that is, when the mappable has norm=NoNorm()),
or other unusual circumstances.
============ ===================================================
Property Description
============ ===================================================
*boundaries* None or a sequence
*values* None or a sequence which must be of length 1 less
than the sequence of *boundaries*. For each region
delimited by adjacent entries in *boundaries*, the
color mapped to the corresponding value in values
will be used.
============ ===================================================
'''
colorbar_doc = '''
Add a colorbar to a plot.
Function signatures for the :mod:`~matplotlib.pyplot` interface; all
but the first are also method signatures for the
:meth:`~matplotlib.figure.Figure.colorbar` method::
colorbar(**kwargs)
colorbar(mappable, **kwargs)
colorbar(mappable, cax=cax, **kwargs)
colorbar(mappable, ax=ax, **kwargs)
Parameters
----------
mappable
The `matplotlib.cm.ScalarMappable` (i.e., `~matplotlib.image.Image`,
`~matplotlib.contour.ContourSet`, etc.) described by this colorbar.
This argument is mandatory for the `.Figure.colorbar` method but optional
for the `.pyplot.colorbar` function, which sets the default to the current
image.
Note that one can create a `ScalarMappable` "on-the-fly" to generate
colorbars not attached to a previously drawn artist, e.g. ::
fig.colorbar(cm.ScalarMappable(norm=norm, cmap=cmap), ax=ax)
cax : :class:`~matplotlib.axes.Axes` object, optional
Axes into which the colorbar will be drawn.
ax : :class:`~matplotlib.axes.Axes`, list of Axes, optional
Parent axes from which space for a new colorbar axes will be stolen.
If a list of axes is given they will all be resized to make room for the
colorbar axes.
use_gridspec : bool, optional
If *cax* is ``None``, a new *cax* is created as an instance of Axes. If
*ax* is an instance of Subplot and *use_gridspec* is ``True``, *cax* is
created as an instance of Subplot using the :mod:`~.gridspec` module.
Returns
-------
colorbar : `~matplotlib.colorbar.Colorbar`
See also its base class, `~matplotlib.colorbar.ColorbarBase`. Use
`~.ColorbarBase.set_label` to label the colorbar.
Notes
-----
Additional keyword arguments are of two kinds:
axes properties:
%s
colorbar properties:
%s
If *mappable* is a :class:`~matplotlib.contours.ContourSet`, its *extend*
kwarg is included automatically.
The *shrink* kwarg provides a simple way to scale the colorbar with respect
to the axes. Note that if *cax* is specified, it determines the size of the
colorbar and *shrink* and *aspect* kwargs are ignored.
For more precise control, you can manually specify the positions of
the axes objects in which the mappable and the colorbar are drawn. In
this case, do not use any of the axes properties kwargs.
It is known that some vector graphics viewers (svg and pdf) renders white gaps
between segments of the colorbar. This is due to bugs in the viewers, not
Matplotlib. As a workaround, the colorbar can be rendered with overlapping
segments::
cbar = colorbar()
cbar.solids.set_edgecolor("face")
draw()
However this has negative consequences in other circumstances, e.g. with
semi-transparent images (alpha < 1) and colorbar extensions; therefore, this
workaround is not used by default (see issue #1188).
''' % (make_axes_kw_doc, colormap_kw_doc)
docstring.interpd.update(colorbar_doc=colorbar_doc)
def _set_ticks_on_axis_warn(*args, **kw):
# a top level function which gets put in at the axes'
# set_xticks set_yticks by _patch_ax
cbook._warn_external("Use the colorbar set_ticks() method instead.")
class _ColorbarAutoLocator(ticker.MaxNLocator):
"""
AutoLocator for Colorbar
This locator is just a `.MaxNLocator` except the min and max are
clipped by the norm's min and max (i.e. vmin/vmax from the
image/pcolor/contour object). This is necessary so ticks don't
extrude into the "extend regions".
"""
def __init__(self, colorbar):
"""
This ticker needs to know the *colorbar* so that it can access
its *vmin* and *vmax*. Otherwise it is the same as
`~.ticker.AutoLocator`.
"""
self._colorbar = colorbar
nbins = 'auto'
steps = [1, 2, 2.5, 5, 10]
super().__init__(nbins=nbins, steps=steps)
def tick_values(self, vmin, vmax):
# flip if needed:
if vmin > vmax:
vmin, vmax = vmax, vmin
vmin = max(vmin, self._colorbar.norm.vmin)
vmax = min(vmax, self._colorbar.norm.vmax)
ticks = super().tick_values(vmin, vmax)
rtol = (vmax - vmin) * 1e-10
return ticks[(ticks >= vmin - rtol) & (ticks <= vmax + rtol)]
class _ColorbarAutoMinorLocator(ticker.AutoMinorLocator):
"""
AutoMinorLocator for Colorbar
This locator is just a `.AutoMinorLocator` except the min and max are
clipped by the norm's min and max (i.e. vmin/vmax from the
image/pcolor/contour object). This is necessary so that the minorticks
don't extrude into the "extend regions".
"""
def __init__(self, colorbar, n=None):
"""
This ticker needs to know the *colorbar* so that it can access
its *vmin* and *vmax*.
"""
self._colorbar = colorbar
self.ndivs = n
super().__init__(n=None)
def __call__(self):
vmin = self._colorbar.norm.vmin
vmax = self._colorbar.norm.vmax
ticks = super().__call__()
rtol = (vmax - vmin) * 1e-10
return ticks[(ticks >= vmin - rtol) & (ticks <= vmax + rtol)]
class _ColorbarLogLocator(ticker.LogLocator):
"""
LogLocator for Colorbarbar
This locator is just a `.LogLocator` except the min and max are
clipped by the norm's min and max (i.e. vmin/vmax from the
image/pcolor/contour object). This is necessary so ticks don't
extrude into the "extend regions".
"""
def __init__(self, colorbar, *args, **kwargs):
"""
_ColorbarLogLocator(colorbar, *args, **kwargs)
This ticker needs to know the *colorbar* so that it can access
its *vmin* and *vmax*. Otherwise it is the same as
`~.ticker.LogLocator`. The ``*args`` and ``**kwargs`` are the
same as `~.ticker.LogLocator`.
"""
self._colorbar = colorbar
super().__init__(*args, **kwargs)
def tick_values(self, vmin, vmax):
if vmin > vmax:
vmin, vmax = vmax, vmin
vmin = max(vmin, self._colorbar.norm.vmin)
vmax = min(vmax, self._colorbar.norm.vmax)
ticks = super().tick_values(vmin, vmax)
rtol = (np.log10(vmax) - np.log10(vmin)) * 1e-10
ticks = ticks[(np.log10(ticks) >= np.log10(vmin) - rtol) &
(np.log10(ticks) <= np.log10(vmax) + rtol)]
return ticks
class _ColorbarMappableDummy(object):
"""
Private class to hold deprecated ColorbarBase methods that used to be
inhereted from ScalarMappable.
"""
@cbook.deprecated("3.1", alternative="ScalarMappable.set_norm")
def set_norm(self, norm):
"""
`.colorbar.Colorbar.set_norm` does nothing; set the norm on
the mappable associated with this colorbar.
"""
pass
@cbook.deprecated("3.1", alternative="ScalarMappable.set_cmap")
def set_cmap(self, cmap):
"""
`.colorbar.Colorbar.set_cmap` does nothing; set the norm on
the mappable associated with this colorbar.
"""
pass
@cbook.deprecated("3.1", alternative="ScalarMappable.set_clim")
def set_clim(self, vmin=None, vmax=None):
"""
`.colorbar.Colorbar.set_clim` does nothing; set the limits on
the mappable associated with this colorbar.
"""
pass
@cbook.deprecated("3.1", alternative="ScalarMappable.get_cmap")
def get_cmap(self):
"""
return the colormap
"""
return self.cmap
@cbook.deprecated("3.1", alternative="ScalarMappable.get_clim")
def get_clim(self):
"""
return the min, max of the color limits for image scaling
"""
return self.norm.vmin, self.norm.vmax
class ColorbarBase(_ColorbarMappableDummy):
'''
Draw a colorbar in an existing axes.
This is a base class for the :class:`Colorbar` class, which is the
basis for the :func:`~matplotlib.pyplot.colorbar` function and the
:meth:`~matplotlib.figure.Figure.colorbar` method, which are the
usual ways of creating a colorbar.
It is also useful by itself for showing a colormap. If the *cmap*
kwarg is given but *boundaries* and *values* are left as None,
then the colormap will be displayed on a 0-1 scale. To show the
under- and over-value colors, specify the *norm* as::
colors.Normalize(clip=False)
To show the colors versus index instead of on the 0-1 scale,
use::
norm=colors.NoNorm.
Useful public methods are :meth:`set_label` and :meth:`add_lines`.
Attributes
----------
ax : Axes
The `Axes` instance in which the colorbar is drawn.
lines : list
A list of `LineCollection` if lines were drawn, otherwise
an empty list.
dividers : LineCollection
A LineCollection if *drawedges* is ``True``, otherwise ``None``.
'''
_slice_dict = {'neither': slice(0, None),
'both': slice(1, -1),
'min': slice(1, None),
'max': slice(0, -1)}
n_rasterize = 50 # rasterize solids if number of colors >= n_rasterize
def __init__(self, ax, cmap=None,
norm=None,
alpha=None,
values=None,
boundaries=None,
orientation='vertical',
ticklocation='auto',
extend='neither',
spacing='uniform', # uniform or proportional
ticks=None,
format=None,
drawedges=False,
filled=True,
extendfrac=None,
extendrect=False,
label='',
):
#: The axes that this colorbar lives in.
self.ax = ax
self._patch_ax()
if cmap is None:
cmap = cm.get_cmap()
if norm is None:
norm = colors.Normalize()
self.alpha = alpha
self.cmap = cmap
self.norm = norm
self.values = values
self.boundaries = boundaries
self.extend = extend
self._inside = self._slice_dict[extend]
self.spacing = spacing
self.orientation = orientation
self.drawedges = drawedges
self.filled = filled
self.extendfrac = extendfrac
self.extendrect = extendrect
self.solids = None
self.lines = list()
self.outline = None
self.patch = None
self.dividers = None
self.locator = None
self.formatter = None
self._manual_tick_data_values = None
if ticklocation == 'auto':
ticklocation = 'bottom' if orientation == 'horizontal' else 'right'
self.ticklocation = ticklocation
self.set_label(label)
self._reset_locator_formatter_scale()
if np.iterable(ticks):
self.locator = ticker.FixedLocator(ticks, nbins=len(ticks))
else:
self.locator = ticks # Handle default in _ticker()
if isinstance(format, str):
self.formatter = ticker.FormatStrFormatter(format)
else:
self.formatter = format # Assume it is a Formatter or None
self.draw_all()
def _extend_lower(self):
"""Return whether the lower limit is open ended."""
return self.extend in ('both', 'min')
def _extend_upper(self):
"""Return whether the uper limit is open ended."""
return self.extend in ('both', 'max')
def _patch_ax(self):
# bind some methods to the axes to warn users
# against using those methods.
self.ax.set_xticks = _set_ticks_on_axis_warn
self.ax.set_yticks = _set_ticks_on_axis_warn
def draw_all(self):
'''
Calculate any free parameters based on the current cmap and norm,
and do all the drawing.
'''
# sets self._boundaries and self._values in real data units.
# takes into account extend values:
self._process_values()
# sets self.vmin and vmax in data units, but just for
# the part of the colorbar that is not part of the extend
# patch:
self._find_range()
# returns the X and Y mesh, *but* this was/is in normalized
# units:
X, Y = self._mesh()
C = self._values[:, np.newaxis]
self.config_axis()
self._config_axes(X, Y)
if self.filled:
self._add_solids(X, Y, C)
def config_axis(self):
ax = self.ax
if self.orientation == 'vertical':
long_axis, short_axis = ax.yaxis, ax.xaxis
else:
long_axis, short_axis = ax.xaxis, ax.yaxis
long_axis.set_label_position(self.ticklocation)
long_axis.set_ticks_position(self.ticklocation)
short_axis.set_ticks([])
short_axis.set_ticks([], minor=True)
self._set_label()
def _get_ticker_locator_formatter(self):
"""
This code looks at the norm being used by the colorbar
and decides what locator and formatter to use. If ``locator`` has
already been set by hand, it just returns
``self.locator, self.formatter``.
"""
locator = self.locator
formatter = self.formatter
if locator is None:
if self.boundaries is None:
if isinstance(self.norm, colors.NoNorm):
nv = len(self._values)
base = 1 + int(nv / 10)
locator = ticker.IndexLocator(base=base, offset=0)
elif isinstance(self.norm, colors.BoundaryNorm):
b = self.norm.boundaries
locator = ticker.FixedLocator(b, nbins=10)
elif isinstance(self.norm, colors.LogNorm):
locator = _ColorbarLogLocator(self)
elif isinstance(self.norm, colors.SymLogNorm):
# The subs setting here should be replaced
# by logic in the locator.
locator = ticker.SymmetricalLogLocator(
subs=np.arange(1, 10),
linthresh=self.norm.linthresh,
base=10)
else:
if mpl.rcParams['_internal.classic_mode']:
locator = ticker.MaxNLocator()
else:
locator = _ColorbarAutoLocator(self)
else:
b = self._boundaries[self._inside]
locator = ticker.FixedLocator(b, nbins=10)
if formatter is None:
if isinstance(self.norm, colors.LogNorm):
formatter = ticker.LogFormatterSciNotation()
elif isinstance(self.norm, colors.SymLogNorm):
formatter = ticker.LogFormatterSciNotation(
linthresh=self.norm.linthresh)
else:
formatter = ticker.ScalarFormatter()
else:
formatter = self.formatter
self.locator = locator
self.formatter = formatter
_log.debug('locator: %r', locator)
return locator, formatter
def _use_auto_colorbar_locator(self):
"""
Return if we should use an adjustable tick locator or a fixed
one. (check is used twice so factored out here...)
"""
return (self.boundaries is None
and self.values is None
and ((type(self.norm) == colors.Normalize)
or (type(self.norm) == colors.LogNorm)))
def _reset_locator_formatter_scale(self):
"""
Reset the locator et al to defaults. Any user-hardcoded changes
need to be re-entered if this gets called (either at init, or when
the mappable normal gets changed: Colorbar.update_normal)
"""
self.locator = None
self.formatter = None
if (isinstance(self.norm, colors.LogNorm)
and self._use_auto_colorbar_locator()):
# *both* axes are made log so that determining the
# mid point is easier.
self.ax.set_xscale('log')
self.ax.set_yscale('log')
self.minorticks_on()
else:
self.ax.set_xscale('linear')
self.ax.set_yscale('linear')
def update_ticks(self):
"""
Force the update of the ticks and ticklabels. This must be
called whenever the tick locator and/or tick formatter changes.
"""
ax = self.ax
# get the locator and formatter. Defaults to
# self.locator if not None..
locator, formatter = self._get_ticker_locator_formatter()
if self.orientation == 'vertical':
long_axis, short_axis = ax.yaxis, ax.xaxis
else:
long_axis, short_axis = ax.xaxis, ax.yaxis
if self._use_auto_colorbar_locator():
_log.debug('Using auto colorbar locator on colorbar')
_log.debug('locator: %r', locator)
long_axis.set_major_locator(locator)
long_axis.set_major_formatter(formatter)
else:
_log.debug('Using fixed locator on colorbar')
ticks, ticklabels, offset_string = self._ticker(locator, formatter)
long_axis.set_ticks(ticks)
long_axis.set_ticklabels(ticklabels)
long_axis.get_major_formatter().set_offset_string(offset_string)
def set_ticks(self, ticks, update_ticks=True):
"""
Set tick locations.
Parameters
----------
ticks : {None, sequence, :class:`~matplotlib.ticker.Locator` instance}
If None, a default Locator will be used.
update_ticks : {True, False}, optional
If True, tick locations are updated immediately. If False,
use :meth:`update_ticks` to manually update the ticks.
"""
if np.iterable(ticks):
self.locator = ticker.FixedLocator(ticks, nbins=len(ticks))
else:
self.locator = ticks
if update_ticks:
self.update_ticks()
self.stale = True
def get_ticks(self, minor=False):
"""Return the x ticks as a list of locations."""
if self._manual_tick_data_values is None:
ax = self.ax
if self.orientation == 'vertical':
long_axis, short_axis = ax.yaxis, ax.xaxis
else:
long_axis, short_axis = ax.xaxis, ax.yaxis
return long_axis.get_majorticklocs()
else:
# We made the axes manually, the old way, and the ylim is 0-1,
# so the majorticklocs are in those units, not data units.
return self._manual_tick_data_values
def set_ticklabels(self, ticklabels, update_ticks=True):
"""
Set tick labels.
Tick labels are updated immediately unless *update_ticks* is *False*,
in which case one should call `.update_ticks` explicitly.
"""
if isinstance(self.locator, ticker.FixedLocator):
self.formatter = ticker.FixedFormatter(ticklabels)
if update_ticks:
self.update_ticks()
else:
cbook._warn_external("set_ticks() must have been called.")
self.stale = True
def minorticks_on(self):
"""
Turns on the minor ticks on the colorbar without extruding
into the "extend regions".
"""
ax = self.ax
long_axis = ax.yaxis if self.orientation == 'vertical' else ax.xaxis
if long_axis.get_scale() == 'log':
long_axis.set_minor_locator(_ColorbarLogLocator(self, base=10.,
subs='auto'))
long_axis.set_minor_formatter(ticker.LogFormatterSciNotation())
else:
long_axis.set_minor_locator(_ColorbarAutoMinorLocator(self))
def minorticks_off(self):
"""
Turns off the minor ticks on the colorbar.
"""
ax = self.ax
long_axis = ax.yaxis if self.orientation == 'vertical' else ax.xaxis
long_axis.set_minor_locator(ticker.NullLocator())
def _config_axes(self, X, Y):
'''
Make an axes patch and outline.
'''
ax = self.ax
ax.set_frame_on(False)
ax.set_navigate(False)
xy = self._outline(X, Y)
ax.ignore_existing_data_limits = True
ax.update_datalim(xy)
ax.set_xlim(*ax.dataLim.intervalx)
ax.set_ylim(*ax.dataLim.intervaly)
if self.outline is not None:
self.outline.remove()
self.outline = mpatches.Polygon(
xy, edgecolor=mpl.rcParams['axes.edgecolor'],
facecolor='none',
linewidth=mpl.rcParams['axes.linewidth'],
closed=True,
zorder=2)
ax.add_artist(self.outline)
self.outline.set_clip_box(None)
self.outline.set_clip_path(None)
c = mpl.rcParams['axes.facecolor']
if self.patch is not None:
self.patch.remove()
self.patch = mpatches.Polygon(xy, edgecolor=c,
facecolor=c,
linewidth=0.01,
zorder=-1)
ax.add_artist(self.patch)
self.update_ticks()
def _set_label(self):
if self.orientation == 'vertical':
self.ax.set_ylabel(self._label, **self._labelkw)
else:
self.ax.set_xlabel(self._label, **self._labelkw)
self.stale = True
def set_label(self, label, **kw):
"""Label the long axis of the colorbar."""
self._label = str(label)
self._labelkw = kw
self._set_label()
def _outline(self, X, Y):
'''
Return *x*, *y* arrays of colorbar bounding polygon,
taking orientation into account.
'''
N = X.shape[0]
ii = [0, 1, N - 2, N - 1, 2 * N - 1, 2 * N - 2, N + 1, N, 0]
x = X.T.reshape(-1)[ii]
y = Y.T.reshape(-1)[ii]
return (np.column_stack([y, x])
if self.orientation == 'horizontal' else
np.column_stack([x, y]))
def _edges(self, X, Y):
'''
Return the separator line segments; helper for _add_solids.
'''
N = X.shape[0]
# Using the non-array form of these line segments is much
# simpler than making them into arrays.
if self.orientation == 'vertical':
return [list(zip(X[i], Y[i])) for i in range(1, N - 1)]
else:
return [list(zip(Y[i], X[i])) for i in range(1, N - 1)]
def _add_solids(self, X, Y, C):
'''
Draw the colors using :meth:`~matplotlib.axes.Axes.pcolormesh`;
optionally add separators.
'''
if self.orientation == 'vertical':
args = (X, Y, C)
else:
args = (np.transpose(Y), np.transpose(X), np.transpose(C))
kw = dict(cmap=self.cmap,
norm=self.norm,
alpha=self.alpha,
edgecolors='None')
_log.debug('Setting pcolormesh')
col = self.ax.pcolormesh(*args, **kw)
# self.add_observer(col) # We should observe, not be observed...
if self.solids is not None:
self.solids.remove()
self.solids = col
if self.dividers is not None:
self.dividers.remove()
self.dividers = None
if self.drawedges:
linewidths = (0.5 * mpl.rcParams['axes.linewidth'],)
self.dividers = collections.LineCollection(
self._edges(X, Y),
colors=(mpl.rcParams['axes.edgecolor'],),
linewidths=linewidths)
self.ax.add_collection(self.dividers)
elif len(self._y) >= self.n_rasterize:
self.solids.set_rasterized(True)
def add_lines(self, levels, colors, linewidths, erase=True):
'''
Draw lines on the colorbar.
*colors* and *linewidths* must be scalars or
sequences the same length as *levels*.
Set *erase* to False to add lines without first
removing any previously added lines.
'''
y = self._locate(levels)
rtol = (self._y[-1] - self._y[0]) * 1e-10
igood = (y < self._y[-1] + rtol) & (y > self._y[0] - rtol)
y = y[igood]
if np.iterable(colors):
colors = np.asarray(colors)[igood]
if np.iterable(linewidths):
linewidths = np.asarray(linewidths)[igood]
X, Y = np.meshgrid([self._y[0], self._y[-1]], y)
if self.orientation == 'vertical':
xy = np.stack([X, Y], axis=-1)
else:
xy = np.stack([Y, X], axis=-1)
col = collections.LineCollection(xy, linewidths=linewidths)
if erase and self.lines:
for lc in self.lines:
lc.remove()
self.lines = []
self.lines.append(col)
col.set_color(colors)
self.ax.add_collection(col)
self.stale = True
def _ticker(self, locator, formatter):
'''
Return the sequence of ticks (colorbar data locations),
ticklabels (strings), and the corresponding offset string.
'''
if isinstance(self.norm, colors.NoNorm) and self.boundaries is None:
intv = self._values[0], self._values[-1]
else:
intv = self.vmin, self.vmax
locator.create_dummy_axis(minpos=intv[0])
formatter.create_dummy_axis(minpos=intv[0])
locator.set_view_interval(*intv)
locator.set_data_interval(*intv)
formatter.set_view_interval(*intv)
formatter.set_data_interval(*intv)
b = np.array(locator())
if isinstance(locator, ticker.LogLocator):
eps = 1e-10
b = b[(b <= intv[1] * (1 + eps)) & (b >= intv[0] * (1 - eps))]
else:
eps = (intv[1] - intv[0]) * 1e-10
b = b[(b <= intv[1] + eps) & (b >= intv[0] - eps)]
self._manual_tick_data_values = b
ticks = self._locate(b)
ticklabels = formatter.format_ticks(b)
offset_string = formatter.get_offset()
return ticks, ticklabels, offset_string
def _process_values(self, b=None):
'''
Set the :attr:`_boundaries` and :attr:`_values` attributes
based on the input boundaries and values. Input boundaries
can be *self.boundaries* or the argument *b*.
'''
if b is None:
b = self.boundaries
if b is not None:
self._boundaries = np.asarray(b, dtype=float)
if self.values is None:
self._values = 0.5 * (self._boundaries[:-1]
+ self._boundaries[1:])
if isinstance(self.norm, colors.NoNorm):
self._values = (self._values + 0.00001).astype(np.int16)
else:
self._values = np.array(self.values)
return
if self.values is not None:
self._values = np.array(self.values)
if self.boundaries is None:
b = np.zeros(len(self.values) + 1)
b[1:-1] = 0.5 * (self._values[:-1] + self._values[1:])
b[0] = 2.0 * b[1] - b[2]
b[-1] = 2.0 * b[-2] - b[-3]
self._boundaries = b
return
self._boundaries = np.array(self.boundaries)
return
# Neither boundaries nor values are specified;
# make reasonable ones based on cmap and norm.
if isinstance(self.norm, colors.NoNorm):
b = self._uniform_y(self.cmap.N + 1) * self.cmap.N - 0.5
v = np.zeros(len(b) - 1, dtype=np.int16)
v[self._inside] = np.arange(self.cmap.N, dtype=np.int16)
if self._extend_lower():
v[0] = -1
if self._extend_upper():
v[-1] = self.cmap.N
self._boundaries = b
self._values = v
return
elif isinstance(self.norm, colors.BoundaryNorm):
b = list(self.norm.boundaries)
if self._extend_lower():
b = [b[0] - 1] + b
if self._extend_upper():
b = b + [b[-1] + 1]
b = np.array(b)
v = np.zeros(len(b) - 1)
bi = self.norm.boundaries
v[self._inside] = 0.5 * (bi[:-1] + bi[1:])
if self._extend_lower():
v[0] = b[0] - 1
if self._extend_upper():
v[-1] = b[-1] + 1
self._boundaries = b
self._values = v
return
else:
if not self.norm.scaled():
self.norm.vmin = 0
self.norm.vmax = 1
self.norm.vmin, self.norm.vmax = mtransforms.nonsingular(
self.norm.vmin,
self.norm.vmax,
expander=0.1)
b = self.norm.inverse(self._uniform_y(self.cmap.N + 1))
if isinstance(self.norm, (colors.PowerNorm, colors.LogNorm)):
# If using a lognorm or powernorm, ensure extensions don't
# go negative
if self._extend_lower():
b[0] = 0.9 * b[0]
if self._extend_upper():
b[-1] = 1.1 * b[-1]
else:
if self._extend_lower():
b[0] = b[0] - 1
if self._extend_upper():
b[-1] = b[-1] + 1
self._process_values(b)
def _find_range(self):
'''
Set :attr:`vmin` and :attr:`vmax` attributes to the first and
last boundary excluding extended end boundaries.
'''
b = self._boundaries[self._inside]
self.vmin = b[0]
self.vmax = b[-1]
def _central_N(self):
"""Return the number of boundaries excluding end extensions."""
nb = len(self._boundaries)
if self.extend == 'both':
nb -= 2
elif self.extend in ('min', 'max'):
nb -= 1
return nb
def _extended_N(self):
'''
Based on the colormap and extend variable, return the
number of boundaries.
'''
N = self.cmap.N + 1
if self.extend == 'both':
N += 2
elif self.extend in ('min', 'max'):
N += 1
return N
def _get_extension_lengths(self, frac, automin, automax, default=0.05):
'''
Get the lengths of colorbar extensions.
A helper method for _uniform_y and _proportional_y.
'''
# Set the default value.
extendlength = np.array([default, default])
if isinstance(frac, str):
if frac.lower() == 'auto':
# Use the provided values when 'auto' is required.
extendlength[:] = [automin, automax]
else:
# Any other string is invalid.
raise ValueError('invalid value for extendfrac')
elif frac is not None:
try:
# Try to set min and max extension fractions directly.
extendlength[:] = frac
# If frac is a sequence containing None then NaN may
# be encountered. This is an error.
if np.isnan(extendlength).any():
raise ValueError()
except (TypeError, ValueError):
# Raise an error on encountering an invalid value for frac.
raise ValueError('invalid value for extendfrac')
return extendlength
def _uniform_y(self, N):
'''
Return colorbar data coordinates for *N* uniformly
spaced boundaries, plus ends if required.
'''
if self.extend == 'neither':
y = np.linspace(0, 1, N)
else:
automin = automax = 1. / (N - 1.)
extendlength = self._get_extension_lengths(self.extendfrac,
automin, automax,
default=0.05)
if self.extend == 'both':
y = np.zeros(N + 2, 'd')
y[0] = 0. - extendlength[0]
y[-1] = 1. + extendlength[1]
elif self.extend == 'min':
y = np.zeros(N + 1, 'd')
y[0] = 0. - extendlength[0]
else:
y = np.zeros(N + 1, 'd')
y[-1] = 1. + extendlength[1]
y[self._inside] = np.linspace(0, 1, N)
return y
def _proportional_y(self):
'''
Return colorbar data coordinates for the boundaries of
a proportional colorbar.
'''
if isinstance(self.norm, colors.BoundaryNorm):
y = (self._boundaries - self._boundaries[0])
y = y / (self._boundaries[-1] - self._boundaries[0])
else:
y = self.norm(self._boundaries.copy())
y = np.ma.filled(y, np.nan)
if self.extend == 'min':
# Exclude leftmost interval of y.
clen = y[-1] - y[1]
automin = (y[2] - y[1]) / clen
automax = (y[-1] - y[-2]) / clen
elif self.extend == 'max':
# Exclude rightmost interval in y.
clen = y[-2] - y[0]
automin = (y[1] - y[0]) / clen
automax = (y[-2] - y[-3]) / clen
elif self.extend == 'both':
# Exclude leftmost and rightmost intervals in y.
clen = y[-2] - y[1]
automin = (y[2] - y[1]) / clen
automax = (y[-2] - y[-3]) / clen
if self.extend in ('both', 'min', 'max'):
extendlength = self._get_extension_lengths(self.extendfrac,
automin, automax,
default=0.05)
if self.extend in ('both', 'min'):
y[0] = 0. - extendlength[0]
if self.extend in ('both', 'max'):
y[-1] = 1. + extendlength[1]
yi = y[self._inside]
norm = colors.Normalize(yi[0], yi[-1])
y[self._inside] = np.ma.filled(norm(yi), np.nan)
return y
def _mesh(self):
'''
Return X,Y, the coordinate arrays for the colorbar pcolormesh.
These are suitable for a vertical colorbar; swapping and
transposition for a horizontal colorbar are done outside
this function.
'''
# if boundaries and values are None, then we can go ahead and
# scale this up for Auto tick location. Otherwise we
# want to keep normalized between 0 and 1 and use manual tick
# locations.
x = np.array([0.0, 1.0])
if self.spacing == 'uniform':
y = self._uniform_y(self._central_N())
else:
y = self._proportional_y()
if self._use_auto_colorbar_locator():
y = self.norm.inverse(y)
x = self.norm.inverse(x)
self._y = y
X, Y = np.meshgrid(x, y)
if self._use_auto_colorbar_locator():
xmid = self.norm.inverse(0.5)
else:
xmid = 0.5
if self._extend_lower() and not self.extendrect:
X[0, :] = xmid
if self._extend_upper() and not self.extendrect:
X[-1, :] = xmid
return X, Y
def _locate(self, x):
'''
Given a set of color data values, return their
corresponding colorbar data coordinates.
'''
if isinstance(self.norm, (colors.NoNorm, colors.BoundaryNorm)):
b = self._boundaries
xn = x
else:
# Do calculations using normalized coordinates so
# as to make the interpolation more accurate.
b = self.norm(self._boundaries, clip=False).filled()
xn = self.norm(x, clip=False).filled()
bunique = b
yunique = self._y
# trim extra b values at beginning and end if they are
# not unique. These are here for extended colorbars, and are not
# wanted for the interpolation.
if b[0] == b[1]:
bunique = bunique[1:]
yunique = yunique[1:]
if b[-1] == b[-2]:
bunique = bunique[:-1]
yunique = yunique[:-1]
z = np.interp(xn, bunique, yunique)
return z
def set_alpha(self, alpha):
self.alpha = alpha
def remove(self):
"""
Remove this colorbar from the figure
"""
fig = self.ax.figure
fig.delaxes(self.ax)
class Colorbar(ColorbarBase):
"""
This class connects a :class:`ColorbarBase` to a
:class:`~matplotlib.cm.ScalarMappable` such as a
:class:`~matplotlib.image.AxesImage` generated via
:meth:`~matplotlib.axes.Axes.imshow`.
It is not intended to be instantiated directly; instead,
use :meth:`~matplotlib.figure.Figure.colorbar` or
:func:`~matplotlib.pyplot.colorbar` to make your colorbar.
"""
def __init__(self, ax, mappable, **kw):
# Ensure the given mappable's norm has appropriate vmin and vmax set
# even if mappable.draw has not yet been called.
if mappable.get_array() is not None:
mappable.autoscale_None()
self.mappable = mappable
kw['cmap'] = cmap = mappable.cmap
kw['norm'] = mappable.norm
if isinstance(mappable, contour.ContourSet):
CS = mappable
kw['alpha'] = mappable.get_alpha()
kw['boundaries'] = CS._levels
kw['values'] = CS.cvalues
kw['extend'] = CS.extend
kw.setdefault('ticks', ticker.FixedLocator(CS.levels, nbins=10))
kw['filled'] = CS.filled
ColorbarBase.__init__(self, ax, **kw)
if not CS.filled:
self.add_lines(CS)
else:
if getattr(cmap, 'colorbar_extend', False) is not False:
kw.setdefault('extend', cmap.colorbar_extend)
if isinstance(mappable, martist.Artist):
kw['alpha'] = mappable.get_alpha()
ColorbarBase.__init__(self, ax, **kw)
def on_mappable_changed(self, mappable):
"""
Updates this colorbar to match the mappable's properties.
Typically this is automatically registered as an event handler
by :func:`colorbar_factory` and should not be called manually.
"""
_log.debug('colorbar mappable changed')
self.update_normal(mappable)
def add_lines(self, CS, erase=True):
'''
Add the lines from a non-filled
:class:`~matplotlib.contour.ContourSet` to the colorbar.
Set *erase* to False if these lines should be added to
any pre-existing lines.
'''
if not isinstance(CS, contour.ContourSet) or CS.filled:
raise ValueError('add_lines is only for a ContourSet of lines')
tcolors = [c[0] for c in CS.tcolors]
tlinewidths = [t[0] for t in CS.tlinewidths]
# The following was an attempt to get the colorbar lines
# to follow subsequent changes in the contour lines,
# but more work is needed: specifically, a careful
# look at event sequences, and at how
# to make one object track another automatically.
#tcolors = [col.get_colors()[0] for col in CS.collections]
#tlinewidths = [col.get_linewidth()[0] for lw in CS.collections]
ColorbarBase.add_lines(self, CS.levels, tcolors, tlinewidths,
erase=erase)
def update_normal(self, mappable):
"""
Update solid patches, lines, etc.
Unlike `.update_bruteforce`, this does not clear the axes. This is
meant to be called when the norm of the image or contour plot to which
this colorbar belongs changes.
If the norm on the mappable is different than before, this resets the
locator and formatter for the axis, so if these have been customized,
they will need to be customized again. However, if the norm only
changes values of *vmin*, *vmax* or *cmap* then the old formatter
and locator will be preserved.
"""
_log.debug('colorbar update normal %r %r', mappable.norm, self.norm)
self.mappable = mappable
self.set_alpha(mappable.get_alpha())
self.cmap = mappable.cmap
if mappable.norm != self.norm:
self.norm = mappable.norm
self._reset_locator_formatter_scale()
self.draw_all()
if isinstance(self.mappable, contour.ContourSet):
CS = self.mappable
if not CS.filled:
self.add_lines(CS)
self.stale = True
def update_bruteforce(self, mappable):
'''
Destroy and rebuild the colorbar. This is
intended to become obsolete, and will probably be
deprecated and then removed. It is not called when
the pyplot.colorbar function or the Figure.colorbar
method are used to create the colorbar.
'''
# We are using an ugly brute-force method: clearing and
# redrawing the whole thing. The problem is that if any
# properties have been changed by methods other than the
# colorbar methods, those changes will be lost.
self.ax.cla()
self.locator = None
self.formatter = None
# clearing the axes will delete outline, patch, solids, and lines:
self.outline = None
self.patch = None
self.solids = None
self.lines = list()
self.dividers = None
self.update_normal(mappable)
self.draw_all()
if isinstance(self.mappable, contour.ContourSet):
CS = self.mappable
if not CS.filled:
self.add_lines(CS)
#if self.lines is not None:
# tcolors = [c[0] for c in CS.tcolors]
# self.lines.set_color(tcolors)
#Fixme? Recalculate boundaries, ticks if vmin, vmax have changed.
#Fixme: Some refactoring may be needed; we should not
# be recalculating everything if there was a simple alpha
# change.
def remove(self):
"""
Remove this colorbar from the figure. If the colorbar was created with
``use_gridspec=True`` then restore the gridspec to its previous value.
"""
ColorbarBase.remove(self)
self.mappable.callbacksSM.disconnect(self.mappable.colorbar_cid)
self.mappable.colorbar = None
self.mappable.colorbar_cid = None
try:
ax = self.mappable.axes
except AttributeError:
return
try:
gs = ax.get_subplotspec().get_gridspec()
subplotspec = gs.get_topmost_subplotspec()
except AttributeError:
# use_gridspec was False
pos = ax.get_position(original=True)
ax._set_position(pos)
else:
# use_gridspec was True
ax.set_subplotspec(subplotspec)
@docstring.Substitution(make_axes_kw_doc)
def make_axes(parents, location=None, orientation=None, fraction=0.15,
shrink=1.0, aspect=20, **kw):
'''
Resize and reposition parent axes, and return a child
axes suitable for a colorbar.
Keyword arguments may include the following (with defaults):
location : [None|'left'|'right'|'top'|'bottom']
The position, relative to **parents**, where the colorbar axes
should be created. If None, the value will either come from the
given ``orientation``, else it will default to 'right'.
orientation : [None|'vertical'|'horizontal']
The orientation of the colorbar. Typically, this keyword shouldn't
be used, as it can be derived from the ``location`` keyword.
%s
Returns (cax, kw), the child axes and the reduced kw dictionary to be
passed when creating the colorbar instance.
'''
locations = ["left", "right", "top", "bottom"]
if orientation is not None and location is not None:
raise TypeError('position and orientation are mutually exclusive. '
'Consider setting the position to any of {}'
.format(', '.join(locations)))
# provide a default location
if location is None and orientation is None:
location = 'right'
# allow the user to not specify the location by specifying the
# orientation instead
if location is None:
location = 'right' if orientation == 'vertical' else 'bottom'
if location not in locations:
raise ValueError('Invalid colorbar location. Must be one '
'of %s' % ', '.join(locations))
default_location_settings = {'left': {'anchor': (1.0, 0.5),
'panchor': (0.0, 0.5),
'pad': 0.10,
'orientation': 'vertical'},
'right': {'anchor': (0.0, 0.5),
'panchor': (1.0, 0.5),
'pad': 0.05,
'orientation': 'vertical'},
'top': {'anchor': (0.5, 0.0),
'panchor': (0.5, 1.0),
'pad': 0.05,
'orientation': 'horizontal'},
'bottom': {'anchor': (0.5, 1.0),
'panchor': (0.5, 0.0),
'pad': 0.15, # backwards compat
'orientation': 'horizontal'},
}
loc_settings = default_location_settings[location]
# put appropriate values into the kw dict for passing back to
# the Colorbar class
kw['orientation'] = loc_settings['orientation']
kw['ticklocation'] = location
anchor = kw.pop('anchor', loc_settings['anchor'])
parent_anchor = kw.pop('panchor', loc_settings['panchor'])
parents_iterable = np.iterable(parents)
# turn parents into a list if it is not already. We do this w/ np
# because `plt.subplots` can return an ndarray and is natural to
# pass to `colorbar`.
parents = np.atleast_1d(parents).ravel()
# check if using constrained_layout:
try:
gs = parents[0].get_subplotspec().get_gridspec()
using_constrained_layout = (gs._layoutbox is not None)
except AttributeError:
using_constrained_layout = False
# defaults are not appropriate for constrained_layout:
pad0 = loc_settings['pad']
if using_constrained_layout:
pad0 = 0.02
pad = kw.pop('pad', pad0)
fig = parents[0].get_figure()
if not all(fig is ax.get_figure() for ax in parents):
raise ValueError('Unable to create a colorbar axes as not all '
'parents share the same figure.')
# take a bounding box around all of the given axes
parents_bbox = mtransforms.Bbox.union(
[ax.get_position(original=True).frozen() for ax in parents])
pb = parents_bbox
if location in ('left', 'right'):
if location == 'left':
pbcb, _, pb1 = pb.splitx(fraction, fraction + pad)
else:
pb1, _, pbcb = pb.splitx(1 - fraction - pad, 1 - fraction)
pbcb = pbcb.shrunk(1.0, shrink).anchored(anchor, pbcb)
else:
if location == 'bottom':
pbcb, _, pb1 = pb.splity(fraction, fraction + pad)
else:
pb1, _, pbcb = pb.splity(1 - fraction - pad, 1 - fraction)
pbcb = pbcb.shrunk(shrink, 1.0).anchored(anchor, pbcb)
# define the aspect ratio in terms of y's per x rather than x's per y
aspect = 1.0 / aspect
# define a transform which takes us from old axes coordinates to
# new axes coordinates
shrinking_trans = mtransforms.BboxTransform(parents_bbox, pb1)
# transform each of the axes in parents using the new transform
for ax in parents:
new_posn = shrinking_trans.transform(ax.get_position(original=True))
new_posn = mtransforms.Bbox(new_posn)
ax._set_position(new_posn)
if parent_anchor is not False:
ax.set_anchor(parent_anchor)
cax = fig.add_axes(pbcb, label="<colorbar>")
# OK, now make a layoutbox for the cb axis. Later, we will use this
# to make the colorbar fit nicely.
if not using_constrained_layout:
# no layout boxes:
lb = None
lbpos = None
# and we need to set the aspect ratio by hand...
cax.set_aspect(aspect, anchor=anchor, adjustable='box')
else:
if not parents_iterable:
# this is a single axis...
ax = parents[0]
lb, lbpos = constrained_layout.layoutcolorbarsingle(
ax, cax, shrink, aspect, location, pad=pad)
else: # there is more than one parent, so lets use gridspec
# the colorbar will be a sibling of this gridspec, so the
# parent is the same parent as the gridspec. Either the figure,
# or a subplotspec.
lb, lbpos = constrained_layout.layoutcolorbargridspec(
parents, cax, shrink, aspect, location, pad)
cax._layoutbox = lb
cax._poslayoutbox = lbpos
return cax, kw
@docstring.Substitution(make_axes_kw_doc)
def make_axes_gridspec(parent, *, fraction=0.15, shrink=1.0, aspect=20, **kw):
'''
Resize and reposition a parent axes, and return a child axes
suitable for a colorbar. This function is similar to
make_axes. Prmary differences are
* *make_axes_gridspec* only handles the *orientation* keyword
and cannot handle the "location" keyword.
* *make_axes_gridspec* should only be used with a subplot parent.
* *make_axes* creates an instance of Axes. *make_axes_gridspec*
creates an instance of Subplot.
* *make_axes* updates the position of the
parent. *make_axes_gridspec* replaces the grid_spec attribute
of the parent with a new one.
While this function is meant to be compatible with *make_axes*,
there could be some minor differences.
Keyword arguments may include the following (with defaults):
*orientation*
'vertical' or 'horizontal'
%s
All but the first of these are stripped from the input kw set.
Returns (cax, kw), the child axes and the reduced kw dictionary to be
passed when creating the colorbar instance.
'''
orientation = kw.setdefault('orientation', 'vertical')
kw['ticklocation'] = 'auto'
x1 = 1 - fraction
# for shrinking
pad_s = (1 - shrink) * 0.5
wh_ratios = [pad_s, shrink, pad_s]
# we need to none the tree of layoutboxes because
# constrained_layout can't remove and replace the tree
# hierarchy w/o a seg fault.
gs = parent.get_subplotspec().get_gridspec()
layoutbox.nonetree(gs._layoutbox)
gs_from_subplotspec = gridspec.GridSpecFromSubplotSpec
if orientation == 'vertical':
pad = kw.pop('pad', 0.05)
wh_space = 2 * pad / (1 - pad)
gs = gs_from_subplotspec(1, 2,
subplot_spec=parent.get_subplotspec(),
wspace=wh_space,
width_ratios=[x1 - pad, fraction])
gs2 = gs_from_subplotspec(3, 1,
subplot_spec=gs[1],
hspace=0.,
height_ratios=wh_ratios)
anchor = (0.0, 0.5)
panchor = (1.0, 0.5)
else:
pad = kw.pop('pad', 0.15)
wh_space = 2 * pad / (1 - pad)
gs = gs_from_subplotspec(2, 1,
subplot_spec=parent.get_subplotspec(),
hspace=wh_space,
height_ratios=[x1 - pad, fraction])
gs2 = gs_from_subplotspec(1, 3,
subplot_spec=gs[1],
wspace=0.,
width_ratios=wh_ratios)
aspect = 1 / aspect
anchor = (0.5, 1.0)
panchor = (0.5, 0.0)
parent.set_subplotspec(gs[0])
parent.update_params()
parent._set_position(parent.figbox)
parent.set_anchor(panchor)
fig = parent.get_figure()
cax = fig.add_subplot(gs2[1], label="<colorbar>")
cax.set_aspect(aspect, anchor=anchor, adjustable='box')
return cax, kw
class ColorbarPatch(Colorbar):
"""
A Colorbar which is created using :class:`~matplotlib.patches.Patch`
rather than the default :func:`~matplotlib.axes.pcolor`.
It uses a list of Patch instances instead of a
:class:`~matplotlib.collections.PatchCollection` because the
latter does not allow the hatch pattern to vary among the
members of the collection.
"""
def __init__(self, ax, mappable, **kw):
# we do not want to override the behaviour of solids
# so add a new attribute which will be a list of the
# colored patches in the colorbar
self.solids_patches = []
Colorbar.__init__(self, ax, mappable, **kw)
def _add_solids(self, X, Y, C):
"""
Draw the colors using :class:`~matplotlib.patches.Patch`;
optionally add separators.
"""
n_segments = len(C)
# ensure there are sufficient hatches
hatches = self.mappable.hatches * n_segments
patches = []
for i in range(len(X) - 1):
val = C[i][0]
hatch = hatches[i]
xy = np.array([[X[i][0], Y[i][0]],
[X[i][1], Y[i][0]],
[X[i + 1][1], Y[i + 1][0]],
[X[i + 1][0], Y[i + 1][1]]])
if self.orientation == 'horizontal':
# if horizontal swap the xs and ys
xy = xy[..., ::-1]
patch = mpatches.PathPatch(mpath.Path(xy),
facecolor=self.cmap(self.norm(val)),
hatch=hatch, linewidth=0,
antialiased=False, alpha=self.alpha)
self.ax.add_patch(patch)
patches.append(patch)
if self.solids_patches:
for solid in self.solids_patches:
solid.remove()
self.solids_patches = patches
if self.dividers is not None:
self.dividers.remove()
self.dividers = None
if self.drawedges:
self.dividers = collections.LineCollection(
self._edges(X, Y),
colors=(mpl.rcParams['axes.edgecolor'],),
linewidths=(0.5 * mpl.rcParams['axes.linewidth'],))
self.ax.add_collection(self.dividers)
def colorbar_factory(cax, mappable, **kwargs):
"""
Creates a colorbar on the given axes for the given mappable.
Typically, for automatic colorbar placement given only a mappable use
:meth:`~matplotlib.figure.Figure.colorbar`.
"""
# if the given mappable is a contourset with any hatching, use
# ColorbarPatch else use Colorbar
if (isinstance(mappable, contour.ContourSet)
and any(hatch is not None for hatch in mappable.hatches)):
cb = ColorbarPatch(cax, mappable, **kwargs)
else:
cb = Colorbar(cax, mappable, **kwargs)
cid = mappable.callbacksSM.connect('changed', cb.on_mappable_changed)
mappable.colorbar = cb
mappable.colorbar_cid = cid
return cb
|
0c5eca3bc9825128f48ef77616f9b01c92d1c50eaef07ec907fce6d95d828dce
|
"""
The figure module provides the top-level
:class:`~matplotlib.artist.Artist`, the :class:`Figure`, which
contains all the plot elements. The following classes are defined
:class:`SubplotParams`
control the default spacing of the subplots
:class:`Figure`
Top level container for all plot elements.
"""
import logging
from numbers import Integral
import numpy as np
from matplotlib import rcParams
from matplotlib import backends, docstring, projections
from matplotlib import __version__ as _mpl_version
from matplotlib import get_backend
import matplotlib.artist as martist
from matplotlib.artist import Artist, allow_rasterization
from matplotlib.backend_bases import FigureCanvasBase
import matplotlib.cbook as cbook
import matplotlib.colorbar as cbar
import matplotlib.image as mimage
from matplotlib.axes import Axes, SubplotBase, subplot_class_factory
from matplotlib.blocking_input import BlockingMouseInput, BlockingKeyMouseInput
from matplotlib.gridspec import GridSpec
import matplotlib.legend as mlegend
from matplotlib.patches import Rectangle
from matplotlib.projections import (get_projection_names,
process_projection_requirements)
from matplotlib.text import Text, TextWithDash
from matplotlib.transforms import (Affine2D, Bbox, BboxTransformTo,
TransformedBbox)
import matplotlib._layoutbox as layoutbox
from matplotlib.backend_bases import NonGuiException
_log = logging.getLogger(__name__)
docstring.interpd.update(projection_names=get_projection_names())
def _stale_figure_callback(self, val):
if self.figure:
self.figure.stale = val
class AxesStack(cbook.Stack):
"""
Specialization of the `.Stack` to handle all tracking of
`~matplotlib.axes.Axes` in a `.Figure`.
This stack stores ``key, (ind, axes)`` pairs, where:
* **key** should be a hash of the args and kwargs
used in generating the Axes.
* **ind** is a serial number for tracking the order
in which axes were added.
The AxesStack is a callable, where ``ax_stack()`` returns
the current axes. Alternatively the :meth:`current_key_axes` will
return the current key and associated axes.
"""
def __init__(self):
super().__init__()
self._ind = 0
def as_list(self):
"""
Return a list of the Axes instances that have been added to the figure.
"""
ia_list = [a for k, a in self._elements]
ia_list.sort()
return [a for i, a in ia_list]
def get(self, key):
"""
Return the Axes instance that was added with *key*.
If it is not present, return *None*.
"""
item = dict(self._elements).get(key)
if item is None:
return None
cbook.warn_deprecated(
"2.1",
message="Adding an axes using the same arguments as a previous "
"axes currently reuses the earlier instance. In a future "
"version, a new instance will always be created and returned. "
"Meanwhile, this warning can be suppressed, and the future "
"behavior ensured, by passing a unique label to each axes "
"instance.")
return item[1]
def _entry_from_axes(self, e):
ind, k = {a: (ind, k) for k, (ind, a) in self._elements}[e]
return (k, (ind, e))
def remove(self, a):
"""Remove the axes from the stack."""
super().remove(self._entry_from_axes(a))
def bubble(self, a):
"""
Move the given axes, which must already exist in the
stack, to the top.
"""
return super().bubble(self._entry_from_axes(a))
def add(self, key, a):
"""
Add Axes *a*, with key *key*, to the stack, and return the stack.
If *key* is unhashable, replace it by a unique, arbitrary object.
If *a* is already on the stack, don't add it again, but
return *None*.
"""
# All the error checking may be unnecessary; but this method
# is called so seldom that the overhead is negligible.
if not isinstance(a, Axes):
raise ValueError("second argument, {!r}, is not an Axes".format(a))
try:
hash(key)
except TypeError:
key = object()
a_existing = self.get(key)
if a_existing is not None:
super().remove((key, a_existing))
cbook._warn_external(
"key {!r} already existed; Axes is being replaced".format(key))
# I don't think the above should ever happen.
if a in self:
return None
self._ind += 1
return super().push((key, (self._ind, a)))
def current_key_axes(self):
"""
Return a tuple of ``(key, axes)`` for the active axes.
If no axes exists on the stack, then returns ``(None, None)``.
"""
if not len(self._elements):
return self._default, self._default
else:
key, (index, axes) = self._elements[self._pos]
return key, axes
def __call__(self):
return self.current_key_axes()[1]
def __contains__(self, a):
return a in self.as_list()
class SubplotParams(object):
"""
A class to hold the parameters for a subplot.
"""
def __init__(self, left=None, bottom=None, right=None, top=None,
wspace=None, hspace=None):
"""
All dimensions are fractions of the figure width or height.
Defaults are given by :rc:`figure.subplot.[name]`.
Parameters
----------
left : float
The left side of the subplots of the figure.
right : float
The right side of the subplots of the figure.
bottom : float
The bottom of the subplots of the figure.
top : float
The top of the subplots of the figure.
wspace : float
The amount of width reserved for space between subplots,
expressed as a fraction of the average axis width.
hspace : float
The amount of height reserved for space between subplots,
expressed as a fraction of the average axis height.
"""
self.validate = True
self.update(left, bottom, right, top, wspace, hspace)
def update(self, left=None, bottom=None, right=None, top=None,
wspace=None, hspace=None):
"""
Update the dimensions of the passed parameters. *None* means unchanged.
"""
thisleft = getattr(self, 'left', None)
thisright = getattr(self, 'right', None)
thistop = getattr(self, 'top', None)
thisbottom = getattr(self, 'bottom', None)
thiswspace = getattr(self, 'wspace', None)
thishspace = getattr(self, 'hspace', None)
self._update_this('left', left)
self._update_this('right', right)
self._update_this('bottom', bottom)
self._update_this('top', top)
self._update_this('wspace', wspace)
self._update_this('hspace', hspace)
def reset():
self.left = thisleft
self.right = thisright
self.top = thistop
self.bottom = thisbottom
self.wspace = thiswspace
self.hspace = thishspace
if self.validate:
if self.left >= self.right:
reset()
raise ValueError('left cannot be >= right')
if self.bottom >= self.top:
reset()
raise ValueError('bottom cannot be >= top')
def _update_this(self, s, val):
if val is None:
val = getattr(self, s, None)
if val is None:
key = 'figure.subplot.' + s
val = rcParams[key]
setattr(self, s, val)
class Figure(Artist):
"""
The top level container for all the plot elements.
The Figure instance supports callbacks through a *callbacks* attribute
which is a `.CallbackRegistry` instance. The events you can connect to
are 'dpi_changed', and the callback will be called with ``func(fig)`` where
fig is the `Figure` instance.
Attributes
----------
patch
The `.Rectangle` instance representing the figure background patch.
suppressComposite
For multiple figure images, the figure will make composite images
depending on the renderer option_image_nocomposite function. If
*suppressComposite* is a boolean, this will override the renderer.
"""
def __str__(self):
return "Figure(%gx%g)" % tuple(self.bbox.size)
def __repr__(self):
return "<{clsname} size {h:g}x{w:g} with {naxes} Axes>".format(
clsname=self.__class__.__name__,
h=self.bbox.size[0], w=self.bbox.size[1],
naxes=len(self.axes),
)
def __init__(self,
figsize=None,
dpi=None,
facecolor=None,
edgecolor=None,
linewidth=0.0,
frameon=None,
subplotpars=None, # default to rc
tight_layout=None, # default to rc figure.autolayout
constrained_layout=None, # default to rc
#figure.constrained_layout.use
):
"""
Parameters
----------
figsize : 2-tuple of floats, default: :rc:`figure.figsize`
Figure dimension ``(width, height)`` in inches.
dpi : float, default: :rc:`figure.dpi`
Dots per inch.
facecolor : default: :rc:`figure.facecolor`
The figure patch facecolor.
edgecolor : default: :rc:`figure.edgecolor`
The figure patch edge color.
linewidth : float
The linewidth of the frame (i.e. the edge linewidth of the figure
patch).
frameon : bool, default: :rc:`figure.frameon`
If ``False``, suppress drawing the figure background patch.
subplotpars : :class:`SubplotParams`
Subplot parameters. If not given, the default subplot
parameters :rc:`figure.subplot.*` are used.
tight_layout : bool or dict, default: :rc:`figure.autolayout`
If ``False`` use *subplotpars*. If ``True`` adjust subplot
parameters using `.tight_layout` with default padding.
When providing a dict containing the keys ``pad``, ``w_pad``,
``h_pad``, and ``rect``, the default `.tight_layout` paddings
will be overridden.
constrained_layout : bool
If ``True`` use constrained layout to adjust positioning of plot
elements. Like ``tight_layout``, but designed to be more
flexible. See
:doc:`/tutorials/intermediate/constrainedlayout_guide`
for examples. (Note: does not work with :meth:`.subplot` or
:meth:`.subplot2grid`.)
Defaults to :rc:`figure.constrained_layout.use`.
"""
super().__init__()
# remove the non-figure artist _axes property
# as it makes no sense for a figure to be _in_ an axes
# this is used by the property methods in the artist base class
# which are over-ridden in this class
del self._axes
self.callbacks = cbook.CallbackRegistry()
if figsize is None:
figsize = rcParams['figure.figsize']
if dpi is None:
dpi = rcParams['figure.dpi']
if facecolor is None:
facecolor = rcParams['figure.facecolor']
if edgecolor is None:
edgecolor = rcParams['figure.edgecolor']
if frameon is None:
frameon = rcParams['figure.frameon']
if not np.isfinite(figsize).all() or (np.array(figsize) <= 0).any():
raise ValueError('figure size must be positive finite not '
f'{figsize}')
self.bbox_inches = Bbox.from_bounds(0, 0, *figsize)
self.dpi_scale_trans = Affine2D().scale(dpi, dpi)
# do not use property as it will trigger
self._dpi = dpi
self.bbox = TransformedBbox(self.bbox_inches, self.dpi_scale_trans)
self.transFigure = BboxTransformTo(self.bbox)
self.patch = Rectangle(
xy=(0, 0), width=1, height=1,
facecolor=facecolor, edgecolor=edgecolor, linewidth=linewidth,
visible=frameon)
self._set_artist_props(self.patch)
self.patch.set_antialiased(False)
FigureCanvasBase(self) # Set self.canvas.
self._suptitle = None
if subplotpars is None:
subplotpars = SubplotParams()
self.subplotpars = subplotpars
# constrained_layout:
self._layoutbox = None
# set in set_constrained_layout_pads()
self.set_constrained_layout(constrained_layout)
self.set_tight_layout(tight_layout)
self._axstack = AxesStack() # track all figure axes and current axes
self.clf()
self._cachedRenderer = None
# groupers to keep track of x and y labels we want to align.
# see self.align_xlabels and self.align_ylabels and
# axis._get_tick_boxes_siblings
self._align_xlabel_grp = cbook.Grouper()
self._align_ylabel_grp = cbook.Grouper()
# list of child gridspecs for this figure
self._gridspecs = []
# TODO: I'd like to dynamically add the _repr_html_ method
# to the figure in the right context, but then IPython doesn't
# use it, for some reason.
def _repr_html_(self):
# We can't use "isinstance" here, because then we'd end up importing
# webagg unconditionally.
if 'WebAgg' in type(self.canvas).__name__:
from matplotlib.backends import backend_webagg
return backend_webagg.ipython_inline_display(self)
def show(self, warn=True):
"""
If using a GUI backend with pyplot, display the figure window.
If the figure was not created using
:func:`~matplotlib.pyplot.figure`, it will lack a
:class:`~matplotlib.backend_bases.FigureManagerBase`, and
will raise an AttributeError.
.. warning::
This does not manage an GUI event loop. Consequently, the figure
may only be shown briefly or not shown at all if you or your
environment are not managing an event loop.
Proper use cases for `.Figure.show` include running this from a
GUI application or an IPython shell.
If you're running a pure python shell or executing a non-GUI
python script, you should use `matplotlib.pyplot.show` instead,
which takes care of managing the event loop for you.
Parameters
----------
warn : bool
If ``True`` and we are not running headless (i.e. on Linux with an
unset DISPLAY), issue warning when called on a non-GUI backend.
"""
try:
manager = getattr(self.canvas, 'manager')
except AttributeError as err:
raise AttributeError("%s\n"
"Figure.show works only "
"for figures managed by pyplot, normally "
"created by pyplot.figure()." % err)
if manager is not None:
try:
manager.show()
return
except NonGuiException:
pass
if (backends._get_running_interactive_framework() != "headless"
and warn):
cbook._warn_external('Matplotlib is currently using %s, which is '
'a non-GUI backend, so cannot show the '
'figure.' % get_backend())
def _get_axes(self):
return self._axstack.as_list()
axes = property(fget=_get_axes,
doc="List of axes in the Figure. You can access the "
"axes in the Figure through this list. "
"Do not modify the list itself. Instead, use "
"`~Figure.add_axes`, `~.Figure.subplot` or "
"`~.Figure.delaxes` to add or remove an axes.")
def _get_dpi(self):
return self._dpi
def _set_dpi(self, dpi, forward=True):
"""
Parameters
----------
dpi : float
forward : bool
Passed on to `~.Figure.set_size_inches`
"""
self._dpi = dpi
self.dpi_scale_trans.clear().scale(dpi, dpi)
w, h = self.get_size_inches()
self.set_size_inches(w, h, forward=forward)
self.callbacks.process('dpi_changed', self)
dpi = property(_get_dpi, _set_dpi, doc="The resolution in dots per inch.")
def get_tight_layout(self):
"""Return whether `.tight_layout` is called when drawing."""
return self._tight
def set_tight_layout(self, tight):
"""
Set whether and how `.tight_layout` is called when drawing.
Parameters
----------
tight : bool or dict with keys "pad", "w_pad", "h_pad", "rect" or None
If a bool, sets whether to call `.tight_layout` upon drawing.
If ``None``, use the ``figure.autolayout`` rcparam instead.
If a dict, pass it as kwargs to `.tight_layout`, overriding the
default paddings.
"""
if tight is None:
tight = rcParams['figure.autolayout']
self._tight = bool(tight)
self._tight_parameters = tight if isinstance(tight, dict) else {}
self.stale = True
def get_constrained_layout(self):
"""
Return a boolean: True means constrained layout is being used.
See :doc:`/tutorials/intermediate/constrainedlayout_guide`.
"""
return self._constrained
def set_constrained_layout(self, constrained):
"""
Set whether ``constrained_layout`` is used upon drawing. If None,
the rcParams['figure.constrained_layout.use'] value will be used.
When providing a dict containing the keys `w_pad`, `h_pad`
the default ``constrained_layout`` paddings will be
overridden. These pads are in inches and default to 3.0/72.0.
``w_pad`` is the width padding and ``h_pad`` is the height padding.
See :doc:`/tutorials/intermediate/constrainedlayout_guide`.
Parameters
----------
constrained : bool or dict or None
"""
self._constrained_layout_pads = dict()
self._constrained_layout_pads['w_pad'] = None
self._constrained_layout_pads['h_pad'] = None
self._constrained_layout_pads['wspace'] = None
self._constrained_layout_pads['hspace'] = None
if constrained is None:
constrained = rcParams['figure.constrained_layout.use']
self._constrained = bool(constrained)
if isinstance(constrained, dict):
self.set_constrained_layout_pads(**constrained)
else:
self.set_constrained_layout_pads()
self.stale = True
def set_constrained_layout_pads(self, **kwargs):
"""
Set padding for ``constrained_layout``. Note the kwargs can be passed
as a dictionary ``fig.set_constrained_layout(**paddict)``.
See :doc:`/tutorials/intermediate/constrainedlayout_guide`.
Parameters
----------
w_pad : scalar
Width padding in inches. This is the pad around axes
and is meant to make sure there is enough room for fonts to
look good. Defaults to 3 pts = 0.04167 inches
h_pad : scalar
Height padding in inches. Defaults to 3 pts.
wspace : scalar
Width padding between subplots, expressed as a fraction of the
subplot width. The total padding ends up being w_pad + wspace.
hspace : scalar
Height padding between subplots, expressed as a fraction of the
subplot width. The total padding ends up being h_pad + hspace.
"""
todo = ['w_pad', 'h_pad', 'wspace', 'hspace']
for td in todo:
if td in kwargs and kwargs[td] is not None:
self._constrained_layout_pads[td] = kwargs[td]
else:
self._constrained_layout_pads[td] = (
rcParams['figure.constrained_layout.' + td])
def get_constrained_layout_pads(self, relative=False):
"""
Get padding for ``constrained_layout``.
Returns a list of `w_pad, h_pad` in inches and
`wspace` and `hspace` as fractions of the subplot.
See :doc:`/tutorials/intermediate/constrainedlayout_guide`.
Parameters
----------
relative : boolean
If `True`, then convert from inches to figure relative.
"""
w_pad = self._constrained_layout_pads['w_pad']
h_pad = self._constrained_layout_pads['h_pad']
wspace = self._constrained_layout_pads['wspace']
hspace = self._constrained_layout_pads['hspace']
if relative and (w_pad is not None or h_pad is not None):
renderer0 = layoutbox.get_renderer(self)
dpi = renderer0.dpi
w_pad = w_pad * dpi / renderer0.width
h_pad = h_pad * dpi / renderer0.height
return w_pad, h_pad, wspace, hspace
def autofmt_xdate(self, bottom=0.2, rotation=30, ha='right', which=None):
"""
Date ticklabels often overlap, so it is useful to rotate them
and right align them. Also, a common use case is a number of
subplots with shared xaxes where the x-axis is date data. The
ticklabels are often long, and it helps to rotate them on the
bottom subplot and turn them off on other subplots, as well as
turn off xlabels.
Parameters
----------
bottom : scalar
The bottom of the subplots for :meth:`subplots_adjust`.
rotation : angle in degrees
The rotation of the xtick labels.
ha : string
The horizontal alignment of the xticklabels.
which : {None, 'major', 'minor', 'both'}
Selects which ticklabels to rotate. Default is None which works
the same as major.
"""
allsubplots = all(hasattr(ax, 'is_last_row') for ax in self.axes)
if len(self.axes) == 1:
for label in self.axes[0].get_xticklabels(which=which):
label.set_ha(ha)
label.set_rotation(rotation)
else:
if allsubplots:
for ax in self.get_axes():
if ax.is_last_row():
for label in ax.get_xticklabels(which=which):
label.set_ha(ha)
label.set_rotation(rotation)
else:
for label in ax.get_xticklabels(which=which):
label.set_visible(False)
ax.set_xlabel('')
if allsubplots:
self.subplots_adjust(bottom=bottom)
self.stale = True
def get_children(self):
"""Get a list of artists contained in the figure."""
return [self.patch,
*self.artists,
*self.axes,
*self.lines,
*self.patches,
*self.texts,
*self.images,
*self.legends]
def contains(self, mouseevent):
"""
Test whether the mouse event occurred on the figure.
Returns
-------
bool, {}
"""
if self._contains is not None:
return self._contains(self, mouseevent)
inside = self.bbox.contains(mouseevent.x, mouseevent.y)
return inside, {}
def get_window_extent(self, *args, **kwargs):
"""
Return the figure bounding box in display space. Arguments are ignored.
"""
return self.bbox
def suptitle(self, t, **kwargs):
"""
Add a centered title to the figure.
Parameters
----------
t : str
The title text.
x : float, default 0.5
The x location of the text in figure coordinates.
y : float, default 0.98
The y location of the text in figure coordinates.
horizontalalignment, ha : {'center', 'left', right'}, default: 'center'
The horizontal alignment of the text relative to (*x*, *y*).
verticalalignment, va : {'top', 'center', 'bottom', 'baseline'}, \
default: 'top'
The vertical alignment of the text relative to (*x*, *y*).
fontsize, size : default: :rc:`figure.titlesize`
The font size of the text. See `.Text.set_size` for possible
values.
fontweight, weight : default: :rc:`figure.titleweight`
The font weight of the text. See `.Text.set_weight` for possible
values.
Returns
-------
text
The `.Text` instance of the title.
Other Parameters
----------------
fontproperties : None or dict, optional
A dict of font properties. If *fontproperties* is given the
default values for font size and weight are taken from the
`FontProperties` defaults. :rc:`figure.titlesize` and
:rc:`figure.titleweight` are ignored in this case.
**kwargs
Additional kwargs are :class:`matplotlib.text.Text` properties.
Examples
--------
>>> fig.suptitle('This is the figure title', fontsize=12)
"""
manual_position = ('x' in kwargs or 'y' in kwargs)
x = kwargs.pop('x', 0.5)
y = kwargs.pop('y', 0.98)
if 'horizontalalignment' not in kwargs and 'ha' not in kwargs:
kwargs['horizontalalignment'] = 'center'
if 'verticalalignment' not in kwargs and 'va' not in kwargs:
kwargs['verticalalignment'] = 'top'
if 'fontproperties' not in kwargs:
if 'fontsize' not in kwargs and 'size' not in kwargs:
kwargs['size'] = rcParams['figure.titlesize']
if 'fontweight' not in kwargs and 'weight' not in kwargs:
kwargs['weight'] = rcParams['figure.titleweight']
sup = self.text(x, y, t, **kwargs)
if self._suptitle is not None:
self._suptitle.set_text(t)
self._suptitle.set_position((x, y))
self._suptitle.update_from(sup)
sup.remove()
else:
self._suptitle = sup
self._suptitle._layoutbox = None
if self._layoutbox is not None and not manual_position:
w_pad, h_pad, wspace, hspace = \
self.get_constrained_layout_pads(relative=True)
figlb = self._layoutbox
self._suptitle._layoutbox = layoutbox.LayoutBox(
parent=figlb, artist=self._suptitle,
name=figlb.name+'.suptitle')
# stack the suptitle on top of all the children.
# Some day this should be on top of all the children in the
# gridspec only.
for child in figlb.children:
if child is not self._suptitle._layoutbox:
layoutbox.vstack([self._suptitle._layoutbox,
child],
padding=h_pad*2., strength='required')
self.stale = True
return self._suptitle
def set_canvas(self, canvas):
"""
Set the canvas that contains the figure
Parameters
----------
canvas : FigureCanvas
"""
self.canvas = canvas
def figimage(self, X, xo=0, yo=0, alpha=None, norm=None, cmap=None,
vmin=None, vmax=None, origin=None, resize=False, **kwargs):
"""
Add a non-resampled image to the figure.
The image is attached to the lower or upper left corner depending on
*origin*.
Parameters
----------
X
The image data. This is an array of one of the following shapes:
- MxN: luminance (grayscale) values
- MxNx3: RGB values
- MxNx4: RGBA values
xo, yo : int
The *x*/*y* image offset in pixels.
alpha : None or float
The alpha blending value.
norm : :class:`matplotlib.colors.Normalize`
A :class:`.Normalize` instance to map the luminance to the
interval [0, 1].
cmap : str or :class:`matplotlib.colors.Colormap`
The colormap to use. Default: :rc:`image.cmap`.
vmin, vmax : scalar
If *norm* is not given, these values set the data limits for the
colormap.
origin : {'upper', 'lower'}
Indicates where the [0, 0] index of the array is in the upper left
or lower left corner of the axes. Defaults to :rc:`image.origin`.
resize : bool
If *True*, resize the figure to match the given image size.
Returns
-------
:class:`matplotlib.image.FigureImage`
Other Parameters
----------------
**kwargs
Additional kwargs are `.Artist` kwargs passed on to `.FigureImage`.
Notes
-----
figimage complements the axes image
(:meth:`~matplotlib.axes.Axes.imshow`) which will be resampled
to fit the current axes. If you want a resampled image to
fill the entire figure, you can define an
:class:`~matplotlib.axes.Axes` with extent [0,0,1,1].
Examples::
f = plt.figure()
nx = int(f.get_figwidth() * f.dpi)
ny = int(f.get_figheight() * f.dpi)
data = np.random.random((ny, nx))
f.figimage(data)
plt.show()
"""
if resize:
dpi = self.get_dpi()
figsize = [x / dpi for x in (X.shape[1], X.shape[0])]
self.set_size_inches(figsize, forward=True)
im = mimage.FigureImage(self, cmap, norm, xo, yo, origin, **kwargs)
im.stale_callback = _stale_figure_callback
im.set_array(X)
im.set_alpha(alpha)
if norm is None:
im.set_clim(vmin, vmax)
self.images.append(im)
im._remove_method = self.images.remove
self.stale = True
return im
def set_size_inches(self, w, h=None, forward=True):
"""Set the figure size in inches.
Call signatures::
fig.set_size_inches(w, h) # OR
fig.set_size_inches((w, h))
optional kwarg *forward=True* will cause the canvas size to be
automatically updated; e.g., you can resize the figure window
from the shell
ACCEPTS: a (w, h) tuple with w, h in inches
See Also
--------
matplotlib.Figure.get_size_inches
"""
if h is None: # Got called with a single pair as argument.
w, h = w
size = np.array([w, h])
if not np.isfinite(size).all() or (size <= 0).any():
raise ValueError(f'figure size must be positive finite not {size}')
self.bbox_inches.p1 = size
if forward:
canvas = getattr(self, 'canvas')
if canvas is not None:
dpi_ratio = getattr(canvas, '_dpi_ratio', 1)
manager = getattr(canvas, 'manager', None)
if manager is not None:
manager.resize(*(size * self.dpi / dpi_ratio).astype(int))
self.stale = True
def get_size_inches(self):
"""
Returns the current size of the figure in inches.
Returns
-------
size : ndarray
The size (width, height) of the figure in inches.
See Also
--------
matplotlib.Figure.set_size_inches
"""
return np.array(self.bbox_inches.p1)
def get_edgecolor(self):
"""Get the edge color of the Figure rectangle."""
return self.patch.get_edgecolor()
def get_facecolor(self):
"""Get the face color of the Figure rectangle."""
return self.patch.get_facecolor()
def get_figwidth(self):
"""Return the figure width as a float."""
return self.bbox_inches.width
def get_figheight(self):
"""Return the figure height as a float."""
return self.bbox_inches.height
def get_dpi(self):
"""Return the resolution in dots per inch as a float."""
return self.dpi
def get_frameon(self):
"""
Return the figure's background patch visibility, i.e.
whether the figure background will be drawn. Equivalent to
``Figure.patch.get_visible()``.
"""
return self.patch.get_visible()
def set_edgecolor(self, color):
"""
Set the edge color of the Figure rectangle.
Parameters
----------
color : color
"""
self.patch.set_edgecolor(color)
def set_facecolor(self, color):
"""
Set the face color of the Figure rectangle.
Parameters
----------
color : color
"""
self.patch.set_facecolor(color)
def set_dpi(self, val):
"""
Set the resolution of the figure in dots-per-inch.
Parameters
----------
val : float
"""
self.dpi = val
self.stale = True
def set_figwidth(self, val, forward=True):
"""
Set the width of the figure in inches.
Parameters
----------
val : float
forward : bool
"""
self.set_size_inches(val, self.get_figheight(), forward=forward)
def set_figheight(self, val, forward=True):
"""
Set the height of the figure in inches.
Parameters
----------
val : float
forward : bool
"""
self.set_size_inches(self.get_figwidth(), val, forward=forward)
def set_frameon(self, b):
"""
Set the figure's background patch visibility, i.e.
whether the figure background will be drawn. Equivalent to
``Figure.patch.set_visible()``.
Parameters
----------
b : bool
"""
self.patch.set_visible(b)
self.stale = True
frameon = property(get_frameon, set_frameon)
def delaxes(self, ax):
"""
Remove the `~matplotlib.axes.Axes` *ax* from the figure and update the
current axes.
"""
self._axstack.remove(ax)
for func in self._axobservers:
func(self)
self.stale = True
def add_artist(self, artist, clip=False):
"""
Add any :class:`~matplotlib.artist.Artist` to the figure.
Usually artists are added to axes objects using
:meth:`matplotlib.axes.Axes.add_artist`, but use this method in the
rare cases that adding directly to the figure is necessary.
Parameters
----------
artist : `~matplotlib.artist.Artist`
The artist to add to the figure. If the added artist has no
transform previously set, its transform will be set to
``figure.transFigure``.
clip : bool, optional, default ``False``
An optional parameter ``clip`` determines whether the added artist
should be clipped by the figure patch. Default is *False*,
i.e. no clipping.
Returns
-------
artist : The added `~matplotlib.artist.Artist`
"""
artist.set_figure(self)
self.artists.append(artist)
artist._remove_method = self.artists.remove
if not artist.is_transform_set():
artist.set_transform(self.transFigure)
if clip:
artist.set_clip_path(self.patch)
self.stale = True
return artist
def _make_key(self, *args, **kwargs):
"""Make a hashable key out of args and kwargs."""
def fixitems(items):
# items may have arrays and lists in them, so convert them
# to tuples for the key
ret = []
for k, v in items:
# some objects can define __getitem__ without being
# iterable and in those cases the conversion to tuples
# will fail. So instead of using the np.iterable(v) function
# we simply try and convert to a tuple, and proceed if not.
try:
v = tuple(v)
except Exception:
pass
ret.append((k, v))
return tuple(ret)
def fixlist(args):
ret = []
for a in args:
if np.iterable(a):
a = tuple(a)
ret.append(a)
return tuple(ret)
key = fixlist(args), fixitems(kwargs.items())
return key
def _process_projection_requirements(
self, *args, polar=False, projection=None, **kwargs):
"""
Handle the args/kwargs to add_axes/add_subplot/gca, returning::
(axes_proj_class, proj_class_kwargs, proj_stack_key)
which can be used for new axes initialization/identification.
"""
if polar:
if projection is not None and projection != 'polar':
raise ValueError(
"polar=True, yet projection=%r. "
"Only one of these arguments should be supplied." %
projection)
projection = 'polar'
if isinstance(projection, str) or projection is None:
projection_class = projections.get_projection_class(projection)
elif hasattr(projection, '_as_mpl_axes'):
projection_class, extra_kwargs = projection._as_mpl_axes()
kwargs.update(**extra_kwargs)
else:
raise TypeError('projection must be a string, None or implement a '
'_as_mpl_axes method. Got %r' % projection)
# Make the key without projection kwargs, this is used as a unique
# lookup for axes instances
key = self._make_key(*args, **kwargs)
return projection_class, kwargs, key
@docstring.dedent_interpd
def add_axes(self, *args, **kwargs):
"""
Add an axes to the figure.
Call signatures::
add_axes(rect, projection=None, polar=False, **kwargs)
add_axes(ax)
Parameters
----------
rect : sequence of float
The dimensions [left, bottom, width, height] of the new axes. All
quantities are in fractions of figure width and height.
projection : {None, 'aitoff', 'hammer', 'lambert', 'mollweide', \
'polar', 'rectilinear', str}, optional
The projection type of the `~.axes.Axes`. *str* is the name of
a custom projection, see `~matplotlib.projections`. The default
None results in a 'rectilinear' projection.
polar : boolean, optional
If True, equivalent to projection='polar'.
sharex, sharey : `~.axes.Axes`, optional
Share the x or y `~matplotlib.axis` with sharex and/or sharey.
The axis will have the same limits, ticks, and scale as the axis
of the shared axes.
label : str
A label for the returned axes.
Other Parameters
----------------
**kwargs
This method also takes the keyword arguments for
the returned axes class. The keyword arguments for the
rectilinear axes class `~.axes.Axes` can be found in
the following table but there might also be other keyword
arguments if another projection is used, see the actual axes
class.
%(Axes)s
Returns
-------
axes : `~.axes.Axes` (or a subclass of `~.axes.Axes`)
The returned axes class depends on the projection used. It is
`~.axes.Axes` if rectilinear projection are used and
`.projections.polar.PolarAxes` if polar projection
are used.
Notes
-----
If the figure already has an axes with key (*args*,
*kwargs*) then it will simply make that axes current and
return it. This behavior is deprecated. Meanwhile, if you do
not want this behavior (i.e., you want to force the creation of a
new axes), you must use a unique set of args and kwargs. The axes
*label* attribute has been exposed for this purpose: if you want
two axes that are otherwise identical to be added to the figure,
make sure you give them unique labels.
In rare circumstances, `.add_axes` may be called with a single
argument, a axes instance already created in the present figure but
not in the figure's list of axes.
See Also
--------
.Figure.add_subplot
.pyplot.subplot
.pyplot.axes
.Figure.subplots
.pyplot.subplots
Examples
--------
Some simple examples::
rect = l, b, w, h
fig = plt.figure()
fig.add_axes(rect,label=label1)
fig.add_axes(rect,label=label2)
fig.add_axes(rect, frameon=False, facecolor='g')
fig.add_axes(rect, polar=True)
ax=fig.add_axes(rect, projection='polar')
fig.delaxes(ax)
fig.add_axes(ax)
"""
if not len(args):
return
# shortcut the projection "key" modifications later on, if an axes
# with the exact args/kwargs exists, return it immediately.
key = self._make_key(*args, **kwargs)
ax = self._axstack.get(key)
if ax is not None:
self.sca(ax)
return ax
if isinstance(args[0], Axes):
a = args[0]
if a.get_figure() is not self:
raise ValueError(
"The Axes must have been created in the present figure")
else:
rect = args[0]
if not np.isfinite(rect).all():
raise ValueError('all entries in rect must be finite '
'not {}'.format(rect))
projection_class, kwargs, key = \
self._process_projection_requirements(*args, **kwargs)
# check that an axes of this type doesn't already exist, if it
# does, set it as active and return it
ax = self._axstack.get(key)
if isinstance(ax, projection_class):
self.sca(ax)
return ax
# create the new axes using the axes class given
a = projection_class(self, rect, **kwargs)
return self._add_axes_internal(key, a)
@docstring.dedent_interpd
def add_subplot(self, *args, **kwargs):
"""
Add an `~.axes.Axes` to the figure as part of a subplot arrangement.
Call signatures::
add_subplot(nrows, ncols, index, **kwargs)
add_subplot(pos, **kwargs)
add_subplot(ax)
add_subplot()
Parameters
----------
*args
Either a 3-digit integer or three separate integers
describing the position of the subplot. If the three
integers are *nrows*, *ncols*, and *index* in order, the
subplot will take the *index* position on a grid with *nrows*
rows and *ncols* columns. *index* starts at 1 in the upper left
corner and increases to the right.
*pos* is a three digit integer, where the first digit is the
number of rows, the second the number of columns, and the third
the index of the subplot. i.e. fig.add_subplot(235) is the same as
fig.add_subplot(2, 3, 5). Note that all integers must be less than
10 for this form to work.
If no positional arguments are passed, defaults to (1, 1, 1).
projection : {None, 'aitoff', 'hammer', 'lambert', 'mollweide', \
'polar', 'rectilinear', str}, optional
The projection type of the subplot (`~.axes.Axes`). *str* is the
name of a custom projection, see `~matplotlib.projections`. The
default None results in a 'rectilinear' projection.
polar : boolean, optional
If True, equivalent to projection='polar'.
sharex, sharey : `~.axes.Axes`, optional
Share the x or y `~matplotlib.axis` with sharex and/or sharey.
The axis will have the same limits, ticks, and scale as the axis
of the shared axes.
label : str
A label for the returned axes.
Other Parameters
----------------
**kwargs
This method also takes the keyword arguments for
the returned axes base class. The keyword arguments for the
rectilinear base class `~.axes.Axes` can be found in
the following table but there might also be other keyword
arguments if another projection is used.
%(Axes)s
Returns
-------
axes : an `.axes.SubplotBase` subclass of `~.axes.Axes` (or a \
subclass of `~.axes.Axes`)
The axes of the subplot. The returned axes base class depends on
the projection used. It is `~.axes.Axes` if rectilinear projection
are used and `.projections.polar.PolarAxes` if polar projection
are used. The returned axes is then a subplot subclass of the
base class.
Notes
-----
If the figure already has a subplot with key (*args*,
*kwargs*) then it will simply make that subplot current and
return it. This behavior is deprecated. Meanwhile, if you do
not want this behavior (i.e., you want to force the creation of a
new subplot), you must use a unique set of args and kwargs. The axes
*label* attribute has been exposed for this purpose: if you want
two subplots that are otherwise identical to be added to the figure,
make sure you give them unique labels.
In rare circumstances, `.add_subplot` may be called with a single
argument, a subplot axes instance already created in the
present figure but not in the figure's list of axes.
See Also
--------
.Figure.add_axes
.pyplot.subplot
.pyplot.axes
.Figure.subplots
.pyplot.subplots
Examples
--------
::
fig = plt.figure()
fig.add_subplot(221)
# equivalent but more general
ax1 = fig.add_subplot(2, 2, 1)
# add a subplot with no frame
ax2 = fig.add_subplot(222, frameon=False)
# add a polar subplot
fig.add_subplot(223, projection='polar')
# add a red subplot that share the x-axis with ax1
fig.add_subplot(224, sharex=ax1, facecolor='red')
#delete x2 from the figure
fig.delaxes(ax2)
#add x2 to the figure again
fig.add_subplot(ax2)
"""
if not len(args):
args = (1, 1, 1)
if len(args) == 1 and isinstance(args[0], Integral):
if not 100 <= args[0] <= 999:
raise ValueError("Integer subplot specification must be a "
"three-digit number, not {}".format(args[0]))
args = tuple(map(int, str(args[0])))
if isinstance(args[0], SubplotBase):
a = args[0]
if a.get_figure() is not self:
raise ValueError(
"The Subplot must have been created in the present figure")
# make a key for the subplot (which includes the axes object id
# in the hash)
key = self._make_key(*args, **kwargs)
else:
projection_class, kwargs, key = \
self._process_projection_requirements(*args, **kwargs)
# try to find the axes with this key in the stack
ax = self._axstack.get(key)
if ax is not None:
if isinstance(ax, projection_class):
# the axes already existed, so set it as active & return
self.sca(ax)
return ax
else:
# Undocumented convenience behavior:
# subplot(111); subplot(111, projection='polar')
# will replace the first with the second.
# Without this, add_subplot would be simpler and
# more similar to add_axes.
self._axstack.remove(ax)
a = subplot_class_factory(projection_class)(self, *args, **kwargs)
return self._add_axes_internal(key, a)
def _add_axes_internal(self, key, ax):
"""Private helper for `add_axes` and `add_subplot`."""
self._axstack.add(key, ax)
self.sca(ax)
ax._remove_method = self._remove_ax
self.stale = True
ax.stale_callback = _stale_figure_callback
return ax
def subplots(self, nrows=1, ncols=1, sharex=False, sharey=False,
squeeze=True, subplot_kw=None, gridspec_kw=None):
"""
Add a set of subplots to this figure.
This utility wrapper makes it convenient to create common layouts of
subplots in a single call.
Parameters
----------
nrows, ncols : int, optional, default: 1
Number of rows/columns of the subplot grid.
sharex, sharey : bool or {'none', 'all', 'row', 'col'}, default: False
Controls sharing of properties among x (`sharex`) or y (`sharey`)
axes:
- True or 'all': x- or y-axis will be shared among all
subplots.
- False or 'none': each subplot x- or y-axis will be
independent.
- 'row': each subplot row will share an x- or y-axis.
- 'col': each subplot column will share an x- or y-axis.
When subplots have a shared x-axis along a column, only the x tick
labels of the bottom subplot are created. Similarly, when subplots
have a shared y-axis along a row, only the y tick labels of the
first column subplot are created. To later turn other subplots'
ticklabels on, use `~matplotlib.axes.Axes.tick_params`.
squeeze : bool, optional, default: True
- If True, extra dimensions are squeezed out from the returned
array of Axes:
- if only one subplot is constructed (nrows=ncols=1), the
resulting single Axes object is returned as a scalar.
- for Nx1 or 1xM subplots, the returned object is a 1D numpy
object array of Axes objects.
- for NxM, subplots with N>1 and M>1 are returned
as a 2D array.
- If False, no squeezing at all is done: the returned Axes object
is always a 2D array containing Axes instances, even if it ends
up being 1x1.
subplot_kw : dict, optional
Dict with keywords passed to the
:meth:`~matplotlib.figure.Figure.add_subplot` call used to create
each subplot.
gridspec_kw : dict, optional
Dict with keywords passed to the
`~matplotlib.gridspec.GridSpec` constructor used to create
the grid the subplots are placed on.
Returns
-------
ax : `~.axes.Axes` object or array of Axes objects.
*ax* can be either a single `~matplotlib.axes.Axes` object or
an array of Axes objects if more than one subplot was created. The
dimensions of the resulting array can be controlled with the
squeeze keyword, see above.
Examples
--------
::
# First create some toy data:
x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)
# Create a figure
plt.figure()
# Creates a subplot
ax = fig.subplots()
ax.plot(x, y)
ax.set_title('Simple plot')
# Creates two subplots and unpacks the output array immediately
ax1, ax2 = fig.subplots(1, 2, sharey=True)
ax1.plot(x, y)
ax1.set_title('Sharing Y axis')
ax2.scatter(x, y)
# Creates four polar axes, and accesses them through the
# returned array
axes = fig.subplots(2, 2, subplot_kw=dict(polar=True))
axes[0, 0].plot(x, y)
axes[1, 1].scatter(x, y)
# Share a X axis with each column of subplots
fig.subplots(2, 2, sharex='col')
# Share a Y axis with each row of subplots
fig.subplots(2, 2, sharey='row')
# Share both X and Y axes with all subplots
fig.subplots(2, 2, sharex='all', sharey='all')
# Note that this is the same as
fig.subplots(2, 2, sharex=True, sharey=True)
See Also
--------
.pyplot.subplots
.Figure.add_subplot
.pyplot.subplot
"""
if isinstance(sharex, bool):
sharex = "all" if sharex else "none"
if isinstance(sharey, bool):
sharey = "all" if sharey else "none"
# This check was added because it is very easy to type
# `subplots(1, 2, 1)` when `subplot(1, 2, 1)` was intended.
# In most cases, no error will ever occur, but mysterious behavior
# will result because what was intended to be the subplot index is
# instead treated as a bool for sharex.
if isinstance(sharex, Integral):
cbook._warn_external(
"sharex argument to subplots() was an integer. Did you "
"intend to use subplot() (without 's')?")
cbook._check_in_list(["all", "row", "col", "none"],
sharex=sharex, sharey=sharey)
if subplot_kw is None:
subplot_kw = {}
if gridspec_kw is None:
gridspec_kw = {}
# don't mutate kwargs passed by user...
subplot_kw = subplot_kw.copy()
gridspec_kw = gridspec_kw.copy()
if self.get_constrained_layout():
gs = GridSpec(nrows, ncols, figure=self, **gridspec_kw)
else:
# this should turn constrained_layout off if we don't want it
gs = GridSpec(nrows, ncols, figure=None, **gridspec_kw)
self._gridspecs.append(gs)
# Create array to hold all axes.
axarr = np.empty((nrows, ncols), dtype=object)
for row in range(nrows):
for col in range(ncols):
shared_with = {"none": None, "all": axarr[0, 0],
"row": axarr[row, 0], "col": axarr[0, col]}
subplot_kw["sharex"] = shared_with[sharex]
subplot_kw["sharey"] = shared_with[sharey]
axarr[row, col] = self.add_subplot(gs[row, col], **subplot_kw)
# turn off redundant tick labeling
if sharex in ["col", "all"]:
# turn off all but the bottom row
for ax in axarr[:-1, :].flat:
ax.xaxis.set_tick_params(which='both',
labelbottom=False, labeltop=False)
ax.xaxis.offsetText.set_visible(False)
if sharey in ["row", "all"]:
# turn off all but the first column
for ax in axarr[:, 1:].flat:
ax.yaxis.set_tick_params(which='both',
labelleft=False, labelright=False)
ax.yaxis.offsetText.set_visible(False)
if squeeze:
# Discarding unneeded dimensions that equal 1. If we only have one
# subplot, just return it instead of a 1-element array.
return axarr.item() if axarr.size == 1 else axarr.squeeze()
else:
# Returned axis array will be always 2-d, even if nrows=ncols=1.
return axarr
def _remove_ax(self, ax):
def _reset_loc_form(axis):
axis.set_major_formatter(axis.get_major_formatter())
axis.set_major_locator(axis.get_major_locator())
axis.set_minor_formatter(axis.get_minor_formatter())
axis.set_minor_locator(axis.get_minor_locator())
def _break_share_link(ax, grouper):
siblings = grouper.get_siblings(ax)
if len(siblings) > 1:
grouper.remove(ax)
for last_ax in siblings:
if ax is not last_ax:
return last_ax
return None
self.delaxes(ax)
last_ax = _break_share_link(ax, ax._shared_y_axes)
if last_ax is not None:
_reset_loc_form(last_ax.yaxis)
last_ax = _break_share_link(ax, ax._shared_x_axes)
if last_ax is not None:
_reset_loc_form(last_ax.xaxis)
def clf(self, keep_observers=False):
"""
Clear the figure.
Set *keep_observers* to True if, for example,
a gui widget is tracking the axes in the figure.
"""
self.suppressComposite = None
self.callbacks = cbook.CallbackRegistry()
for ax in tuple(self.axes): # Iterate over the copy.
ax.cla()
self.delaxes(ax) # removes ax from self._axstack
toolbar = getattr(self.canvas, 'toolbar', None)
if toolbar is not None:
toolbar.update()
self._axstack.clear()
self.artists = []
self.lines = []
self.patches = []
self.texts = []
self.images = []
self.legends = []
if not keep_observers:
self._axobservers = []
self._suptitle = None
if self.get_constrained_layout():
layoutbox.nonetree(self._layoutbox)
self.stale = True
def clear(self, keep_observers=False):
"""
Clear the figure -- synonym for :meth:`clf`.
"""
self.clf(keep_observers=keep_observers)
@allow_rasterization
def draw(self, renderer):
"""
Render the figure using :class:`matplotlib.backend_bases.RendererBase`
instance *renderer*.
"""
# draw the figure bounding box, perhaps none for white figure
if not self.get_visible():
return
artists = self.get_children()
artists.remove(self.patch)
artists = sorted(
(artist for artist in artists if not artist.get_animated()),
key=lambda artist: artist.get_zorder())
for ax in self.axes:
locator = ax.get_axes_locator()
if locator:
pos = locator(ax, renderer)
ax.apply_aspect(pos)
else:
ax.apply_aspect()
for child in ax.get_children():
if hasattr(child, 'apply_aspect'):
locator = child.get_axes_locator()
if locator:
pos = locator(child, renderer)
child.apply_aspect(pos)
else:
child.apply_aspect()
try:
renderer.open_group('figure')
if self.get_constrained_layout() and self.axes:
self.execute_constrained_layout(renderer)
if self.get_tight_layout() and self.axes:
try:
self.tight_layout(renderer,
**self._tight_parameters)
except ValueError:
pass
# ValueError can occur when resizing a window.
self.patch.draw(renderer)
mimage._draw_list_compositing_images(
renderer, self, artists, self.suppressComposite)
renderer.close_group('figure')
finally:
self.stale = False
self._cachedRenderer = renderer
self.canvas.draw_event(renderer)
def draw_artist(self, a):
"""
Draw :class:`matplotlib.artist.Artist` instance *a* only.
This is available only after the figure is drawn.
"""
if self._cachedRenderer is None:
raise AttributeError("draw_artist can only be used after an "
"initial draw which caches the renderer")
a.draw(self._cachedRenderer)
def get_axes(self):
"""
Return a list of axes in the Figure. You can access and modify the
axes in the Figure through this list.
Do not modify the list itself. Instead, use `~Figure.add_axes`,
`~.Figure.subplot` or `~.Figure.delaxes` to add or remove an axes.
Note: This is equivalent to the property `~.Figure.axes`.
"""
return self.axes
# Note: in the docstring below, the newlines in the examples after the
# calls to legend() allow replacing it with figlegend() to generate the
# docstring of pyplot.figlegend.
@docstring.dedent_interpd
def legend(self, *args, **kwargs):
"""
Place a legend on the figure.
To make a legend from existing artists on every axes::
legend()
To make a legend for a list of lines and labels::
legend(
(line1, line2, line3),
('label1', 'label2', 'label3'),
loc='upper right')
These can also be specified by keyword::
legend(
handles=(line1, line2, line3),
labels=('label1', 'label2', 'label3'),
loc='upper right')
Parameters
----------
handles : sequence of `.Artist`, optional
A list of Artists (lines, patches) to be added to the legend.
Use this together with *labels*, if you need full control on what
is shown in the legend and the automatic mechanism described above
is not sufficient.
The length of handles and labels should be the same in this
case. If they are not, they are truncated to the smaller length.
labels : sequence of strings, optional
A list of labels to show next to the artists.
Use this together with *handles*, if you need full control on what
is shown in the legend and the automatic mechanism described above
is not sufficient.
Other Parameters
----------------
%(_legend_kw_doc)s
Returns
-------
:class:`matplotlib.legend.Legend` instance
Notes
-----
Not all kinds of artist are supported by the legend command. See
:doc:`/tutorials/intermediate/legend_guide` for details.
"""
handles, labels, extra_args, kwargs = mlegend._parse_legend_args(
self.axes,
*args,
**kwargs)
# check for third arg
if len(extra_args):
# cbook.warn_deprecated(
# "2.1",
# message="Figure.legend will accept no more than two "
# "positional arguments in the future. Use "
# "'fig.legend(handles, labels, loc=location)' "
# "instead.")
# kwargs['loc'] = extra_args[0]
# extra_args = extra_args[1:]
pass
l = mlegend.Legend(self, handles, labels, *extra_args, **kwargs)
self.legends.append(l)
l._remove_method = self.legends.remove
self.stale = True
return l
@cbook._delete_parameter("3.1", "withdash")
@docstring.dedent_interpd
def text(self, x, y, s, fontdict=None, withdash=False, **kwargs):
"""
Add text to figure.
Parameters
----------
x, y : float
The position to place the text. By default, this is in figure
coordinates, floats in [0, 1]. The coordinate system can be changed
using the *transform* keyword.
s : str
The text string.
fontdict : dictionary, optional, default: None
A dictionary to override the default text properties. If fontdict
is None, the defaults are determined by your rc parameters. A
property in *kwargs* override the same property in fontdict.
withdash : boolean, optional, default: False
Creates a `~matplotlib.text.TextWithDash` instance instead of a
`~matplotlib.text.Text` instance.
Other Parameters
----------------
**kwargs : `~matplotlib.text.Text` properties
Other miscellaneous text parameters.
%(Text)s
Returns
-------
text : `~.text.Text`
See Also
--------
.Axes.text
.pyplot.text
"""
default = dict(transform=self.transFigure)
if withdash:
text = TextWithDash(x=x, y=y, text=s)
else:
text = Text(x=x, y=y, text=s)
text.update(default)
if fontdict is not None:
text.update(fontdict)
text.update(kwargs)
text.set_figure(self)
text.stale_callback = _stale_figure_callback
self.texts.append(text)
text._remove_method = self.texts.remove
self.stale = True
return text
def _set_artist_props(self, a):
if a != self:
a.set_figure(self)
a.stale_callback = _stale_figure_callback
a.set_transform(self.transFigure)
@docstring.dedent_interpd
def gca(self, **kwargs):
"""
Get the current axes, creating one if necessary.
The following kwargs are supported for ensuring the returned axes
adheres to the given projection etc., and for axes creation if
the active axes does not exist:
%(Axes)s
"""
ckey, cax = self._axstack.current_key_axes()
# if there exists an axes on the stack see if it matches
# the desired axes configuration
if cax is not None:
# if no kwargs are given just return the current axes
# this is a convenience for gca() on axes such as polar etc.
if not kwargs:
return cax
# if the user has specified particular projection detail
# then build up a key which can represent this
else:
projection_class, _, key = \
self._process_projection_requirements(**kwargs)
# let the returned axes have any gridspec by removing it from
# the key
ckey = ckey[1:]
key = key[1:]
# if the cax matches this key then return the axes, otherwise
# continue and a new axes will be created
if key == ckey and isinstance(cax, projection_class):
return cax
else:
cbook._warn_external('Requested projection is different '
'from current axis projection, '
'creating new axis with requested '
'projection.')
# no axes found, so create one which spans the figure
return self.add_subplot(1, 1, 1, **kwargs)
def sca(self, a):
"""Set the current axes to be a and return a."""
self._axstack.bubble(a)
for func in self._axobservers:
func(self)
return a
def _gci(self):
"""
Helper for :func:`~matplotlib.pyplot.gci`. Do not use elsewhere.
"""
# Look first for an image in the current Axes:
cax = self._axstack.current_key_axes()[1]
if cax is None:
return None
im = cax._gci()
if im is not None:
return im
# If there is no image in the current Axes, search for
# one in a previously created Axes. Whether this makes
# sense is debatable, but it is the documented behavior.
for ax in reversed(self.axes):
im = ax._gci()
if im is not None:
return im
return None
def __getstate__(self):
state = super().__getstate__()
# the axobservers cannot currently be pickled.
# Additionally, the canvas cannot currently be pickled, but this has
# the benefit of meaning that a figure can be detached from one canvas,
# and re-attached to another.
for attr_to_pop in ('_axobservers', 'show',
'canvas', '_cachedRenderer'):
state.pop(attr_to_pop, None)
# add version information to the state
state['__mpl_version__'] = _mpl_version
# check whether the figure manager (if any) is registered with pyplot
from matplotlib import _pylab_helpers
if getattr(self.canvas, 'manager', None) \
in _pylab_helpers.Gcf.figs.values():
state['_restore_to_pylab'] = True
# set all the layoutbox information to None. kiwisolver objects can't
# be pickled, so we lose the layout options at this point.
state.pop('_layoutbox', None)
# suptitle:
if self._suptitle is not None:
self._suptitle._layoutbox = None
return state
def __setstate__(self, state):
version = state.pop('__mpl_version__')
restore_to_pylab = state.pop('_restore_to_pylab', False)
if version != _mpl_version:
cbook._warn_external(
f"This figure was saved with matplotlib version {version} and "
f"is unlikely to function correctly.")
self.__dict__ = state
# re-initialise some of the unstored state information
self._axobservers = []
self.canvas = None
self._layoutbox = None
if restore_to_pylab:
# lazy import to avoid circularity
import matplotlib.pyplot as plt
import matplotlib._pylab_helpers as pylab_helpers
allnums = plt.get_fignums()
num = max(allnums) + 1 if allnums else 1
mgr = plt._backend_mod.new_figure_manager_given_figure(num, self)
# XXX The following is a copy and paste from pyplot. Consider
# factoring to pylab_helpers
if self.get_label():
mgr.set_window_title(self.get_label())
# make this figure current on button press event
def make_active(event):
pylab_helpers.Gcf.set_active(mgr)
mgr._cidgcf = mgr.canvas.mpl_connect('button_press_event',
make_active)
pylab_helpers.Gcf.set_active(mgr)
self.number = num
plt.draw_if_interactive()
self.stale = True
def add_axobserver(self, func):
"""Whenever the axes state change, ``func(self)`` will be called."""
self._axobservers.append(func)
def savefig(self, fname, *, transparent=None, **kwargs):
"""
Save the current figure.
Call signature::
savefig(fname, dpi=None, facecolor='w', edgecolor='w',
orientation='portrait', papertype=None, format=None,
transparent=False, bbox_inches=None, pad_inches=0.1,
frameon=None, metadata=None)
The output formats available depend on the backend being used.
Parameters
----------
fname : str or PathLike or file-like object
A path, or a Python file-like object, or
possibly some backend-dependent object such as
`matplotlib.backends.backend_pdf.PdfPages`.
If *format* is not set, then the output format is inferred from
the extension of *fname*, if any, and from :rc:`savefig.format`
otherwise. If *format* is set, it determines the output format.
Hence, if *fname* is not a path or has no extension, remember to
specify *format* to ensure that the correct backend is used.
Other Parameters
----------------
dpi : [ *None* | scalar > 0 | 'figure' ]
The resolution in dots per inch. If *None*, defaults to
:rc:`savefig.dpi`. If 'figure', uses the figure's dpi value.
quality : [ *None* | 1 <= scalar <= 100 ]
The image quality, on a scale from 1 (worst) to 95 (best).
Applicable only if *format* is jpg or jpeg, ignored otherwise.
If *None*, defaults to :rc:`savefig.jpeg_quality` (95 by default).
Values above 95 should be avoided; 100 completely disables the
JPEG quantization stage.
optimize : bool
If *True*, indicates that the JPEG encoder should make an extra
pass over the image in order to select optimal encoder settings.
Applicable only if *format* is jpg or jpeg, ignored otherwise.
Is *False* by default.
progressive : bool
If *True*, indicates that this image should be stored as a
progressive JPEG file. Applicable only if *format* is jpg or
jpeg, ignored otherwise. Is *False* by default.
facecolor : color spec or None, optional
The facecolor of the figure; if *None*, defaults to
:rc:`savefig.facecolor`.
edgecolor : color spec or None, optional
The edgecolor of the figure; if *None*, defaults to
:rc:`savefig.edgecolor`
orientation : {'landscape', 'portrait'}
Currently only supported by the postscript backend.
papertype : str
One of 'letter', 'legal', 'executive', 'ledger', 'a0' through
'a10', 'b0' through 'b10'. Only supported for postscript
output.
format : str
The file format, e.g. 'png', 'pdf', 'svg', ... The behavior when
this is unset is documented under *fname*.
transparent : bool
If *True*, the axes patches will all be transparent; the
figure patch will also be transparent unless facecolor
and/or edgecolor are specified via kwargs.
This is useful, for example, for displaying
a plot on top of a colored background on a web page. The
transparency of these patches will be restored to their
original values upon exit of this function.
bbox_inches : str or `~matplotlib.transforms.Bbox`, optional
Bbox in inches. Only the given portion of the figure is
saved. If 'tight', try to figure out the tight bbox of
the figure. If None, use savefig.bbox
pad_inches : scalar, optional
Amount of padding around the figure when bbox_inches is
'tight'. If None, use savefig.pad_inches
bbox_extra_artists : list of `~matplotlib.artist.Artist`, optional
A list of extra artists that will be considered when the
tight bbox is calculated.
metadata : dict, optional
Key/value pairs to store in the image metadata. The supported keys
and defaults depend on the image format and backend:
- 'png' with Agg backend: See the parameter ``metadata`` of
`~.FigureCanvasAgg.print_png`.
- 'pdf' with pdf backend: See the parameter ``metadata`` of
`~.backend_pdf.PdfPages`.
- 'eps' and 'ps' with PS backend: Only 'Creator' is supported.
pil_kwargs : dict, optional
Additional keyword arguments that are passed to `PIL.Image.save`
when saving the figure. Only applicable for formats that are saved
using Pillow, i.e. JPEG, TIFF, and (if the keyword is set to a
non-None value) PNG.
"""
kwargs.setdefault('dpi', rcParams['savefig.dpi'])
if "frameon" in kwargs:
cbook.warn_deprecated("3.1", name="frameon", obj_type="kwarg",
alternative="facecolor")
frameon = kwargs.pop("frameon")
if frameon is None:
frameon = dict.__getitem__(rcParams, 'savefig.frameon')
else:
frameon = False # Won't pass "if frameon:" below.
if transparent is None:
transparent = rcParams['savefig.transparent']
if transparent:
kwargs.setdefault('facecolor', 'none')
kwargs.setdefault('edgecolor', 'none')
original_axes_colors = []
for ax in self.axes:
patch = ax.patch
original_axes_colors.append((patch.get_facecolor(),
patch.get_edgecolor()))
patch.set_facecolor('none')
patch.set_edgecolor('none')
else:
kwargs.setdefault('facecolor', rcParams['savefig.facecolor'])
kwargs.setdefault('edgecolor', rcParams['savefig.edgecolor'])
if frameon:
original_frameon = self.patch.get_visible()
self.patch.set_visible(frameon)
self.canvas.print_figure(fname, **kwargs)
if frameon:
self.patch.set_visible(original_frameon)
if transparent:
for ax, cc in zip(self.axes, original_axes_colors):
ax.patch.set_facecolor(cc[0])
ax.patch.set_edgecolor(cc[1])
@docstring.dedent_interpd
def colorbar(self, mappable, cax=None, ax=None, use_gridspec=True, **kw):
"""
Create a colorbar for a ScalarMappable instance, *mappable*.
Documentation for the pyplot thin wrapper:
%(colorbar_doc)s
"""
if ax is None:
ax = self.gca()
# Store the value of gca so that we can set it back later on.
current_ax = self.gca()
if cax is None:
if use_gridspec and isinstance(ax, SubplotBase) \
and (not self.get_constrained_layout()):
cax, kw = cbar.make_axes_gridspec(ax, **kw)
else:
cax, kw = cbar.make_axes(ax, **kw)
# need to remove kws that cannot be passed to Colorbar
NON_COLORBAR_KEYS = ['fraction', 'pad', 'shrink', 'aspect', 'anchor',
'panchor']
cb_kw = {k: v for k, v in kw.items() if k not in NON_COLORBAR_KEYS}
cb = cbar.colorbar_factory(cax, mappable, **cb_kw)
self.sca(current_ax)
self.stale = True
return cb
def subplots_adjust(self, left=None, bottom=None, right=None, top=None,
wspace=None, hspace=None):
"""
Update the :class:`SubplotParams` with *kwargs* (defaulting to rc when
*None*) and update the subplot locations.
"""
if self.get_constrained_layout():
self.set_constrained_layout(False)
cbook._warn_external("This figure was using "
"constrained_layout==True, but that is "
"incompatible with subplots_adjust and or "
"tight_layout: setting "
"constrained_layout==False. ")
self.subplotpars.update(left, bottom, right, top, wspace, hspace)
for ax in self.axes:
if not isinstance(ax, SubplotBase):
# Check if sharing a subplots axis
if isinstance(ax._sharex, SubplotBase):
ax._sharex.update_params()
ax.set_position(ax._sharex.figbox)
elif isinstance(ax._sharey, SubplotBase):
ax._sharey.update_params()
ax.set_position(ax._sharey.figbox)
else:
ax.update_params()
ax.set_position(ax.figbox)
self.stale = True
def ginput(self, n=1, timeout=30, show_clicks=True, mouse_add=1,
mouse_pop=3, mouse_stop=2):
"""
Blocking call to interact with a figure.
Wait until the user clicks *n* times on the figure, and return the
coordinates of each click in a list.
There are three possible interactions:
- Add a point.
- Remove the most recently added point.
- Stop the interaction and return the points added so far.
The actions are assigned to mouse buttons via the arguments
*mouse_add*, *mouse_pop* and *mouse_stop*. Mouse buttons are defined
by the numbers:
- 1: left mouse button
- 2: middle mouse button
- 3: right mouse button
- None: no mouse button
Parameters
----------
n : int, optional, default: 1
Number of mouse clicks to accumulate. If negative, accumulate
clicks until the input is terminated manually.
timeout : scalar, optional, default: 30
Number of seconds to wait before timing out. If zero or negative
will never timeout.
show_clicks : bool, optional, default: False
If True, show a red cross at the location of each click.
mouse_add : {1, 2, 3, None}, optional, default: 1 (left click)
Mouse button used to add points.
mouse_pop : {1, 2, 3, None}, optional, default: 3 (right click)
Mouse button used to remove the most recently added point.
mouse_stop : {1, 2, 3, None}, optional, default: 2 (middle click)
Mouse button used to stop input.
Returns
-------
points : list of tuples
A list of the clicked (x, y) coordinates.
Notes
-----
The keyboard can also be used to select points in case your mouse
does not have one or more of the buttons. The delete and backspace
keys act like right clicking (i.e., remove last point), the enter key
terminates input and any other key (not already used by the window
manager) selects a point.
"""
blocking_mouse_input = BlockingMouseInput(self,
mouse_add=mouse_add,
mouse_pop=mouse_pop,
mouse_stop=mouse_stop)
return blocking_mouse_input(n=n, timeout=timeout,
show_clicks=show_clicks)
def waitforbuttonpress(self, timeout=-1):
"""
Blocking call to interact with the figure.
This will return True is a key was pressed, False if a mouse
button was pressed and None if *timeout* was reached without
either being pressed.
If *timeout* is negative, does not timeout.
"""
blocking_input = BlockingKeyMouseInput(self)
return blocking_input(timeout=timeout)
def get_default_bbox_extra_artists(self):
bbox_artists = [artist for artist in self.get_children()
if (artist.get_visible() and artist.get_in_layout())]
for ax in self.axes:
if ax.get_visible():
bbox_artists.extend(ax.get_default_bbox_extra_artists())
# we don't want the figure's patch to influence the bbox calculation
bbox_artists.remove(self.patch)
return bbox_artists
def get_tightbbox(self, renderer, bbox_extra_artists=None):
"""
Return a (tight) bounding box of the figure in inches.
Artists that have ``artist.set_in_layout(False)`` are not included
in the bbox.
Parameters
----------
renderer : `.RendererBase` instance
renderer that will be used to draw the figures (i.e.
``fig.canvas.get_renderer()``)
bbox_extra_artists : list of `.Artist` or ``None``
List of artists to include in the tight bounding box. If
``None`` (default), then all artist children of each axes are
included in the tight bounding box.
Returns
-------
bbox : `.BboxBase`
containing the bounding box (in figure inches).
"""
bb = []
if bbox_extra_artists is None:
artists = self.get_default_bbox_extra_artists()
else:
artists = bbox_extra_artists
for a in artists:
bbox = a.get_tightbbox(renderer)
if bbox is not None and (bbox.width != 0 or bbox.height != 0):
bb.append(bbox)
for ax in self.axes:
if ax.get_visible():
# some axes don't take the bbox_extra_artists kwarg so we
# need this conditional....
try:
bbox = ax.get_tightbbox(renderer,
bbox_extra_artists=bbox_extra_artists)
except TypeError:
bbox = ax.get_tightbbox(renderer)
bb.append(bbox)
bb = [b for b in bb
if (np.isfinite(b.width) and np.isfinite(b.height)
and (b.width != 0 or b.height != 0))]
if len(bb) == 0:
return self.bbox_inches
_bbox = Bbox.union(bb)
bbox_inches = TransformedBbox(_bbox,
Affine2D().scale(1. / self.dpi))
return bbox_inches
def init_layoutbox(self):
"""Initialize the layoutbox for use in constrained_layout."""
if self._layoutbox is None:
self._layoutbox = layoutbox.LayoutBox(parent=None,
name='figlb',
artist=self)
self._layoutbox.constrain_geometry(0., 0., 1., 1.)
def execute_constrained_layout(self, renderer=None):
"""
Use ``layoutbox`` to determine pos positions within axes.
See also `.set_constrained_layout_pads`.
"""
from matplotlib._constrained_layout import do_constrained_layout
_log.debug('Executing constrainedlayout')
if self._layoutbox is None:
cbook._warn_external("Calling figure.constrained_layout, but "
"figure not setup to do constrained layout. "
" You either called GridSpec without the "
"fig keyword, you are using plt.subplot, "
"or you need to call figure or subplots "
"with the constrained_layout=True kwarg.")
return
w_pad, h_pad, wspace, hspace = self.get_constrained_layout_pads()
# convert to unit-relative lengths
fig = self
width, height = fig.get_size_inches()
w_pad = w_pad / width
h_pad = h_pad / height
if renderer is None:
renderer = layoutbox.get_renderer(fig)
do_constrained_layout(fig, renderer, h_pad, w_pad, hspace, wspace)
def tight_layout(self, renderer=None, pad=1.08, h_pad=None, w_pad=None,
rect=None):
"""
Automatically adjust subplot parameters to give specified padding.
To exclude an artist on the axes from the bounding box calculation
that determines the subplot parameters (i.e. legend, or annotation),
then set `a.set_in_layout(False)` for that artist.
Parameters
----------
renderer : subclass of `~.backend_bases.RendererBase`, optional
Defaults to the renderer for the figure.
pad : float, optional
Padding between the figure edge and the edges of subplots,
as a fraction of the font size.
h_pad, w_pad : float, optional
Padding (height/width) between edges of adjacent subplots,
as a fraction of the font size. Defaults to *pad*.
rect : tuple (left, bottom, right, top), optional
A rectangle (left, bottom, right, top) in the normalized
figure coordinate that the whole subplots area (including
labels) will fit into. Default is (0, 0, 1, 1).
See Also
--------
.Figure.set_tight_layout
.pyplot.tight_layout
"""
from .tight_layout import (
get_renderer, get_subplotspec_list, get_tight_layout_figure)
subplotspec_list = get_subplotspec_list(self.axes)
if None in subplotspec_list:
cbook._warn_external("This figure includes Axes that are not "
"compatible with tight_layout, so results "
"might be incorrect.")
if renderer is None:
renderer = get_renderer(self)
kwargs = get_tight_layout_figure(
self, self.axes, subplotspec_list, renderer,
pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect)
if kwargs:
self.subplots_adjust(**kwargs)
def align_xlabels(self, axs=None):
"""
Align the ylabels of subplots in the same subplot column if label
alignment is being done automatically (i.e. the label position is
not manually set).
Alignment persists for draw events after this is called.
If a label is on the bottom, it is aligned with labels on axes that
also have their label on the bottom and that have the same
bottom-most subplot row. If the label is on the top,
it is aligned with labels on axes with the same top-most row.
Parameters
----------
axs : list of `~matplotlib.axes.Axes`
Optional list of (or ndarray) `~matplotlib.axes.Axes`
to align the xlabels.
Default is to align all axes on the figure.
See Also
--------
matplotlib.figure.Figure.align_ylabels
matplotlib.figure.Figure.align_labels
Notes
-----
This assumes that ``axs`` are from the same `.GridSpec`, so that
their `.SubplotSpec` positions correspond to figure positions.
Examples
--------
Example with rotated xtick labels::
fig, axs = plt.subplots(1, 2)
for tick in axs[0].get_xticklabels():
tick.set_rotation(55)
axs[0].set_xlabel('XLabel 0')
axs[1].set_xlabel('XLabel 1')
fig.align_xlabels()
"""
if axs is None:
axs = self.axes
axs = np.asarray(axs).ravel()
for ax in axs:
_log.debug(' Working on: %s', ax.get_xlabel())
ss = ax.get_subplotspec()
nrows, ncols, row0, row1, col0, col1 = ss.get_rows_columns()
labpo = ax.xaxis.get_label_position() # top or bottom
# loop through other axes, and search for label positions
# that are same as this one, and that share the appropriate
# row number.
# Add to a grouper associated with each axes of sibblings.
# This list is inspected in `axis.draw` by
# `axis._update_label_position`.
for axc in axs:
if axc.xaxis.get_label_position() == labpo:
ss = axc.get_subplotspec()
nrows, ncols, rowc0, rowc1, colc, col1 = \
ss.get_rows_columns()
if (labpo == 'bottom' and rowc1 == row1 or
labpo == 'top' and rowc0 == row0):
# grouper for groups of xlabels to align
self._align_xlabel_grp.join(ax, axc)
def align_ylabels(self, axs=None):
"""
Align the ylabels of subplots in the same subplot column if label
alignment is being done automatically (i.e. the label position is
not manually set).
Alignment persists for draw events after this is called.
If a label is on the left, it is aligned with labels on axes that
also have their label on the left and that have the same
left-most subplot column. If the label is on the right,
it is aligned with labels on axes with the same right-most column.
Parameters
----------
axs : list of `~matplotlib.axes.Axes`
Optional list (or ndarray) of `~matplotlib.axes.Axes`
to align the ylabels.
Default is to align all axes on the figure.
See Also
--------
matplotlib.figure.Figure.align_xlabels
matplotlib.figure.Figure.align_labels
Notes
-----
This assumes that ``axs`` are from the same `.GridSpec`, so that
their `.SubplotSpec` positions correspond to figure positions.
Examples
--------
Example with large yticks labels::
fig, axs = plt.subplots(2, 1)
axs[0].plot(np.arange(0, 1000, 50))
axs[0].set_ylabel('YLabel 0')
axs[1].set_ylabel('YLabel 1')
fig.align_ylabels()
"""
if axs is None:
axs = self.axes
axs = np.asarray(axs).ravel()
for ax in axs:
_log.debug(' Working on: %s', ax.get_ylabel())
ss = ax.get_subplotspec()
nrows, ncols, row0, row1, col0, col1 = ss.get_rows_columns()
labpo = ax.yaxis.get_label_position() # left or right
# loop through other axes, and search for label positions
# that are same as this one, and that share the appropriate
# column number.
# Add to a list associated with each axes of sibblings.
# This list is inspected in `axis.draw` by
# `axis._update_label_position`.
for axc in axs:
if axc != ax:
if axc.yaxis.get_label_position() == labpo:
ss = axc.get_subplotspec()
nrows, ncols, row0, row1, colc0, colc1 = \
ss.get_rows_columns()
if (labpo == 'left' and colc0 == col0 or
labpo == 'right' and colc1 == col1):
# grouper for groups of ylabels to align
self._align_ylabel_grp.join(ax, axc)
def align_labels(self, axs=None):
"""
Align the xlabels and ylabels of subplots with the same subplots
row or column (respectively) if label alignment is being
done automatically (i.e. the label position is not manually set).
Alignment persists for draw events after this is called.
Parameters
----------
axs : list of `~matplotlib.axes.Axes`
Optional list (or ndarray) of `~matplotlib.axes.Axes`
to align the labels.
Default is to align all axes on the figure.
See Also
--------
matplotlib.figure.Figure.align_xlabels
matplotlib.figure.Figure.align_ylabels
"""
self.align_xlabels(axs=axs)
self.align_ylabels(axs=axs)
def add_gridspec(self, nrows, ncols, **kwargs):
"""
Return a `.GridSpec` that has this figure as a parent. This allows
complex layout of axes in the figure.
Parameters
----------
nrows : int
Number of rows in grid.
ncols : int
Number or columns in grid.
Returns
-------
gridspec : `.GridSpec`
Other Parameters
----------------
**kwargs
Keyword arguments are passed to `.GridSpec`.
See Also
--------
matplotlib.pyplot.subplots
Examples
--------
Adding a subplot that spans two rows::
fig = plt.figure()
gs = fig.add_gridspec(2, 2)
ax1 = fig.add_subplot(gs[0, 0])
ax2 = fig.add_subplot(gs[1, 0])
# spans two rows:
ax3 = fig.add_subplot(gs[:, 1])
"""
_ = kwargs.pop('figure', None) # pop in case user has added this...
gs = GridSpec(nrows=nrows, ncols=ncols, figure=self, **kwargs)
self._gridspecs.append(gs)
return gs
def figaspect(arg):
"""
Calculate the width and height for a figure with a specified aspect ratio.
While the height is taken from :rc:`figure.figsize`, the width is
adjusted to match the desired aspect ratio. Additionally, it is ensured
that the width is in the range [4., 16.] and the height is in the range
[2., 16.]. If necessary, the default height is adjusted to ensure this.
Parameters
----------
arg : scalar or 2d array
If a scalar, this defines the aspect ratio (i.e. the ratio height /
width).
In case of an array the aspect ratio is number of rows / number of
columns, so that the array could be fitted in the figure undistorted.
Returns
-------
width, height
The figure size in inches.
Notes
-----
If you want to create an axes within the figure, that still preserves the
aspect ratio, be sure to create it with equal width and height. See
examples below.
Thanks to Fernando Perez for this function.
Examples
--------
Make a figure twice as tall as it is wide::
w, h = figaspect(2.)
fig = Figure(figsize=(w, h))
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
ax.imshow(A, **kwargs)
Make a figure with the proper aspect for an array::
A = rand(5,3)
w, h = figaspect(A)
fig = Figure(figsize=(w, h))
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
ax.imshow(A, **kwargs)
"""
isarray = hasattr(arg, 'shape') and not np.isscalar(arg)
# min/max sizes to respect when autoscaling. If John likes the idea, they
# could become rc parameters, for now they're hardwired.
figsize_min = np.array((4.0, 2.0)) # min length for width/height
figsize_max = np.array((16.0, 16.0)) # max length for width/height
# Extract the aspect ratio of the array
if isarray:
nr, nc = arg.shape[:2]
arr_ratio = nr / nc
else:
arr_ratio = arg
# Height of user figure defaults
fig_height = rcParams['figure.figsize'][1]
# New size for the figure, keeping the aspect ratio of the caller
newsize = np.array((fig_height / arr_ratio, fig_height))
# Sanity checks, don't drop either dimension below figsize_min
newsize /= min(1.0, *(newsize / figsize_min))
# Avoid humongous windows as well
newsize /= max(1.0, *(newsize / figsize_max))
# Finally, if we have a really funky aspect ratio, break it but respect
# the min/max dimensions (we don't want figures 10 feet tall!)
newsize = np.clip(newsize, figsize_min, figsize_max)
return newsize
docstring.interpd.update(Figure=martist.kwdoc(Figure))
|
52c902be41f800fd8b966705a12d2ec510e6d2eb6efd026e72c04b7eb6b15fab
|
"""
A module for converting numbers or color arguments to *RGB* or *RGBA*.
*RGB* and *RGBA* are sequences of, respectively, 3 or 4 floats in the
range 0-1.
This module includes functions and classes for color specification
conversions, and for mapping numbers to colors in a 1-D array of colors called
a colormap.
Mapping data onto colors using a colormap typically involves two steps:
a data array is first mapped onto the range 0-1 using a subclass of
:class:`Normalize`, then this number is mapped to a color using
a subclass of :class:`Colormap`. Two are provided here:
:class:`LinearSegmentedColormap`, which uses piecewise-linear interpolation
to define colormaps, and :class:`ListedColormap`, which makes a colormap
from a list of colors.
.. seealso::
:doc:`/tutorials/colors/colormap-manipulation` for examples of how to
make colormaps and
:doc:`/tutorials/colors/colormaps` for a list of built-in colormaps.
:doc:`/tutorials/colors/colormapnorms` for more details about data
normalization
More colormaps are available at palettable_.
The module also provides functions for checking whether an object can be
interpreted as a color (:func:`is_color_like`), for converting such an object
to an RGBA tuple (:func:`to_rgba`) or to an HTML-like hex string in the
`#rrggbb` format (:func:`to_hex`), and a sequence of colors to an `(n, 4)`
RGBA array (:func:`to_rgba_array`). Caching is used for efficiency.
Matplotlib recognizes the following formats to specify a color:
* an RGB or RGBA tuple of float values in ``[0, 1]`` (e.g., ``(0.1, 0.2, 0.5)``
or ``(0.1, 0.2, 0.5, 0.3)``);
* a hex RGB or RGBA string (e.g., ``'#0f0f0f'`` or ``'#0f0f0f80'``;
case-insensitive);
* a string representation of a float value in ``[0, 1]`` inclusive for gray
level (e.g., ``'0.5'``);
* one of ``{'b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'}``;
* a X11/CSS4 color name (case-insensitive);
* a name from the `xkcd color survey`_, prefixed with ``'xkcd:'`` (e.g.,
``'xkcd:sky blue'``; case insensitive);
* one of the Tableau Colors from the 'T10' categorical palette (the default
color cycle): ``{'tab:blue', 'tab:orange', 'tab:green', 'tab:red',
'tab:purple', 'tab:brown', 'tab:pink', 'tab:gray', 'tab:olive', 'tab:cyan'}``
(case-insensitive);
* a "CN" color spec, i.e. `'C'` followed by a number, which is an index into
the default property cycle (``matplotlib.rcParams['axes.prop_cycle']``); the
indexing is intended to occur at rendering time, and defaults to black if the
cycle does not include color.
.. _palettable: https://jiffyclub.github.io/palettable/
.. _xkcd color survey: https://xkcd.com/color/rgb/
"""
from collections.abc import Sized
import itertools
import re
import numpy as np
import matplotlib.cbook as cbook
from ._color_data import BASE_COLORS, TABLEAU_COLORS, CSS4_COLORS, XKCD_COLORS
class _ColorMapping(dict):
def __init__(self, mapping):
super().__init__(mapping)
self.cache = {}
def __setitem__(self, key, value):
super().__setitem__(key, value)
self.cache.clear()
def __delitem__(self, key):
super().__delitem__(key)
self.cache.clear()
_colors_full_map = {}
# Set by reverse priority order.
_colors_full_map.update(XKCD_COLORS)
_colors_full_map.update({k.replace('grey', 'gray'): v
for k, v in XKCD_COLORS.items()
if 'grey' in k})
_colors_full_map.update(CSS4_COLORS)
_colors_full_map.update(TABLEAU_COLORS)
_colors_full_map.update({k.replace('gray', 'grey'): v
for k, v in TABLEAU_COLORS.items()
if 'gray' in k})
_colors_full_map.update(BASE_COLORS)
_colors_full_map = _ColorMapping(_colors_full_map)
def get_named_colors_mapping():
"""Return the global mapping of names to named colors."""
return _colors_full_map
def _sanitize_extrema(ex):
if ex is None:
return ex
try:
ret = ex.item()
except AttributeError:
ret = float(ex)
return ret
def _is_nth_color(c):
"""Return whether *c* can be interpreted as an item in the color cycle."""
return isinstance(c, str) and re.match(r"\AC[0-9]+\Z", c)
def is_color_like(c):
"""Return whether *c* can be interpreted as an RGB(A) color."""
# Special-case nth color syntax because it cannot be parsed during setup.
if _is_nth_color(c):
return True
try:
to_rgba(c)
except ValueError:
return False
else:
return True
def same_color(c1, c2):
"""
Compare two colors to see if they are the same.
Parameters
----------
c1, c2 : Matplotlib colors
Returns
-------
bool
``True`` if *c1* and *c2* are the same color, otherwise ``False``.
"""
return (to_rgba_array(c1) == to_rgba_array(c2)).all()
def to_rgba(c, alpha=None):
"""
Convert *c* to an RGBA color.
Parameters
----------
c : Matplotlib color
alpha : scalar, optional
If *alpha* is not ``None``, it forces the alpha value, except if *c* is
``"none"`` (case-insensitive), which always maps to ``(0, 0, 0, 0)``.
Returns
-------
tuple
Tuple of ``(r, g, b, a)`` scalars.
"""
# Special-case nth color syntax because it should not be cached.
if _is_nth_color(c):
from matplotlib import rcParams
prop_cycler = rcParams['axes.prop_cycle']
colors = prop_cycler.by_key().get('color', ['k'])
c = colors[int(c[1:]) % len(colors)]
try:
rgba = _colors_full_map.cache[c, alpha]
except (KeyError, TypeError): # Not in cache, or unhashable.
rgba = None
if rgba is None: # Suppress exception chaining of cache lookup failure.
rgba = _to_rgba_no_colorcycle(c, alpha)
try:
_colors_full_map.cache[c, alpha] = rgba
except TypeError:
pass
return rgba
def _to_rgba_no_colorcycle(c, alpha=None):
"""Convert *c* to an RGBA color, with no support for color-cycle syntax.
If *alpha* is not ``None``, it forces the alpha value, except if *c* is
``"none"`` (case-insensitive), which always maps to ``(0, 0, 0, 0)``.
"""
orig_c = c
if isinstance(c, str):
if c.lower() == "none":
return (0., 0., 0., 0.)
# Named color.
try:
# This may turn c into a non-string, so we check again below.
c = _colors_full_map[c]
except KeyError:
try:
c = _colors_full_map[c.lower()]
except KeyError:
pass
else:
if len(orig_c) == 1:
cbook.warn_deprecated(
"3.1", message="Support for uppercase "
"single-letter colors is deprecated since Matplotlib "
"%(since)s and will be removed %(removal)s; please "
"use lowercase instead.")
if isinstance(c, str):
# hex color with no alpha.
match = re.match(r"\A#[a-fA-F0-9]{6}\Z", c)
if match:
return (tuple(int(n, 16) / 255
for n in [c[1:3], c[3:5], c[5:7]])
+ (alpha if alpha is not None else 1.,))
# hex color with alpha.
match = re.match(r"\A#[a-fA-F0-9]{8}\Z", c)
if match:
color = [int(n, 16) / 255
for n in [c[1:3], c[3:5], c[5:7], c[7:9]]]
if alpha is not None:
color[-1] = alpha
return tuple(color)
# string gray.
try:
c = float(c)
except ValueError:
pass
else:
if not (0 <= c <= 1):
raise ValueError(
f"Invalid string grayscale value {orig_c!r}. "
f"Value must be within 0-1 range")
return c, c, c, alpha if alpha is not None else 1.
raise ValueError(f"Invalid RGBA argument: {orig_c!r}")
# tuple color.
c = np.array(c)
if not np.can_cast(c.dtype, float, "same_kind") or c.ndim != 1:
# Test the dtype explicitly as `map(float, ...)`, `np.array(...,
# float)` and `np.array(...).astype(float)` all convert "0.5" to 0.5.
# Test dimensionality to reject single floats.
raise ValueError(f"Invalid RGBA argument: {orig_c!r}")
# Return a tuple to prevent the cached value from being modified.
c = tuple(c.astype(float))
if len(c) not in [3, 4]:
raise ValueError("RGBA sequence should have length 3 or 4")
if len(c) == 3 and alpha is None:
alpha = 1
if alpha is not None:
c = c[:3] + (alpha,)
if any(elem < 0 or elem > 1 for elem in c):
raise ValueError("RGBA values should be within 0-1 range")
return c
def to_rgba_array(c, alpha=None):
"""Convert *c* to a (n, 4) array of RGBA colors.
If *alpha* is not ``None``, it forces the alpha value. If *c* is
``"none"`` (case-insensitive) or an empty list, an empty array is returned.
"""
# Special-case inputs that are already arrays, for performance. (If the
# array has the wrong kind or shape, raise the error during one-at-a-time
# conversion.)
if (isinstance(c, np.ndarray) and c.dtype.kind in "if"
and c.ndim == 2 and c.shape[1] in [3, 4]):
if c.shape[1] == 3:
result = np.column_stack([c, np.zeros(len(c))])
result[:, -1] = alpha if alpha is not None else 1.
elif c.shape[1] == 4:
result = c.copy()
if alpha is not None:
result[:, -1] = alpha
if np.any((result < 0) | (result > 1)):
raise ValueError("RGBA values should be within 0-1 range")
return result
# Handle single values.
# Note that this occurs *after* handling inputs that are already arrays, as
# `to_rgba(c, alpha)` (below) is expensive for such inputs, due to the need
# to format the array in the ValueError message(!).
if cbook._str_lower_equal(c, "none"):
return np.zeros((0, 4), float)
try:
return np.array([to_rgba(c, alpha)], float)
except (ValueError, TypeError):
pass
# Convert one at a time.
result = np.empty((len(c), 4), float)
for i, cc in enumerate(c):
result[i] = to_rgba(cc, alpha)
return result
def to_rgb(c):
"""Convert *c* to an RGB color, silently dropping the alpha channel."""
return to_rgba(c)[:3]
def to_hex(c, keep_alpha=False):
"""Convert *c* to a hex color.
Uses the ``#rrggbb`` format if *keep_alpha* is False (the default),
``#rrggbbaa`` otherwise.
"""
c = to_rgba(c)
if not keep_alpha:
c = c[:3]
return "#" + "".join(format(int(np.round(val * 255)), "02x")
for val in c)
### Backwards-compatible color-conversion API
cnames = CSS4_COLORS
hexColorPattern = re.compile(r"\A#[a-fA-F0-9]{6}\Z")
rgb2hex = to_hex
hex2color = to_rgb
class ColorConverter(object):
"""
This class is only kept for backwards compatibility.
Its functionality is entirely provided by module-level functions.
"""
colors = _colors_full_map
cache = _colors_full_map.cache
to_rgb = staticmethod(to_rgb)
to_rgba = staticmethod(to_rgba)
to_rgba_array = staticmethod(to_rgba_array)
colorConverter = ColorConverter()
### End of backwards-compatible color-conversion API
def makeMappingArray(N, data, gamma=1.0):
"""Create an *N* -element 1-d lookup table
*data* represented by a list of x,y0,y1 mapping correspondences.
Each element in this list represents how a value between 0 and 1
(inclusive) represented by x is mapped to a corresponding value
between 0 and 1 (inclusive). The two values of y are to allow
for discontinuous mapping functions (say as might be found in a
sawtooth) where y0 represents the value of y for values of x
<= to that given, and y1 is the value to be used for x > than
that given). The list must start with x=0, end with x=1, and
all values of x must be in increasing order. Values between
the given mapping points are determined by simple linear interpolation.
Alternatively, data can be a function mapping values between 0 - 1
to 0 - 1.
The function returns an array "result" where ``result[x*(N-1)]``
gives the closest value for values of x between 0 and 1.
"""
if callable(data):
xind = np.linspace(0, 1, N) ** gamma
lut = np.clip(np.array(data(xind), dtype=float), 0, 1)
return lut
try:
adata = np.array(data)
except Exception:
raise TypeError("data must be convertible to an array")
shape = adata.shape
if len(shape) != 2 or shape[1] != 3:
raise ValueError("data must be nx3 format")
x = adata[:, 0]
y0 = adata[:, 1]
y1 = adata[:, 2]
if x[0] != 0. or x[-1] != 1.0:
raise ValueError(
"data mapping points must start with x=0 and end with x=1")
if (np.diff(x) < 0).any():
raise ValueError("data mapping points must have x in increasing order")
# begin generation of lookup table
x = x * (N - 1)
xind = (N - 1) * np.linspace(0, 1, N) ** gamma
ind = np.searchsorted(x, xind)[1:-1]
distance = (xind[1:-1] - x[ind - 1]) / (x[ind] - x[ind - 1])
lut = np.concatenate([
[y1[0]],
distance * (y0[ind] - y1[ind - 1]) + y1[ind - 1],
[y0[-1]],
])
# ensure that the lut is confined to values between 0 and 1 by clipping it
return np.clip(lut, 0.0, 1.0)
class Colormap(object):
"""
Baseclass for all scalar to RGBA mappings.
Typically Colormap instances are used to convert data values (floats) from
the interval ``[0, 1]`` to the RGBA color that the respective Colormap
represents. For scaling of data into the ``[0, 1]`` interval see
:class:`matplotlib.colors.Normalize`. It is worth noting that
:class:`matplotlib.cm.ScalarMappable` subclasses make heavy use of this
``data->normalize->map-to-color`` processing chain.
"""
def __init__(self, name, N=256):
"""
Parameters
----------
name : str
The name of the colormap.
N : int
The number of rgb quantization levels.
"""
self.name = name
self.N = int(N) # ensure that N is always int
self._rgba_bad = (0.0, 0.0, 0.0, 0.0) # If bad, don't paint anything.
self._rgba_under = None
self._rgba_over = None
self._i_under = self.N
self._i_over = self.N + 1
self._i_bad = self.N + 2
self._isinit = False
#: When this colormap exists on a scalar mappable and colorbar_extend
#: is not False, colorbar creation will pick up ``colorbar_extend`` as
#: the default value for the ``extend`` keyword in the
#: :class:`matplotlib.colorbar.Colorbar` constructor.
self.colorbar_extend = False
def __call__(self, X, alpha=None, bytes=False):
"""
Parameters
----------
X : scalar, ndarray
The data value(s) to convert to RGBA.
For floats, X should be in the interval ``[0.0, 1.0]`` to
return the RGBA values ``X*100`` percent along the Colormap line.
For integers, X should be in the interval ``[0, Colormap.N)`` to
return RGBA values *indexed* from the Colormap with index ``X``.
alpha : float, None
Alpha must be a scalar between 0 and 1, or None.
bytes : bool
If False (default), the returned RGBA values will be floats in the
interval ``[0, 1]`` otherwise they will be uint8s in the interval
``[0, 255]``.
Returns
-------
Tuple of RGBA values if X is scalar, otherwise an array of
RGBA values with a shape of ``X.shape + (4, )``.
"""
# See class docstring for arg/kwarg documentation.
if not self._isinit:
self._init()
mask_bad = None
if not np.iterable(X):
vtype = 'scalar'
xa = np.array([X])
else:
vtype = 'array'
xma = np.ma.array(X, copy=True) # Copy here to avoid side effects.
mask_bad = xma.mask # Mask will be used below.
xa = xma.filled() # Fill to avoid infs, etc.
del xma
# Calculations with native byteorder are faster, and avoid a
# bug that otherwise can occur with putmask when the last
# argument is a numpy scalar.
if not xa.dtype.isnative:
xa = xa.byteswap().newbyteorder()
if xa.dtype.kind == "f":
xa *= self.N
# Negative values are out of range, but astype(int) would truncate
# them towards zero.
xa[xa < 0] = -1
# xa == 1 (== N after multiplication) is not out of range.
xa[xa == self.N] = self.N - 1
# Avoid converting large positive values to negative integers.
np.clip(xa, -1, self.N, out=xa)
xa = xa.astype(int)
# Set the over-range indices before the under-range;
# otherwise the under-range values get converted to over-range.
xa[xa > self.N - 1] = self._i_over
xa[xa < 0] = self._i_under
if mask_bad is not None:
if mask_bad.shape == xa.shape:
np.copyto(xa, self._i_bad, where=mask_bad)
elif mask_bad:
xa.fill(self._i_bad)
if bytes:
lut = (self._lut * 255).astype(np.uint8)
else:
lut = self._lut.copy() # Don't let alpha modify original _lut.
if alpha is not None:
alpha = np.clip(alpha, 0, 1)
if bytes:
alpha = int(alpha * 255)
if (lut[-1] == 0).all():
lut[:-1, -1] = alpha
# All zeros is taken as a flag for the default bad
# color, which is no color--fully transparent. We
# don't want to override this.
else:
lut[:, -1] = alpha
# If the bad value is set to have a color, then we
# override its alpha just as for any other value.
rgba = lut.take(xa, axis=0, mode='clip')
if vtype == 'scalar':
rgba = tuple(rgba[0, :])
return rgba
def __copy__(self):
"""Create new object with the same class, update attributes
"""
cls = self.__class__
cmapobject = cls.__new__(cls)
cmapobject.__dict__.update(self.__dict__)
if self._isinit:
cmapobject._lut = np.copy(self._lut)
return cmapobject
def set_bad(self, color='k', alpha=None):
"""Set color to be used for masked values.
"""
self._rgba_bad = to_rgba(color, alpha)
if self._isinit:
self._set_extremes()
def set_under(self, color='k', alpha=None):
"""Set color to be used for low out-of-range values.
Requires norm.clip = False
"""
self._rgba_under = to_rgba(color, alpha)
if self._isinit:
self._set_extremes()
def set_over(self, color='k', alpha=None):
"""Set color to be used for high out-of-range values.
Requires norm.clip = False
"""
self._rgba_over = to_rgba(color, alpha)
if self._isinit:
self._set_extremes()
def _set_extremes(self):
if self._rgba_under:
self._lut[self._i_under] = self._rgba_under
else:
self._lut[self._i_under] = self._lut[0]
if self._rgba_over:
self._lut[self._i_over] = self._rgba_over
else:
self._lut[self._i_over] = self._lut[self.N - 1]
self._lut[self._i_bad] = self._rgba_bad
def _init(self):
"""Generate the lookup table, self._lut"""
raise NotImplementedError("Abstract class only")
def is_gray(self):
if not self._isinit:
self._init()
return (np.all(self._lut[:, 0] == self._lut[:, 1]) and
np.all(self._lut[:, 0] == self._lut[:, 2]))
def _resample(self, lutsize):
"""
Return a new color map with *lutsize* entries.
"""
raise NotImplementedError()
def reversed(self, name=None):
"""
Make a reversed instance of the Colormap.
.. note:: Function not implemented for base class.
Parameters
----------
name : str, optional
The name for the reversed colormap. If it's None the
name will be the name of the parent colormap + "_r".
See Also
--------
LinearSegmentedColormap.reversed
ListedColormap.reversed
"""
raise NotImplementedError()
class LinearSegmentedColormap(Colormap):
"""
Colormap objects based on lookup tables using linear segments.
The lookup table is generated using linear interpolation for each
primary color, with the 0-1 domain divided into any number of
segments.
"""
def __init__(self, name, segmentdata, N=256, gamma=1.0):
"""
Create color map from linear mapping segments
segmentdata argument is a dictionary with a red, green and blue
entries. Each entry should be a list of *x*, *y0*, *y1* tuples,
forming rows in a table. Entries for alpha are optional.
Example: suppose you want red to increase from 0 to 1 over
the bottom half, green to do the same over the middle half,
and blue over the top half. Then you would use::
cdict = {'red': [(0.0, 0.0, 0.0),
(0.5, 1.0, 1.0),
(1.0, 1.0, 1.0)],
'green': [(0.0, 0.0, 0.0),
(0.25, 0.0, 0.0),
(0.75, 1.0, 1.0),
(1.0, 1.0, 1.0)],
'blue': [(0.0, 0.0, 0.0),
(0.5, 0.0, 0.0),
(1.0, 1.0, 1.0)]}
Each row in the table for a given color is a sequence of
*x*, *y0*, *y1* tuples. In each sequence, *x* must increase
monotonically from 0 to 1. For any input value *z* falling
between *x[i]* and *x[i+1]*, the output value of a given color
will be linearly interpolated between *y1[i]* and *y0[i+1]*::
row i: x y0 y1
/
/
row i+1: x y0 y1
Hence y0 in the first row and y1 in the last row are never used.
See Also
--------
LinearSegmentedColormap.from_list
Static method; factory function for generating a smoothly-varying
LinearSegmentedColormap.
makeMappingArray
For information about making a mapping array.
"""
# True only if all colors in map are identical; needed for contouring.
self.monochrome = False
Colormap.__init__(self, name, N)
self._segmentdata = segmentdata
self._gamma = gamma
def _init(self):
self._lut = np.ones((self.N + 3, 4), float)
self._lut[:-3, 0] = makeMappingArray(
self.N, self._segmentdata['red'], self._gamma)
self._lut[:-3, 1] = makeMappingArray(
self.N, self._segmentdata['green'], self._gamma)
self._lut[:-3, 2] = makeMappingArray(
self.N, self._segmentdata['blue'], self._gamma)
if 'alpha' in self._segmentdata:
self._lut[:-3, 3] = makeMappingArray(
self.N, self._segmentdata['alpha'], 1)
self._isinit = True
self._set_extremes()
def set_gamma(self, gamma):
"""
Set a new gamma value and regenerate color map.
"""
self._gamma = gamma
self._init()
@staticmethod
def from_list(name, colors, N=256, gamma=1.0):
"""
Make a linear segmented colormap with *name* from a sequence
of *colors* which evenly transitions from colors[0] at val=0
to colors[-1] at val=1. *N* is the number of rgb quantization
levels.
Alternatively, a list of (value, color) tuples can be given
to divide the range unevenly.
"""
if not np.iterable(colors):
raise ValueError('colors must be iterable')
if (isinstance(colors[0], Sized) and len(colors[0]) == 2
and not isinstance(colors[0], str)):
# List of value, color pairs
vals, colors = zip(*colors)
else:
vals = np.linspace(0, 1, len(colors))
cdict = dict(red=[], green=[], blue=[], alpha=[])
for val, color in zip(vals, colors):
r, g, b, a = to_rgba(color)
cdict['red'].append((val, r, r))
cdict['green'].append((val, g, g))
cdict['blue'].append((val, b, b))
cdict['alpha'].append((val, a, a))
return LinearSegmentedColormap(name, cdict, N, gamma)
def _resample(self, lutsize):
"""
Return a new color map with *lutsize* entries.
"""
return LinearSegmentedColormap(self.name, self._segmentdata, lutsize)
def reversed(self, name=None):
"""
Make a reversed instance of the Colormap.
Parameters
----------
name : str, optional
The name for the reversed colormap. If it's None the
name will be the name of the parent colormap + "_r".
Returns
-------
LinearSegmentedColormap
The reversed colormap.
"""
if name is None:
name = self.name + "_r"
# Function factory needed to deal with 'late binding' issue.
def factory(dat):
def func_r(x):
return dat(1.0 - x)
return func_r
data_r = {key: (factory(data) if callable(data) else
[(1.0 - x, y1, y0) for x, y0, y1 in reversed(data)])
for key, data in self._segmentdata.items()}
return LinearSegmentedColormap(name, data_r, self.N, self._gamma)
class ListedColormap(Colormap):
"""
Colormap object generated from a list of colors.
This may be most useful when indexing directly into a colormap,
but it can also be used to generate special colormaps for ordinary
mapping.
Parameters
----------
colors : list, array
List of Matplotlib color specifications, or an equivalent Nx3 or Nx4
floating point array (*N* rgb or rgba values).
name : str, optional
String to identify the colormap.
N : int, optional
Number of entries in the map. The default is *None*, in which case
there is one colormap entry for each element in the list of colors.
If::
N < len(colors)
the list will be truncated at *N*. If::
N > len(colors)
the list will be extended by repetition.
"""
def __init__(self, colors, name='from_list', N=None):
self.monochrome = False # True only if all colors in map are
# identical; needed for contouring.
if N is None:
self.colors = colors
N = len(colors)
else:
if isinstance(colors, str):
self.colors = [colors] * N
self.monochrome = True
elif np.iterable(colors):
if len(colors) == 1:
self.monochrome = True
self.colors = list(
itertools.islice(itertools.cycle(colors), N))
else:
try:
gray = float(colors)
except TypeError:
pass
else:
self.colors = [gray] * N
self.monochrome = True
Colormap.__init__(self, name, N)
def _init(self):
self._lut = np.zeros((self.N + 3, 4), float)
self._lut[:-3] = to_rgba_array(self.colors)
self._isinit = True
self._set_extremes()
def _resample(self, lutsize):
"""
Return a new color map with *lutsize* entries.
"""
colors = self(np.linspace(0, 1, lutsize))
return ListedColormap(colors, name=self.name)
def reversed(self, name=None):
"""
Make a reversed instance of the Colormap.
Parameters
----------
name : str, optional
The name for the reversed colormap. If it's None the
name will be the name of the parent colormap + "_r".
Returns
-------
ListedColormap
A reversed instance of the colormap.
"""
if name is None:
name = self.name + "_r"
colors_r = list(reversed(self.colors))
return ListedColormap(colors_r, name=name, N=self.N)
class Normalize(object):
"""
A class which, when called, can normalize data into
the ``[0.0, 1.0]`` interval.
"""
def __init__(self, vmin=None, vmax=None, clip=False):
"""
If *vmin* or *vmax* is not given, they are initialized from the
minimum and maximum value respectively of the first input
processed. That is, *__call__(A)* calls *autoscale_None(A)*.
If *clip* is *True* and the given value falls outside the range,
the returned value will be 0 or 1, whichever is closer.
Returns 0 if::
vmin==vmax
Works with scalars or arrays, including masked arrays. If
*clip* is *True*, masked values are set to 1; otherwise they
remain masked. Clipping silently defeats the purpose of setting
the over, under, and masked colors in the colormap, so it is
likely to lead to surprises; therefore the default is
*clip* = *False*.
"""
self.vmin = _sanitize_extrema(vmin)
self.vmax = _sanitize_extrema(vmax)
self.clip = clip
@staticmethod
def process_value(value):
"""
Homogenize the input *value* for easy and efficient normalization.
*value* can be a scalar or sequence.
Returns *result*, *is_scalar*, where *result* is a
masked array matching *value*. Float dtypes are preserved;
integer types with two bytes or smaller are converted to
np.float32, and larger types are converted to np.float64.
Preserving float32 when possible, and using in-place operations,
can greatly improve speed for large arrays.
Experimental; we may want to add an option to force the
use of float32.
"""
is_scalar = not np.iterable(value)
if is_scalar:
value = [value]
dtype = np.min_scalar_type(value)
if np.issubdtype(dtype, np.integer) or dtype.type is np.bool_:
# bool_/int8/int16 -> float32; int32/int64 -> float64
dtype = np.promote_types(dtype, np.float32)
# ensure data passed in as an ndarray subclass are interpreted as
# an ndarray. See issue #6622.
mask = np.ma.getmask(value)
data = np.asarray(np.ma.getdata(value))
result = np.ma.array(data, mask=mask, dtype=dtype, copy=True)
return result, is_scalar
def __call__(self, value, clip=None):
"""
Normalize *value* data in the ``[vmin, vmax]`` interval into
the ``[0.0, 1.0]`` interval and return it. *clip* defaults
to *self.clip* (which defaults to *False*). If not already
initialized, *vmin* and *vmax* are initialized using
*autoscale_None(value)*.
"""
if clip is None:
clip = self.clip
result, is_scalar = self.process_value(value)
self.autoscale_None(result)
# Convert at least to float, without losing precision.
(vmin,), _ = self.process_value(self.vmin)
(vmax,), _ = self.process_value(self.vmax)
if vmin == vmax:
result.fill(0) # Or should it be all masked? Or 0.5?
elif vmin > vmax:
raise ValueError("minvalue must be less than or equal to maxvalue")
else:
if clip:
mask = np.ma.getmask(result)
result = np.ma.array(np.clip(result.filled(vmax), vmin, vmax),
mask=mask)
# ma division is very slow; we can take a shortcut
resdat = result.data
resdat -= vmin
resdat /= (vmax - vmin)
result = np.ma.array(resdat, mask=result.mask, copy=False)
if is_scalar:
result = result[0]
return result
def inverse(self, value):
if not self.scaled():
raise ValueError("Not invertible until scaled")
(vmin,), _ = self.process_value(self.vmin)
(vmax,), _ = self.process_value(self.vmax)
if np.iterable(value):
val = np.ma.asarray(value)
return vmin + val * (vmax - vmin)
else:
return vmin + value * (vmax - vmin)
def autoscale(self, A):
"""Set *vmin*, *vmax* to min, max of *A*."""
A = np.asanyarray(A)
self.vmin = A.min()
self.vmax = A.max()
def autoscale_None(self, A):
"""Autoscale only None-valued vmin or vmax."""
A = np.asanyarray(A)
if self.vmin is None and A.size:
self.vmin = A.min()
if self.vmax is None and A.size:
self.vmax = A.max()
def scaled(self):
"""Return whether vmin and vmax are set."""
return self.vmin is not None and self.vmax is not None
class DivergingNorm(Normalize):
def __init__(self, vcenter, vmin=None, vmax=None):
"""
Normalize data with a set center.
Useful when mapping data with an unequal rates of change around a
conceptual center, e.g., data that range from -2 to 4, with 0 as
the midpoint.
Parameters
----------
vcenter : float
The data value that defines ``0.5`` in the normalization.
vmin : float, optional
The data value that defines ``0.0`` in the normalization.
Defaults to the min value of the dataset.
vmax : float, optional
The data value that defines ``1.0`` in the normalization.
Defaults to the the max value of the dataset.
Examples
--------
This maps data value -4000 to 0., 0 to 0.5, and +10000 to 1.0; data
between is linearly interpolated::
>>> import matplotlib.colors as mcolors
>>> offset = mcolors.DivergingNorm(vmin=-4000.,
vcenter=0., vmax=10000)
>>> data = [-4000., -2000., 0., 2500., 5000., 7500., 10000.]
>>> offset(data)
array([0., 0.25, 0.5, 0.625, 0.75, 0.875, 1.0])
"""
self.vcenter = vcenter
self.vmin = vmin
self.vmax = vmax
if vcenter is not None and vmax is not None and vcenter >= vmax:
raise ValueError('vmin, vcenter, and vmax must be in '
'ascending order')
if vcenter is not None and vmin is not None and vcenter <= vmin:
raise ValueError('vmin, vcenter, and vmax must be in '
'ascending order')
def autoscale_None(self, A):
"""
Get vmin and vmax, and then clip at vcenter
"""
super().autoscale_None(A)
if self.vmin > self.vcenter:
self.vmin = self.vcenter
if self.vmax < self.vcenter:
self.vmax = self.vcenter
def __call__(self, value, clip=None):
"""
Map value to the interval [0, 1]. The clip argument is unused.
"""
result, is_scalar = self.process_value(value)
self.autoscale_None(result) # sets self.vmin, self.vmax if None
if not self.vmin <= self.vcenter <= self.vmax:
raise ValueError("vmin, vcenter, vmax must increase monotonically")
result = np.ma.masked_array(
np.interp(result, [self.vmin, self.vcenter, self.vmax],
[0, 0.5, 1.]), mask=np.ma.getmask(result))
if is_scalar:
result = np.atleast_1d(result)[0]
return result
class LogNorm(Normalize):
"""Normalize a given value to the 0-1 range on a log scale."""
def _check_vmin_vmax(self):
if self.vmin > self.vmax:
raise ValueError("minvalue must be less than or equal to maxvalue")
elif self.vmin <= 0:
raise ValueError("minvalue must be positive")
def __call__(self, value, clip=None):
if clip is None:
clip = self.clip
result, is_scalar = self.process_value(value)
result = np.ma.masked_less_equal(result, 0, copy=False)
self.autoscale_None(result)
self._check_vmin_vmax()
vmin, vmax = self.vmin, self.vmax
if vmin == vmax:
result.fill(0)
else:
if clip:
mask = np.ma.getmask(result)
result = np.ma.array(np.clip(result.filled(vmax), vmin, vmax),
mask=mask)
# in-place equivalent of above can be much faster
resdat = result.data
mask = result.mask
if mask is np.ma.nomask:
mask = (resdat <= 0)
else:
mask |= resdat <= 0
np.copyto(resdat, 1, where=mask)
np.log(resdat, resdat)
resdat -= np.log(vmin)
resdat /= (np.log(vmax) - np.log(vmin))
result = np.ma.array(resdat, mask=mask, copy=False)
if is_scalar:
result = result[0]
return result
def inverse(self, value):
if not self.scaled():
raise ValueError("Not invertible until scaled")
self._check_vmin_vmax()
vmin, vmax = self.vmin, self.vmax
if np.iterable(value):
val = np.ma.asarray(value)
return vmin * np.ma.power((vmax / vmin), val)
else:
return vmin * pow((vmax / vmin), value)
def autoscale(self, A):
# docstring inherited.
super().autoscale(np.ma.masked_less_equal(A, 0, copy=False))
def autoscale_None(self, A):
# docstring inherited.
super().autoscale_None(np.ma.masked_less_equal(A, 0, copy=False))
class SymLogNorm(Normalize):
"""
The symmetrical logarithmic scale is logarithmic in both the
positive and negative directions from the origin.
Since the values close to zero tend toward infinity, there is a
need to have a range around zero that is linear. The parameter
*linthresh* allows the user to specify the size of this range
(-*linthresh*, *linthresh*).
"""
def __init__(self, linthresh, linscale=1.0,
vmin=None, vmax=None, clip=False):
"""
*linthresh*:
The range within which the plot is linear (to
avoid having the plot go to infinity around zero).
*linscale*:
This allows the linear range (-*linthresh* to *linthresh*)
to be stretched relative to the logarithmic range. Its
value is the number of decades to use for each half of the
linear range. For example, when *linscale* == 1.0 (the
default), the space used for the positive and negative
halves of the linear range will be equal to one decade in
the logarithmic range. Defaults to 1.
"""
Normalize.__init__(self, vmin, vmax, clip)
self.linthresh = float(linthresh)
self._linscale_adj = (linscale / (1.0 - np.e ** -1))
if vmin is not None and vmax is not None:
self._transform_vmin_vmax()
def __call__(self, value, clip=None):
if clip is None:
clip = self.clip
result, is_scalar = self.process_value(value)
self.autoscale_None(result)
vmin, vmax = self.vmin, self.vmax
if vmin > vmax:
raise ValueError("minvalue must be less than or equal to maxvalue")
elif vmin == vmax:
result.fill(0)
else:
if clip:
mask = np.ma.getmask(result)
result = np.ma.array(np.clip(result.filled(vmax), vmin, vmax),
mask=mask)
# in-place equivalent of above can be much faster
resdat = self._transform(result.data)
resdat -= self._lower
resdat /= (self._upper - self._lower)
if is_scalar:
result = result[0]
return result
def _transform(self, a):
"""Inplace transformation."""
with np.errstate(invalid="ignore"):
masked = np.abs(a) > self.linthresh
sign = np.sign(a[masked])
log = (self._linscale_adj + np.log(np.abs(a[masked]) / self.linthresh))
log *= sign * self.linthresh
a[masked] = log
a[~masked] *= self._linscale_adj
return a
def _inv_transform(self, a):
"""Inverse inplace Transformation."""
masked = np.abs(a) > (self.linthresh * self._linscale_adj)
sign = np.sign(a[masked])
exp = np.exp(sign * a[masked] / self.linthresh - self._linscale_adj)
exp *= sign * self.linthresh
a[masked] = exp
a[~masked] /= self._linscale_adj
return a
def _transform_vmin_vmax(self):
"""Calculates vmin and vmax in the transformed system."""
vmin, vmax = self.vmin, self.vmax
arr = np.array([vmax, vmin]).astype(float)
self._upper, self._lower = self._transform(arr)
def inverse(self, value):
if not self.scaled():
raise ValueError("Not invertible until scaled")
val = np.ma.asarray(value)
val = val * (self._upper - self._lower) + self._lower
return self._inv_transform(val)
def autoscale(self, A):
# docstring inherited.
super().autoscale(A)
self._transform_vmin_vmax()
def autoscale_None(self, A):
# docstring inherited.
super().autoscale_None(A)
self._transform_vmin_vmax()
class PowerNorm(Normalize):
"""
Linearly map a given value to the 0-1 range and then apply
a power-law normalization over that range.
"""
def __init__(self, gamma, vmin=None, vmax=None, clip=False):
Normalize.__init__(self, vmin, vmax, clip)
self.gamma = gamma
def __call__(self, value, clip=None):
if clip is None:
clip = self.clip
result, is_scalar = self.process_value(value)
self.autoscale_None(result)
gamma = self.gamma
vmin, vmax = self.vmin, self.vmax
if vmin > vmax:
raise ValueError("minvalue must be less than or equal to maxvalue")
elif vmin == vmax:
result.fill(0)
else:
if clip:
mask = np.ma.getmask(result)
result = np.ma.array(np.clip(result.filled(vmax), vmin, vmax),
mask=mask)
resdat = result.data
resdat -= vmin
resdat[resdat < 0] = 0
np.power(resdat, gamma, resdat)
resdat /= (vmax - vmin) ** gamma
result = np.ma.array(resdat, mask=result.mask, copy=False)
if is_scalar:
result = result[0]
return result
def inverse(self, value):
if not self.scaled():
raise ValueError("Not invertible until scaled")
gamma = self.gamma
vmin, vmax = self.vmin, self.vmax
if np.iterable(value):
val = np.ma.asarray(value)
return np.ma.power(val, 1. / gamma) * (vmax - vmin) + vmin
else:
return pow(value, 1. / gamma) * (vmax - vmin) + vmin
class BoundaryNorm(Normalize):
"""
Generate a colormap index based on discrete intervals.
Unlike `Normalize` or `LogNorm`, `BoundaryNorm` maps values to integers
instead of to the interval 0-1.
Mapping to the 0-1 interval could have been done via piece-wise linear
interpolation, but using integers seems simpler, and reduces the number of
conversions back and forth between integer and floating point.
"""
def __init__(self, boundaries, ncolors, clip=False):
"""
Parameters
----------
boundaries : array-like
Monotonically increasing sequence of boundaries
ncolors : int
Number of colors in the colormap to be used
clip : bool, optional
If clip is ``True``, out of range values are mapped to 0 if they
are below ``boundaries[0]`` or mapped to ncolors - 1 if they are
above ``boundaries[-1]``.
If clip is ``False``, out of range values are mapped to -1 if
they are below ``boundaries[0]`` or mapped to ncolors if they are
above ``boundaries[-1]``. These are then converted to valid indices
by :meth:`Colormap.__call__`.
Notes
-----
*boundaries* defines the edges of bins, and data falling within a bin
is mapped to the color with the same index.
If the number of bins doesn't equal *ncolors*, the color is chosen
by linear interpolation of the bin number onto color numbers.
"""
self.clip = clip
self.vmin = boundaries[0]
self.vmax = boundaries[-1]
self.boundaries = np.asarray(boundaries)
self.N = len(self.boundaries)
self.Ncmap = ncolors
if self.N - 1 == self.Ncmap:
self._interp = False
else:
self._interp = True
def __call__(self, value, clip=None):
if clip is None:
clip = self.clip
xx, is_scalar = self.process_value(value)
mask = np.ma.getmaskarray(xx)
xx = np.atleast_1d(xx.filled(self.vmax + 1))
if clip:
np.clip(xx, self.vmin, self.vmax, out=xx)
max_col = self.Ncmap - 1
else:
max_col = self.Ncmap
iret = np.zeros(xx.shape, dtype=np.int16)
for i, b in enumerate(self.boundaries):
iret[xx >= b] = i
if self._interp:
scalefac = (self.Ncmap - 1) / (self.N - 2)
iret = (iret * scalefac).astype(np.int16)
iret[xx < self.vmin] = -1
iret[xx >= self.vmax] = max_col
ret = np.ma.array(iret, mask=mask)
if is_scalar:
ret = int(ret[0]) # assume python scalar
return ret
def inverse(self, value):
"""
Raises
------
ValueError
BoundaryNorm is not invertible, so calling this method will always
raise an error
"""
return ValueError("BoundaryNorm is not invertible")
class NoNorm(Normalize):
"""
Dummy replacement for `Normalize`, for the case where we want to use
indices directly in a `~matplotlib.cm.ScalarMappable`.
"""
def __call__(self, value, clip=None):
return value
def inverse(self, value):
return value
def rgb_to_hsv(arr):
"""
Convert float rgb values (in the range [0, 1]), in a numpy array to hsv
values.
Parameters
----------
arr : (..., 3) array-like
All values must be in the range [0, 1]
Returns
-------
hsv : (..., 3) ndarray
Colors converted to hsv values in range [0, 1]
"""
arr = np.asarray(arr)
# check length of the last dimension, should be _some_ sort of rgb
if arr.shape[-1] != 3:
raise ValueError("Last dimension of input array must be 3; "
"shape {} was found.".format(arr.shape))
in_shape = arr.shape
arr = np.array(
arr, copy=False,
dtype=np.promote_types(arr.dtype, np.float32), # Don't work on ints.
ndmin=2, # In case input was 1D.
)
out = np.zeros_like(arr)
arr_max = arr.max(-1)
ipos = arr_max > 0
delta = arr.ptp(-1)
s = np.zeros_like(delta)
s[ipos] = delta[ipos] / arr_max[ipos]
ipos = delta > 0
# red is max
idx = (arr[..., 0] == arr_max) & ipos
out[idx, 0] = (arr[idx, 1] - arr[idx, 2]) / delta[idx]
# green is max
idx = (arr[..., 1] == arr_max) & ipos
out[idx, 0] = 2. + (arr[idx, 2] - arr[idx, 0]) / delta[idx]
# blue is max
idx = (arr[..., 2] == arr_max) & ipos
out[idx, 0] = 4. + (arr[idx, 0] - arr[idx, 1]) / delta[idx]
out[..., 0] = (out[..., 0] / 6.0) % 1.0
out[..., 1] = s
out[..., 2] = arr_max
return out.reshape(in_shape)
def hsv_to_rgb(hsv):
"""
Convert hsv values to rgb.
Parameters
----------
hsv : (..., 3) array-like
All values assumed to be in range [0, 1]
Returns
-------
rgb : (..., 3) ndarray
Colors converted to RGB values in range [0, 1]
"""
hsv = np.asarray(hsv)
# check length of the last dimension, should be _some_ sort of rgb
if hsv.shape[-1] != 3:
raise ValueError("Last dimension of input array must be 3; "
"shape {shp} was found.".format(shp=hsv.shape))
in_shape = hsv.shape
hsv = np.array(
hsv, copy=False,
dtype=np.promote_types(hsv.dtype, np.float32), # Don't work on ints.
ndmin=2, # In case input was 1D.
)
h = hsv[..., 0]
s = hsv[..., 1]
v = hsv[..., 2]
r = np.empty_like(h)
g = np.empty_like(h)
b = np.empty_like(h)
i = (h * 6.0).astype(int)
f = (h * 6.0) - i
p = v * (1.0 - s)
q = v * (1.0 - s * f)
t = v * (1.0 - s * (1.0 - f))
idx = i % 6 == 0
r[idx] = v[idx]
g[idx] = t[idx]
b[idx] = p[idx]
idx = i == 1
r[idx] = q[idx]
g[idx] = v[idx]
b[idx] = p[idx]
idx = i == 2
r[idx] = p[idx]
g[idx] = v[idx]
b[idx] = t[idx]
idx = i == 3
r[idx] = p[idx]
g[idx] = q[idx]
b[idx] = v[idx]
idx = i == 4
r[idx] = t[idx]
g[idx] = p[idx]
b[idx] = v[idx]
idx = i == 5
r[idx] = v[idx]
g[idx] = p[idx]
b[idx] = q[idx]
idx = s == 0
r[idx] = v[idx]
g[idx] = v[idx]
b[idx] = v[idx]
rgb = np.stack([r, g, b], axis=-1)
return rgb.reshape(in_shape)
def _vector_magnitude(arr):
# things that don't work here:
# * np.linalg.norm
# - doesn't broadcast in numpy 1.7
# - drops the mask from ma.array
# * using keepdims - broken on ma.array until 1.11.2
# * using sum - discards mask on ma.array unless entire vector is masked
sum_sq = 0
for i in range(arr.shape[-1]):
sum_sq += np.square(arr[..., i, np.newaxis])
return np.sqrt(sum_sq)
class LightSource(object):
"""
Create a light source coming from the specified azimuth and elevation.
Angles are in degrees, with the azimuth measured
clockwise from north and elevation up from the zero plane of the surface.
The :meth:`shade` is used to produce "shaded" rgb values for a data array.
:meth:`shade_rgb` can be used to combine an rgb image with
The :meth:`shade_rgb`
The :meth:`hillshade` produces an illumination map of a surface.
"""
def __init__(self, azdeg=315, altdeg=45, hsv_min_val=0, hsv_max_val=1,
hsv_min_sat=1, hsv_max_sat=0):
"""
Specify the azimuth (measured clockwise from south) and altitude
(measured up from the plane of the surface) of the light source
in degrees.
Parameters
----------
azdeg : number, optional
The azimuth (0-360, degrees clockwise from North) of the light
source. Defaults to 315 degrees (from the northwest).
altdeg : number, optional
The altitude (0-90, degrees up from horizontal) of the light
source. Defaults to 45 degrees from horizontal.
Notes
-----
For backwards compatibility, the parameters *hsv_min_val*,
*hsv_max_val*, *hsv_min_sat*, and *hsv_max_sat* may be supplied at
initialization as well. However, these parameters will only be used if
"blend_mode='hsv'" is passed into :meth:`shade` or :meth:`shade_rgb`.
See the documentation for :meth:`blend_hsv` for more details.
"""
self.azdeg = azdeg
self.altdeg = altdeg
self.hsv_min_val = hsv_min_val
self.hsv_max_val = hsv_max_val
self.hsv_min_sat = hsv_min_sat
self.hsv_max_sat = hsv_max_sat
@property
def direction(self):
"""The unit vector direction towards the light source."""
# Azimuth is in degrees clockwise from North. Convert to radians
# counterclockwise from East (mathematical notation).
az = np.radians(90 - self.azdeg)
alt = np.radians(self.altdeg)
return np.array([
np.cos(az) * np.cos(alt),
np.sin(az) * np.cos(alt),
np.sin(alt)
])
def hillshade(self, elevation, vert_exag=1, dx=1, dy=1, fraction=1.):
"""
Calculates the illumination intensity for a surface using the defined
azimuth and elevation for the light source.
This computes the normal vectors for the surface, and then passes them
on to `shade_normals`
Parameters
----------
elevation : array-like
A 2d array (or equivalent) of the height values used to generate an
illumination map
vert_exag : number, optional
The amount to exaggerate the elevation values by when calculating
illumination. This can be used either to correct for differences in
units between the x-y coordinate system and the elevation
coordinate system (e.g. decimal degrees vs meters) or to exaggerate
or de-emphasize topographic effects.
dx : number, optional
The x-spacing (columns) of the input *elevation* grid.
dy : number, optional
The y-spacing (rows) of the input *elevation* grid.
fraction : number, optional
Increases or decreases the contrast of the hillshade. Values
greater than one will cause intermediate values to move closer to
full illumination or shadow (and clipping any values that move
beyond 0 or 1). Note that this is not visually or mathematically
the same as vertical exaggeration.
Returns
-------
intensity : ndarray
A 2d array of illumination values between 0-1, where 0 is
completely in shadow and 1 is completely illuminated.
"""
# Because most image and raster GIS data has the first row in the array
# as the "top" of the image, dy is implicitly negative. This is
# consistent to what `imshow` assumes, as well.
dy = -dy
# compute the normal vectors from the partial derivatives
e_dy, e_dx = np.gradient(vert_exag * elevation, dy, dx)
# .view is to keep subclasses
normal = np.empty(elevation.shape + (3,)).view(type(elevation))
normal[..., 0] = -e_dx
normal[..., 1] = -e_dy
normal[..., 2] = 1
normal /= _vector_magnitude(normal)
return self.shade_normals(normal, fraction)
def shade_normals(self, normals, fraction=1.):
"""
Calculates the illumination intensity for the normal vectors of a
surface using the defined azimuth and elevation for the light source.
Imagine an artificial sun placed at infinity in some azimuth and
elevation position illuminating our surface. The parts of the surface
that slope toward the sun should brighten while those sides facing away
should become darker.
Parameters
----------
fraction : number, optional
Increases or decreases the contrast of the hillshade. Values
greater than one will cause intermediate values to move closer to
full illumination or shadow (and clipping any values that move
beyond 0 or 1). Note that this is not visually or mathematically
the same as vertical exaggeration.
Returns
-------
intensity : ndarray
A 2d array of illumination values between 0-1, where 0 is
completely in shadow and 1 is completely illuminated.
"""
intensity = normals.dot(self.direction)
# Apply contrast stretch
imin, imax = intensity.min(), intensity.max()
intensity *= fraction
# Rescale to 0-1, keeping range before contrast stretch
# If constant slope, keep relative scaling (i.e. flat should be 0.5,
# fully occluded 0, etc.)
if (imax - imin) > 1e-6:
# Strictly speaking, this is incorrect. Negative values should be
# clipped to 0 because they're fully occluded. However, rescaling
# in this manner is consistent with the previous implementation and
# visually appears better than a "hard" clip.
intensity -= imin
intensity /= (imax - imin)
intensity = np.clip(intensity, 0, 1, intensity)
return intensity
def shade(self, data, cmap, norm=None, blend_mode='overlay', vmin=None,
vmax=None, vert_exag=1, dx=1, dy=1, fraction=1, **kwargs):
"""
Combine colormapped data values with an illumination intensity map
(a.k.a. "hillshade") of the values.
Parameters
----------
data : array-like
A 2d array (or equivalent) of the height values used to generate a
shaded map.
cmap : `~matplotlib.colors.Colormap` instance
The colormap used to color the *data* array. Note that this must be
a `~matplotlib.colors.Colormap` instance. For example, rather than
passing in `cmap='gist_earth'`, use
`cmap=plt.get_cmap('gist_earth')` instead.
norm : `~matplotlib.colors.Normalize` instance, optional
The normalization used to scale values before colormapping. If
None, the input will be linearly scaled between its min and max.
blend_mode : {'hsv', 'overlay', 'soft'} or callable, optional
The type of blending used to combine the colormapped data
values with the illumination intensity. Default is
"overlay". Note that for most topographic surfaces,
"overlay" or "soft" appear more visually realistic. If a
user-defined function is supplied, it is expected to
combine an MxNx3 RGB array of floats (ranging 0 to 1) with
an MxNx1 hillshade array (also 0 to 1). (Call signature
`func(rgb, illum, **kwargs)`) Additional kwargs supplied
to this function will be passed on to the *blend_mode*
function.
vmin : scalar or None, optional
The minimum value used in colormapping *data*. If *None* the
minimum value in *data* is used. If *norm* is specified, then this
argument will be ignored.
vmax : scalar or None, optional
The maximum value used in colormapping *data*. If *None* the
maximum value in *data* is used. If *norm* is specified, then this
argument will be ignored.
vert_exag : number, optional
The amount to exaggerate the elevation values by when calculating
illumination. This can be used either to correct for differences in
units between the x-y coordinate system and the elevation
coordinate system (e.g. decimal degrees vs meters) or to exaggerate
or de-emphasize topography.
dx : number, optional
The x-spacing (columns) of the input *elevation* grid.
dy : number, optional
The y-spacing (rows) of the input *elevation* grid.
fraction : number, optional
Increases or decreases the contrast of the hillshade. Values
greater than one will cause intermediate values to move closer to
full illumination or shadow (and clipping any values that move
beyond 0 or 1). Note that this is not visually or mathematically
the same as vertical exaggeration.
Additional kwargs are passed on to the *blend_mode* function.
Returns
-------
rgba : ndarray
An MxNx4 array of floats ranging between 0-1.
"""
if vmin is None:
vmin = data.min()
if vmax is None:
vmax = data.max()
if norm is None:
norm = Normalize(vmin=vmin, vmax=vmax)
rgb0 = cmap(norm(data))
rgb1 = self.shade_rgb(rgb0, elevation=data, blend_mode=blend_mode,
vert_exag=vert_exag, dx=dx, dy=dy,
fraction=fraction, **kwargs)
# Don't overwrite the alpha channel, if present.
rgb0[..., :3] = rgb1[..., :3]
return rgb0
def shade_rgb(self, rgb, elevation, fraction=1., blend_mode='hsv',
vert_exag=1, dx=1, dy=1, **kwargs):
"""
Use this light source to adjust the colors of the *rgb* input array to
give the impression of a shaded relief map with the given `elevation`.
Parameters
----------
rgb : array-like
An (M, N, 3) RGB array, assumed to be in the range of 0 to 1.
elevation : array-like
An (M, N) array of the height values used to generate a shaded map.
fraction : number
Increases or decreases the contrast of the hillshade. Values
greater than one will cause intermediate values to move closer to
full illumination or shadow (and clipping any values that move
beyond 0 or 1). Note that this is not visually or mathematically
the same as vertical exaggeration.
blend_mode : {'hsv', 'overlay', 'soft'} or callable, optional
The type of blending used to combine the colormapped data values
with the illumination intensity. For backwards compatibility, this
defaults to "hsv". Note that for most topographic surfaces,
"overlay" or "soft" appear more visually realistic. If a
user-defined function is supplied, it is expected to combine an
MxNx3 RGB array of floats (ranging 0 to 1) with an MxNx1 hillshade
array (also 0 to 1). (Call signature `func(rgb, illum, **kwargs)`)
Additional kwargs supplied to this function will be passed on to
the *blend_mode* function.
vert_exag : number, optional
The amount to exaggerate the elevation values by when calculating
illumination. This can be used either to correct for differences in
units between the x-y coordinate system and the elevation
coordinate system (e.g. decimal degrees vs meters) or to exaggerate
or de-emphasize topography.
dx : number, optional
The x-spacing (columns) of the input *elevation* grid.
dy : number, optional
The y-spacing (rows) of the input *elevation* grid.
Additional kwargs are passed on to the *blend_mode* function.
Returns
-------
shaded_rgb : ndarray
An (m, n, 3) array of floats ranging between 0-1.
"""
# Calculate the "hillshade" intensity.
intensity = self.hillshade(elevation, vert_exag, dx, dy, fraction)
intensity = intensity[..., np.newaxis]
# Blend the hillshade and rgb data using the specified mode
lookup = {
'hsv': self.blend_hsv,
'soft': self.blend_soft_light,
'overlay': self.blend_overlay,
}
if blend_mode in lookup:
blend = lookup[blend_mode](rgb, intensity, **kwargs)
else:
try:
blend = blend_mode(rgb, intensity, **kwargs)
except TypeError:
raise ValueError('"blend_mode" must be callable or one of {}'
.format(lookup.keys))
# Only apply result where hillshade intensity isn't masked
if hasattr(intensity, 'mask'):
mask = intensity.mask[..., 0]
for i in range(3):
blend[..., i][mask] = rgb[..., i][mask]
return blend
def blend_hsv(self, rgb, intensity, hsv_max_sat=None, hsv_max_val=None,
hsv_min_val=None, hsv_min_sat=None):
"""
Take the input data array, convert to HSV values in the given colormap,
then adjust those color values to give the impression of a shaded
relief map with a specified light source. RGBA values are returned,
which can then be used to plot the shaded image with imshow.
The color of the resulting image will be darkened by moving the (s,v)
values (in hsv colorspace) toward (hsv_min_sat, hsv_min_val) in the
shaded regions, or lightened by sliding (s,v) toward (hsv_max_sat
hsv_max_val) in regions that are illuminated. The default extremes are
chose so that completely shaded points are nearly black (s = 1, v = 0)
and completely illuminated points are nearly white (s = 0, v = 1).
Parameters
----------
rgb : ndarray
An MxNx3 RGB array of floats ranging from 0 to 1 (color image).
intensity : ndarray
An MxNx1 array of floats ranging from 0 to 1 (grayscale image).
hsv_max_sat : number, optional
The maximum saturation value that the *intensity* map can shift the
output image to. Defaults to 1.
hsv_min_sat : number, optional
The minimum saturation value that the *intensity* map can shift the
output image to. Defaults to 0.
hsv_max_val : number, optional
The maximum value ("v" in "hsv") that the *intensity* map can shift
the output image to. Defaults to 1.
hsv_min_val : number, optional
The minimum value ("v" in "hsv") that the *intensity* map can shift
the output image to. Defaults to 0.
Returns
-------
rgb : ndarray
An MxNx3 RGB array representing the combined images.
"""
# Backward compatibility...
if hsv_max_sat is None:
hsv_max_sat = self.hsv_max_sat
if hsv_max_val is None:
hsv_max_val = self.hsv_max_val
if hsv_min_sat is None:
hsv_min_sat = self.hsv_min_sat
if hsv_min_val is None:
hsv_min_val = self.hsv_min_val
# Expects a 2D intensity array scaled between -1 to 1...
intensity = intensity[..., 0]
intensity = 2 * intensity - 1
# Convert to rgb, then rgb to hsv
hsv = rgb_to_hsv(rgb[:, :, 0:3])
hue, sat, val = np.moveaxis(hsv, -1, 0)
# Modify hsv values (in place) to simulate illumination.
# putmask(A, mask, B) <=> A[mask] = B[mask]
np.putmask(sat, (np.abs(sat) > 1.e-10) & (intensity > 0),
(1 - intensity) * sat + intensity * hsv_max_sat)
np.putmask(sat, (np.abs(sat) > 1.e-10) & (intensity < 0),
(1 + intensity) * sat - intensity * hsv_min_sat)
np.putmask(val, intensity > 0,
(1 - intensity) * val + intensity * hsv_max_val)
np.putmask(val, intensity < 0,
(1 + intensity) * val - intensity * hsv_min_val)
np.clip(hsv[:, :, 1:], 0, 1, out=hsv[:, :, 1:])
# Convert modified hsv back to rgb.
return hsv_to_rgb(hsv)
def blend_soft_light(self, rgb, intensity):
"""
Combines an rgb image with an intensity map using "soft light"
blending. Uses the "pegtop" formula.
Parameters
----------
rgb : ndarray
An MxNx3 RGB array of floats ranging from 0 to 1 (color image).
intensity : ndarray
An MxNx1 array of floats ranging from 0 to 1 (grayscale image).
Returns
-------
rgb : ndarray
An MxNx3 RGB array representing the combined images.
"""
return 2 * intensity * rgb + (1 - 2 * intensity) * rgb**2
def blend_overlay(self, rgb, intensity):
"""
Combines an rgb image with an intensity map using "overlay" blending.
Parameters
----------
rgb : ndarray
An MxNx3 RGB array of floats ranging from 0 to 1 (color image).
intensity : ndarray
An MxNx1 array of floats ranging from 0 to 1 (grayscale image).
Returns
-------
rgb : ndarray
An MxNx3 RGB array representing the combined images.
"""
low = 2 * intensity * rgb
high = 1 - 2 * (1 - intensity) * (1 - rgb)
return np.where(rgb <= 0.5, low, high)
def from_levels_and_colors(levels, colors, extend='neither'):
"""
A helper routine to generate a cmap and a norm instance which
behave similar to contourf's levels and colors arguments.
Parameters
----------
levels : sequence of numbers
The quantization levels used to construct the :class:`BoundaryNorm`.
Value ``v`` is quantized to level ``i`` if ``lev[i] <= v < lev[i+1]``.
colors : sequence of colors
The fill color to use for each level. If `extend` is "neither" there
must be ``n_level - 1`` colors. For an `extend` of "min" or "max" add
one extra color, and for an `extend` of "both" add two colors.
extend : {'neither', 'min', 'max', 'both'}, optional
The behaviour when a value falls out of range of the given levels.
See :func:`~matplotlib.pyplot.contourf` for details.
Returns
-------
(cmap, norm) : tuple containing a :class:`Colormap` and a \
:class:`Normalize` instance
"""
colors_i0 = 0
colors_i1 = None
if extend == 'both':
colors_i0 = 1
colors_i1 = -1
extra_colors = 2
elif extend == 'min':
colors_i0 = 1
extra_colors = 1
elif extend == 'max':
colors_i1 = -1
extra_colors = 1
elif extend == 'neither':
extra_colors = 0
else:
raise ValueError('Unexpected value for extend: {0!r}'.format(extend))
n_data_colors = len(levels) - 1
n_expected_colors = n_data_colors + extra_colors
if len(colors) != n_expected_colors:
raise ValueError('With extend == {0!r} and n_levels == {1!r} expected'
' n_colors == {2!r}. Got {3!r}.'
''.format(extend, len(levels), n_expected_colors,
len(colors)))
cmap = ListedColormap(colors[colors_i0:colors_i1], N=n_data_colors)
if extend in ['min', 'both']:
cmap.set_under(colors[0])
else:
cmap.set_under('none')
if extend in ['max', 'both']:
cmap.set_over(colors[-1])
else:
cmap.set_over('none')
cmap.colorbar_extend = extend
norm = BoundaryNorm(levels, ncolors=n_data_colors)
return cmap, norm
|
daf9b817119ef411c20b7097bddd74d0ca0f62f18ec072c5f0bcca4b3b05274a
|
# Original code by:
# John Gill <[email protected]>
# Copyright 2004 John Gill and John Hunter
#
# Subsequent changes:
# The Matplotlib development team
# Copyright The Matplotlib development team
"""
This module provides functionality to add a table to a plot.
Use the factory function `~matplotlib.table.table` to create a ready-made
table from texts. If you need more control, use the `.Table` class and its
methods.
The table consists of a grid of cells, which are indexed by (row, column).
The cell (0, 0) is positioned at the top left.
Thanks to John Gill for providing the class and table.
"""
from . import artist, cbook, docstring
from .artist import Artist, allow_rasterization
from .patches import Rectangle
from .text import Text
from .transforms import Bbox
from .path import Path
class Cell(Rectangle):
"""
A cell is a `.Rectangle` with some associated `.Text`.
.. note:
As a user, you'll most likely not creates cells yourself. Instead, you
should use either the `~matplotlib.table.table` factory function or
`.Table.add_cell`.
Parameters
----------
xy : 2-tuple
The position of the bottom left corner of the cell.
width : float
The cell width.
height : float
The cell height.
edgecolor : color spec
The color of the cell border.
facecolor : color spec
The cell facecolor.
fill : bool
Whether the cell background is filled.
text : str
The cell text.
loc : {'left', 'center', 'right'}, default: 'right'
The alignment of the text within the cell.
fontproperties : dict
A dict defining the font properties of the text. Supported keys and
values are the keyword arguments accepted by `.FontProperties`.
"""
PAD = 0.1
"""Padding between text and rectangle."""
def __init__(self, xy, width, height,
edgecolor='k', facecolor='w',
fill=True,
text='',
loc=None,
fontproperties=None
):
# Call base
Rectangle.__init__(self, xy, width=width, height=height, fill=fill,
edgecolor=edgecolor, facecolor=facecolor)
self.set_clip_on(False)
# Create text object
if loc is None:
loc = 'right'
self._loc = loc
self._text = Text(x=xy[0], y=xy[1], text=text,
fontproperties=fontproperties)
self._text.set_clip_on(False)
def set_transform(self, trans):
Rectangle.set_transform(self, trans)
# the text does not get the transform!
self.stale = True
def set_figure(self, fig):
Rectangle.set_figure(self, fig)
self._text.set_figure(fig)
def get_text(self):
"""Return the cell `.Text` instance."""
return self._text
def set_fontsize(self, size):
"""Set the text fontsize."""
self._text.set_fontsize(size)
self.stale = True
def get_fontsize(self):
"""Return the cell fontsize."""
return self._text.get_fontsize()
def auto_set_font_size(self, renderer):
"""Shrink font size until the text fits into the cell width."""
fontsize = self.get_fontsize()
required = self.get_required_width(renderer)
while fontsize > 1 and required > self.get_width():
fontsize -= 1
self.set_fontsize(fontsize)
required = self.get_required_width(renderer)
return fontsize
@allow_rasterization
def draw(self, renderer):
if not self.get_visible():
return
# draw the rectangle
Rectangle.draw(self, renderer)
# position the text
self._set_text_position(renderer)
self._text.draw(renderer)
self.stale = False
def _set_text_position(self, renderer):
"""Set text up so it draws in the right place.
Currently support 'left', 'center' and 'right'
"""
bbox = self.get_window_extent(renderer)
l, b, w, h = bbox.bounds
# draw in center vertically
self._text.set_verticalalignment('center')
y = b + (h / 2.0)
# now position horizontally
if self._loc == 'center':
self._text.set_horizontalalignment('center')
x = l + (w / 2.0)
elif self._loc == 'left':
self._text.set_horizontalalignment('left')
x = l + (w * self.PAD)
else:
self._text.set_horizontalalignment('right')
x = l + (w * (1.0 - self.PAD))
self._text.set_position((x, y))
def get_text_bounds(self, renderer):
"""
Return the text bounds as *(x, y, width, height)* in table coordinates.
"""
bbox = self._text.get_window_extent(renderer)
bboxa = bbox.inverse_transformed(self.get_data_transform())
return bboxa.bounds
def get_required_width(self, renderer):
"""Return the minimal required width for the cell."""
l, b, w, h = self.get_text_bounds(renderer)
return w * (1.0 + (2.0 * self.PAD))
@docstring.dedent_interpd
def set_text_props(self, **kwargs):
"""
Update the text properties.
Valid kwargs are
%(Text)s
"""
self._text.update(kwargs)
self.stale = True
class CustomCell(Cell):
"""
A `.Cell` subclass with configurable edge visibility.
"""
_edges = 'BRTL'
_edge_aliases = {'open': '',
'closed': _edges, # default
'horizontal': 'BT',
'vertical': 'RL'
}
def __init__(self, *args, visible_edges, **kwargs):
super().__init__(*args, **kwargs)
self.visible_edges = visible_edges
@property
def visible_edges(self):
"""
The cell edges to be drawn with a line.
Reading this property returns a substring of 'BRTL' (bottom, right,
top, left').
When setting this property, you can use a substring of 'BRTL' or one
of {'open', 'closed', 'horizontal', 'vertical'}.
"""
return self._visible_edges
@visible_edges.setter
def visible_edges(self, value):
if value is None:
self._visible_edges = self._edges
elif value in self._edge_aliases:
self._visible_edges = self._edge_aliases[value]
else:
if any(edge not in self._edges for edge in value):
raise ValueError('Invalid edge param {}, must only be one of '
'{} or string of {}'.format(
value,
", ".join(self._edge_aliases),
", ".join(self._edges)))
self._visible_edges = value
self.stale = True
def get_path(self):
"""Return a `.Path` for the `.visible_edges`."""
codes = [Path.MOVETO]
for edge in self._edges:
if edge in self._visible_edges:
codes.append(Path.LINETO)
else:
codes.append(Path.MOVETO)
if Path.MOVETO not in codes[1:]: # All sides are visible
codes[-1] = Path.CLOSEPOLY
return Path(
[[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0], [0.0, 0.0]],
codes,
readonly=True
)
class Table(Artist):
"""
A table of cells.
The table consists of a grid of cells, which are indexed by (row, column).
For a simple table, you'll have a full grid of cells with indices from
(0, 0) to (num_rows-1, num_cols-1), in which the cell (0, 0) is positioned
at the top left. However, you can also add cells with negative indices.
You don't have to add a cell to every grid position, so you can create
tables that have holes.
*Note*: You'll usually not create an empty table from scratch. Instead use
`~matplotlib.table.table` to create a table from data.
"""
codes = {'best': 0,
'upper right': 1, # default
'upper left': 2,
'lower left': 3,
'lower right': 4,
'center left': 5,
'center right': 6,
'lower center': 7,
'upper center': 8,
'center': 9,
'top right': 10,
'top left': 11,
'bottom left': 12,
'bottom right': 13,
'right': 14,
'left': 15,
'top': 16,
'bottom': 17,
}
"""Possible values where to place the table relative to the Axes."""
FONTSIZE = 10
AXESPAD = 0.02
"""The border between the Axes and the table edge in Axes units."""
def __init__(self, ax, loc=None, bbox=None, **kwargs):
"""
Parameters
----------
ax : `matplotlib.axes.Axes`
The `~.axes.Axes` to plot the table into.
loc : str
The position of the cell with respect to *ax*. This must be one of
the `~.Table.codes`.
bbox : `.Bbox` or None
A bounding box to draw the table into. If this is not *None*, this
overrides *loc*.
Other Parameters
----------------
**kwargs
`.Artist` properties.
"""
Artist.__init__(self)
if isinstance(loc, str):
if loc not in self.codes:
cbook.warn_deprecated(
"3.1", message="Unrecognized location {!r}. Falling back "
"on 'bottom'; valid locations are\n\t{}\n"
"This will raise an exception %(removal)s."
.format(loc, '\n\t'.join(self.codes)))
loc = 'bottom'
loc = self.codes[loc]
self.set_figure(ax.figure)
self._axes = ax
self._loc = loc
self._bbox = bbox
# use axes coords
self.set_transform(ax.transAxes)
self._cells = {}
self._edges = None
self._autoColumns = []
self._autoFontsize = True
self.update(kwargs)
self.set_clip_on(False)
def add_cell(self, row, col, *args, **kwargs):
"""
Create a cell and add it to the table.
Parameters
----------
row : int
Row index.
col : int
Column index.
*args, **kwargs
All other parameters are passed on to `Cell`.
Returns
-------
cell : `.CustomCell`
The created cell.
"""
xy = (0, 0)
cell = CustomCell(xy, visible_edges=self.edges, *args, **kwargs)
self[row, col] = cell
return cell
def __setitem__(self, position, cell):
"""
Set a custom cell in a given position.
"""
if not isinstance(cell, CustomCell):
raise TypeError('Table only accepts CustomCell')
try:
row, col = position[0], position[1]
except Exception:
raise KeyError('Only tuples length 2 are accepted as coordinates')
cell.set_figure(self.figure)
cell.set_transform(self.get_transform())
cell.set_clip_on(False)
self._cells[row, col] = cell
self.stale = True
def __getitem__(self, position):
"""Retrieve a custom cell from a given position."""
return self._cells[position]
@property
def edges(self):
"""
The default value of `~.CustomCell.visible_edges` for newly added
cells using `.add_cell`.
Notes
-----
This setting does currently only affect newly created cells using
`.add_cell`.
To change existing cells, you have to set their edges explicitly::
for c in tab.get_celld().values():
c.visible_edges = 'horizontal'
"""
return self._edges
@edges.setter
def edges(self, value):
self._edges = value
self.stale = True
def _approx_text_height(self):
return (self.FONTSIZE / 72.0 * self.figure.dpi /
self._axes.bbox.height * 1.2)
@allow_rasterization
def draw(self, renderer):
# docstring inherited
# Need a renderer to do hit tests on mouseevent; assume the last one
# will do
if renderer is None:
renderer = self.figure._cachedRenderer
if renderer is None:
raise RuntimeError('No renderer defined')
if not self.get_visible():
return
renderer.open_group('table')
self._update_positions(renderer)
for key in sorted(self._cells):
self._cells[key].draw(renderer)
renderer.close_group('table')
self.stale = False
def _get_grid_bbox(self, renderer):
"""Get a bbox, in axes co-ordinates for the cells.
Only include those in the range (0,0) to (maxRow, maxCol)"""
boxes = [cell.get_window_extent(renderer)
for (row, col), cell in self._cells.items()
if row >= 0 and col >= 0]
bbox = Bbox.union(boxes)
return bbox.inverse_transformed(self.get_transform())
def contains(self, mouseevent):
# docstring inherited
if self._contains is not None:
return self._contains(self, mouseevent)
# TODO: Return index of the cell containing the cursor so that the user
# doesn't have to bind to each one individually.
renderer = self.figure._cachedRenderer
if renderer is not None:
boxes = [cell.get_window_extent(renderer)
for (row, col), cell in self._cells.items()
if row >= 0 and col >= 0]
bbox = Bbox.union(boxes)
return bbox.contains(mouseevent.x, mouseevent.y), {}
else:
return False, {}
def get_children(self):
"""Return the Artists contained by the table."""
return list(self._cells.values())
get_child_artists = cbook.deprecated("3.0")(get_children)
def get_window_extent(self, renderer):
"""Return the bounding box of the table in window coords."""
boxes = [cell.get_window_extent(renderer)
for cell in self._cells.values()]
return Bbox.union(boxes)
def _do_cell_alignment(self):
"""
Calculate row heights and column widths; position cells accordingly.
"""
# Calculate row/column widths
widths = {}
heights = {}
for (row, col), cell in self._cells.items():
height = heights.setdefault(row, 0.0)
heights[row] = max(height, cell.get_height())
width = widths.setdefault(col, 0.0)
widths[col] = max(width, cell.get_width())
# work out left position for each column
xpos = 0
lefts = {}
for col in sorted(widths):
lefts[col] = xpos
xpos += widths[col]
ypos = 0
bottoms = {}
for row in sorted(heights, reverse=True):
bottoms[row] = ypos
ypos += heights[row]
# set cell positions
for (row, col), cell in self._cells.items():
cell.set_x(lefts[col])
cell.set_y(bottoms[row])
def auto_set_column_width(self, col):
"""
Automatically set the widths of given columns to optimal sizes.
Parameters
----------
col : int or sequence of ints
The indices of the columns to auto-scale.
"""
# check for col possibility on iteration
try:
iter(col)
except (TypeError, AttributeError):
self._autoColumns.append(col)
else:
for cell in col:
self._autoColumns.append(cell)
self.stale = True
def _auto_set_column_width(self, col, renderer):
"""Automatically set width for column."""
cells = [cell for key, cell in self._cells.items() if key[1] == col]
max_width = max((cell.get_required_width(renderer) for cell in cells),
default=0)
for cell in cells:
cell.set_width(max_width)
def auto_set_font_size(self, value=True):
"""Automatically set font size."""
self._autoFontsize = value
self.stale = True
def _auto_set_font_size(self, renderer):
if len(self._cells) == 0:
return
fontsize = next(iter(self._cells.values())).get_fontsize()
cells = []
for key, cell in self._cells.items():
# ignore auto-sized columns
if key[1] in self._autoColumns:
continue
size = cell.auto_set_font_size(renderer)
fontsize = min(fontsize, size)
cells.append(cell)
# now set all fontsizes equal
for cell in self._cells.values():
cell.set_fontsize(fontsize)
def scale(self, xscale, yscale):
"""Scale column widths by *xscale* and row heights by *yscale*."""
for c in self._cells.values():
c.set_width(c.get_width() * xscale)
c.set_height(c.get_height() * yscale)
def set_fontsize(self, size):
"""
Set the font size, in points, of the cell text.
Parameters
----------
size : float
Notes
-----
As long as auto font size has not been disabled, the value will be
clipped such that the text fits horizontally into the cell.
You can disable this behavior using `.auto_set_font_size`.
>>> the_table.auto_set_font_size(False)
>>> the_table.set_fontsize(20)
However, there is no automatic scaling of the row height so that the
text may exceed the cell boundary.
"""
for cell in self._cells.values():
cell.set_fontsize(size)
self.stale = True
def _offset(self, ox, oy):
"""Move all the artists by ox, oy (axes coords)."""
for c in self._cells.values():
x, y = c.get_x(), c.get_y()
c.set_x(x + ox)
c.set_y(y + oy)
def _update_positions(self, renderer):
# called from renderer to allow more precise estimates of
# widths and heights with get_window_extent
# Do any auto width setting
for col in self._autoColumns:
self._auto_set_column_width(col, renderer)
if self._autoFontsize:
self._auto_set_font_size(renderer)
# Align all the cells
self._do_cell_alignment()
bbox = self._get_grid_bbox(renderer)
l, b, w, h = bbox.bounds
if self._bbox is not None:
# Position according to bbox
rl, rb, rw, rh = self._bbox
self.scale(rw / w, rh / h)
ox = rl - l
oy = rb - b
self._do_cell_alignment()
else:
# Position using loc
(BEST, UR, UL, LL, LR, CL, CR, LC, UC, C,
TR, TL, BL, BR, R, L, T, B) = range(len(self.codes))
# defaults for center
ox = (0.5 - w / 2) - l
oy = (0.5 - h / 2) - b
if self._loc in (UL, LL, CL): # left
ox = self.AXESPAD - l
if self._loc in (BEST, UR, LR, R, CR): # right
ox = 1 - (l + w + self.AXESPAD)
if self._loc in (BEST, UR, UL, UC): # upper
oy = 1 - (b + h + self.AXESPAD)
if self._loc in (LL, LR, LC): # lower
oy = self.AXESPAD - b
if self._loc in (LC, UC, C): # center x
ox = (0.5 - w / 2) - l
if self._loc in (CL, CR, C): # center y
oy = (0.5 - h / 2) - b
if self._loc in (TL, BL, L): # out left
ox = - (l + w)
if self._loc in (TR, BR, R): # out right
ox = 1.0 - l
if self._loc in (TR, TL, T): # out top
oy = 1.0 - b
if self._loc in (BL, BR, B): # out bottom
oy = - (b + h)
self._offset(ox, oy)
def get_celld(self):
r"""
Return a dict of cells in the table mapping *(row, column)* to
`.Cell`\s.
Notes
-----
You can also directly index into the Table object to access individual
cells::
cell = table[row, col]
"""
return self._cells
docstring.interpd.update(Table=artist.kwdoc(Table))
@docstring.dedent_interpd
def table(ax,
cellText=None, cellColours=None,
cellLoc='right', colWidths=None,
rowLabels=None, rowColours=None, rowLoc='left',
colLabels=None, colColours=None, colLoc='center',
loc='bottom', bbox=None, edges='closed',
**kwargs):
"""
Add a table to an `~.axes.Axes`.
At least one of *cellText* or *cellColours* must be specified. These
parameters must be 2D lists, in which the outer lists define the rows and
the inner list define the column values per row. Each row must have the
same number of elements.
The table can optionally have row and column headers, which are configured
using *rowLabels*, *rowColours*, *rowLoc* and *colLabels*, *colColours*,
*colLoc* respectively.
For finer grained control over tables, use the `.Table` class and add it to
the axes with `.Axes.add_table`.
Parameters
----------
cellText : 2D list of str, optional
The texts to place into the table cells.
*Note*: Line breaks in the strings are currently not accounted for and
will result in the text exceeding the cell boundaries.
cellColours : 2D list of matplotlib color specs, optional
The background colors of the cells.
cellLoc : {'left', 'center', 'right'}, default: 'right'
The alignment of the text within the cells.
colWidths : list of float, optional
The column widths in units of the axes. If not given, all columns will
have a width of *1 / ncols*.
rowLabels : list of str, optional
The text of the row header cells.
rowColours : list of matplotlib color specs, optional
The colors of the row header cells.
rowLoc : {'left', 'center', 'right'}, optional, default: 'left'
The text alignment of the row header cells.
colLabels : list of str, optional
The text of the column header cells.
colColours : list of matplotlib color specs, optional
The colors of the column header cells.
rowLoc : {'left', 'center', 'right'}, optional, default: 'left'
The text alignment of the column header cells.
loc : str, optional
The position of the cell with respect to *ax*. This must be one of
the `~.Table.codes`.
bbox : `.Bbox`, optional
A bounding box to draw the table into. If this is not *None*, this
overrides *loc*.
edges : substring of 'BRTL' or {'open', 'closed', 'horizontal', 'vertical'}
The cell edges to be drawn with a line. See also
`~.CustomCell.visible_edges`.
Other Parameters
----------------
**kwargs
`.Table` properties.
%(Table)s
Returns
-------
table : `~matplotlib.table.Table`
The created table.
"""
if cellColours is None and cellText is None:
raise ValueError('At least one argument from "cellColours" or '
'"cellText" must be provided to create a table.')
# Check we have some cellText
if cellText is None:
# assume just colours are needed
rows = len(cellColours)
cols = len(cellColours[0])
cellText = [[''] * cols] * rows
rows = len(cellText)
cols = len(cellText[0])
for row in cellText:
if len(row) != cols:
raise ValueError("Each row in 'cellText' must have {} columns"
.format(cols))
if cellColours is not None:
if len(cellColours) != rows:
raise ValueError("'cellColours' must have {} rows".format(rows))
for row in cellColours:
if len(row) != cols:
raise ValueError("Each row in 'cellColours' must have {} "
"columns".format(cols))
else:
cellColours = ['w' * cols] * rows
# Set colwidths if not given
if colWidths is None:
colWidths = [1.0 / cols] * cols
# Fill in missing information for column
# and row labels
rowLabelWidth = 0
if rowLabels is None:
if rowColours is not None:
rowLabels = [''] * rows
rowLabelWidth = colWidths[0]
elif rowColours is None:
rowColours = 'w' * rows
if rowLabels is not None:
if len(rowLabels) != rows:
raise ValueError("'rowLabels' must be of length {0}".format(rows))
# If we have column labels, need to shift
# the text and colour arrays down 1 row
offset = 1
if colLabels is None:
if colColours is not None:
colLabels = [''] * cols
else:
offset = 0
elif colColours is None:
colColours = 'w' * cols
# Set up cell colours if not given
if cellColours is None:
cellColours = ['w' * cols] * rows
# Now create the table
table = Table(ax, loc, bbox, **kwargs)
table.edges = edges
height = table._approx_text_height()
# Add the cells
for row in range(rows):
for col in range(cols):
table.add_cell(row + offset, col,
width=colWidths[col], height=height,
text=cellText[row][col],
facecolor=cellColours[row][col],
loc=cellLoc)
# Do column labels
if colLabels is not None:
for col in range(cols):
table.add_cell(0, col,
width=colWidths[col], height=height,
text=colLabels[col], facecolor=colColours[col],
loc=colLoc)
# Do row labels
if rowLabels is not None:
for row in range(rows):
table.add_cell(row + offset, -1,
width=rowLabelWidth or 1e-15, height=height,
text=rowLabels[row], facecolor=rowColours[row],
loc=rowLoc)
if rowLabelWidth == 0:
table.auto_set_column_width(-1)
ax.add_table(table)
return table
|
f03dd679e970e4e463165a4bc7f3f83f4b6d290f33132322b2220e3db11d1e1d
|
"""
This is an object-oriented plotting library.
A procedural interface is provided by the companion pyplot module,
which may be imported directly, e.g.::
import matplotlib.pyplot as plt
or using ipython::
ipython
at your terminal, followed by::
In [1]: %matplotlib
In [2]: import matplotlib.pyplot as plt
at the ipython shell prompt.
For the most part, direct use of the object-oriented library is
encouraged when programming; pyplot is primarily for working
interactively. The
exceptions are the pyplot commands :func:`~matplotlib.pyplot.figure`,
:func:`~matplotlib.pyplot.subplot`,
:func:`~matplotlib.pyplot.subplots`, and
:func:`~pyplot.savefig`, which can greatly simplify scripting.
Modules include:
:mod:`matplotlib.axes`
defines the :class:`~matplotlib.axes.Axes` class. Most pyplot
commands are wrappers for :class:`~matplotlib.axes.Axes`
methods. The axes module is the highest level of OO access to
the library.
:mod:`matplotlib.figure`
defines the :class:`~matplotlib.figure.Figure` class.
:mod:`matplotlib.artist`
defines the :class:`~matplotlib.artist.Artist` base class for
all classes that draw things.
:mod:`matplotlib.lines`
defines the :class:`~matplotlib.lines.Line2D` class for
drawing lines and markers
:mod:`matplotlib.patches`
defines classes for drawing polygons
:mod:`matplotlib.text`
defines the :class:`~matplotlib.text.Text`,
:class:`~matplotlib.text.TextWithDash`, and
:class:`~matplotlib.text.Annotate` classes
:mod:`matplotlib.image`
defines the :class:`~matplotlib.image.AxesImage` and
:class:`~matplotlib.image.FigureImage` classes
:mod:`matplotlib.collections`
classes for efficient drawing of groups of lines or polygons
:mod:`matplotlib.colors`
classes for interpreting color specifications and for making
colormaps
:mod:`matplotlib.cm`
colormaps and the :class:`~matplotlib.image.ScalarMappable`
mixin class for providing color mapping functionality to other
classes
:mod:`matplotlib.ticker`
classes for calculating tick mark locations and for formatting
tick labels
:mod:`matplotlib.backends`
a subpackage with modules for various gui libraries and output
formats
The base matplotlib namespace includes:
:data:`~matplotlib.rcParams`
a global dictionary of default configuration settings. It is
initialized by code which may be overridden by a matplotlibrc
file.
:func:`~matplotlib.rc`
a function for setting groups of rcParams values
:func:`~matplotlib.use`
a function for setting the matplotlib backend. If used, this
function must be called immediately after importing matplotlib
for the first time. In particular, it must be called
**before** importing pyplot (if pyplot is imported).
matplotlib was initially written by John D. Hunter (1968-2012) and is now
developed and maintained by a host of others.
Occasionally the internal documentation (python docstrings) will refer
to MATLAB®, a registered trademark of The MathWorks, Inc.
"""
# NOTE: This file must remain Python 2 compatible for the foreseeable future,
# to ensure that we error out properly for existing editable installs.
import sys
if sys.version_info < (3, 5): # noqa: E402
raise ImportError("""
Matplotlib 3.0+ does not support Python 2.x, 3.0, 3.1, 3.2, 3.3, or 3.4.
Beginning with Matplotlib 3.0, Python 3.5 and above is required.
See Matplotlib `INSTALL.rst` file for more information:
https://github.com/matplotlib/matplotlib/blob/master/INSTALL.rst
""")
import atexit
from collections import namedtuple
from collections.abc import MutableMapping
import contextlib
from distutils.version import LooseVersion
import functools
import importlib
import inspect
from inspect import Parameter
import locale
import logging
import os
from pathlib import Path
import pprint
import re
import shutil
import subprocess
import tempfile
# cbook must import matplotlib only within function
# definitions, so it is safe to import from it here.
from . import cbook, rcsetup
from matplotlib.cbook import (
MatplotlibDeprecationWarning, dedent, get_label, sanitize_sequence)
from matplotlib.cbook import mplDeprecation # deprecated
from matplotlib.rcsetup import defaultParams, validate_backend, cycler
import numpy
# Get the version from the _version.py versioneer file. For a git checkout,
# this is computed based on the number of commits since the last tag.
from ._version import get_versions
__version__ = str(get_versions()['version'])
del get_versions
_log = logging.getLogger(__name__)
__bibtex__ = r"""@Article{Hunter:2007,
Author = {Hunter, J. D.},
Title = {Matplotlib: A 2D graphics environment},
Journal = {Computing in Science \& Engineering},
Volume = {9},
Number = {3},
Pages = {90--95},
abstract = {Matplotlib is a 2D graphics package used for Python
for application development, interactive scripting, and
publication-quality image generation across user
interfaces and operating systems.},
publisher = {IEEE COMPUTER SOC},
year = 2007
}"""
def compare_versions(a, b):
"Return whether version *a* is greater than or equal to version *b*."
if isinstance(a, bytes):
cbook.warn_deprecated(
"3.0", message="compare_versions arguments should be strs.")
a = a.decode('ascii')
if isinstance(b, bytes):
cbook.warn_deprecated(
"3.0", message="compare_versions arguments should be strs.")
b = b.decode('ascii')
if a:
return LooseVersion(a) >= LooseVersion(b)
else:
return False
def _check_versions():
for modname, minver in [
("cycler", "0.10"),
("dateutil", "2.1"),
("kiwisolver", "1.0.1"),
("numpy", "1.11"),
("pyparsing", "2.0.1"),
]:
module = importlib.import_module(modname)
if LooseVersion(module.__version__) < minver:
raise ImportError("Matplotlib requires {}>={}; you have {}"
.format(modname, minver, module.__version__))
_check_versions()
if not hasattr(sys, 'argv'): # for modpython
sys.argv = ['modpython']
# The decorator ensures this always returns the same handler (and it is only
# attached once).
@functools.lru_cache()
def _ensure_handler():
"""
The first time this function is called, attach a `StreamHandler` using the
same format as `logging.basicConfig` to the Matplotlib root logger.
Return this handler every time this function is called.
"""
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter(logging.BASIC_FORMAT))
_log.addHandler(handler)
return handler
def set_loglevel(level):
"""
Sets the Matplotlib's root logger and root logger handler level, creating
the handler if it does not exist yet.
Typically, one should call ``set_loglevel("info")`` or
``set_loglevel("debug")`` to get additional debugging information.
Parameters
----------
level : {"notset", "debug", "info", "warning", "error", "critical"}
The log level of the handler.
Notes
-----
The first time this function is called, an additional handler is attached
to Matplotlib's root handler; this handler is reused every time and this
function simply manipulates the logger and handler's level.
"""
_log.setLevel(level.upper())
_ensure_handler().setLevel(level.upper())
def _logged_cached(fmt, func=None):
"""
Decorator that logs a function's return value, and memoizes that value.
After ::
@_logged_cached(fmt)
def func(): ...
the first call to *func* will log its return value at the DEBUG level using
%-format string *fmt*, and memoize it; later calls to *func* will directly
return that value.
"""
if func is None: # Return the actual decorator.
return functools.partial(_logged_cached, fmt)
called = False
ret = None
@functools.wraps(func)
def wrapper():
nonlocal called, ret
if not called:
ret = func()
called = True
_log.debug(fmt, ret)
return ret
return wrapper
_ExecInfo = namedtuple("_ExecInfo", "executable version")
@functools.lru_cache()
def _get_executable_info(name):
"""
Get the version of some executable that Matplotlib optionally depends on.
.. warning:
The list of executables that this function supports is set according to
Matplotlib's internal needs, and may change without notice.
Parameters
----------
name : str
The executable to query. The following values are currently supported:
"dvipng", "gs", "inkscape", "magick", "pdftops". This list is subject
to change without notice.
Returns
-------
If the executable is found, a namedtuple with fields ``executable`` (`str`)
and ``version`` (`distutils.version.LooseVersion`, or ``None`` if the
version cannot be determined).
Raises
------
FileNotFoundError
If the executable is not found or older than the oldest version
supported by Matplotlib.
ValueError
If the executable is not one that we know how to query.
"""
def impl(args, regex, min_ver=None):
# Execute the subprocess specified by args; capture stdout and stderr.
# Search for a regex match in the output; if the match succeeds, the
# first group of the match is the version.
# Return an _ExecInfo if the executable exists, and has a version of
# at least min_ver (if set); else, raise FileNotFoundError.
output = subprocess.check_output(
args, stderr=subprocess.STDOUT, universal_newlines=True)
match = re.search(regex, output)
if match:
version = LooseVersion(match.group(1))
if min_ver is not None and version < min_ver:
raise FileNotFoundError(
f"You have {args[0]} version {version} but the minimum "
f"version supported by Matplotlib is {min_ver}.")
return _ExecInfo(args[0], version)
else:
raise FileNotFoundError(
f"Failed to determine the version of {args[0]} from "
f"{' '.join(args)}, which output {output}")
if name == "dvipng":
return impl(["dvipng", "-version"], "(?m)^dvipng .* (.+)", "1.6")
elif name == "gs":
execs = (["gswin32c", "gswin64c", "mgs", "gs"] # "mgs" for miktex.
if sys.platform == "win32" else
["gs"])
for e in execs:
try:
return impl([e, "--version"], "(.*)", "9")
except FileNotFoundError:
pass
raise FileNotFoundError("Failed to find a Ghostscript installation")
elif name == "inkscape":
return impl(["inkscape", "-V"], "^Inkscape ([^ ]*)")
elif name == "magick":
path = None
if sys.platform == "win32":
# Check the registry to avoid confusing ImageMagick's convert with
# Windows's builtin convert.exe.
import winreg
binpath = ""
for flag in [0, winreg.KEY_WOW64_32KEY, winreg.KEY_WOW64_64KEY]:
try:
with winreg.OpenKeyEx(
winreg.HKEY_LOCAL_MACHINE,
r"Software\Imagemagick\Current",
0, winreg.KEY_QUERY_VALUE | flag) as hkey:
binpath = winreg.QueryValueEx(hkey, "BinPath")[0]
except OSError:
pass
if binpath:
for name in ["convert.exe", "magick.exe"]:
candidate = Path(binpath, name)
if candidate.exists():
path = str(candidate)
break
else:
path = "convert"
if path is None:
raise FileNotFoundError(
"Failed to find an ImageMagick installation")
return impl([path, "--version"], r"^Version: ImageMagick (\S*)")
elif name == "pdftops":
info = impl(["pdftops", "-v"], "^pdftops version (.*)")
if info and not ("3.0" <= info.version
# poppler version numbers.
or "0.9" <= info.version <= "1.0"):
raise FileNotFoundError(
f"You have pdftops version {info.version} but the minimum "
f"version supported by Matplotlib is 3.0.")
return info
else:
raise ValueError("Unknown executable: {!r}".format(name))
@cbook.deprecated("3.1")
def checkdep_dvipng():
try:
s = subprocess.Popen(['dvipng', '-version'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = s.communicate()
line = stdout.decode('ascii').split('\n')[1]
v = line.split()[-1]
return v
except (IndexError, ValueError, OSError):
return None
@cbook.deprecated("3.1")
def checkdep_ghostscript():
if checkdep_ghostscript.executable is None:
if sys.platform == 'win32':
# mgs is the name in miktex
gs_execs = ['gswin32c', 'gswin64c', 'mgs', 'gs']
else:
gs_execs = ['gs']
for gs_exec in gs_execs:
try:
s = subprocess.Popen(
[gs_exec, '--version'], stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = s.communicate()
if s.returncode == 0:
v = stdout[:-1].decode('ascii')
if compare_versions(v, '9.0'):
checkdep_ghostscript.executable = gs_exec
checkdep_ghostscript.version = v
except (IndexError, ValueError, OSError):
pass
return checkdep_ghostscript.executable, checkdep_ghostscript.version
checkdep_ghostscript.executable = None
checkdep_ghostscript.version = None
@cbook.deprecated("3.1")
def checkdep_pdftops():
try:
s = subprocess.Popen(['pdftops', '-v'], stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = s.communicate()
lines = stderr.decode('ascii').split('\n')
for line in lines:
if 'version' in line:
v = line.split()[-1]
return v
except (IndexError, ValueError, UnboundLocalError, OSError):
return None
@cbook.deprecated("3.1")
def checkdep_inkscape():
if checkdep_inkscape.version is None:
try:
s = subprocess.Popen(['inkscape', '-V'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = s.communicate()
lines = stdout.decode('ascii').split('\n')
for line in lines:
if 'Inkscape' in line:
v = line.split()[1]
break
checkdep_inkscape.version = v
except (IndexError, ValueError, UnboundLocalError, OSError):
pass
return checkdep_inkscape.version
checkdep_inkscape.version = None
def checkdep_ps_distiller(s):
if not s:
return False
try:
_get_executable_info("gs")
except FileNotFoundError:
_log.warning(
"Setting rcParams['ps.usedistiller'] requires ghostscript.")
return False
if s == "xpdf":
try:
_get_executable_info("pdftops")
except FileNotFoundError:
_log.warning(
"Setting rcParams['ps.usedistiller'] to 'xpdf' requires xpdf.")
return False
return s
def checkdep_usetex(s):
if not s:
return False
if not shutil.which("tex"):
_log.warning("usetex mode requires TeX.")
return False
try:
_get_executable_info("dvipng")
except FileNotFoundError:
_log.warning("usetex mode requires dvipng.")
return False
try:
_get_executable_info("gs")
except FileNotFoundError:
_log.warning("usetex mode requires ghostscript.")
return False
return True
@_logged_cached('$HOME=%s')
def get_home():
"""
Return the user's home directory.
If the user's home directory cannot be found, return None.
"""
try:
return str(Path.home())
except Exception:
return None
def _create_tmp_config_or_cache_dir():
"""
If the config or cache directory cannot be created, create a temporary one.
"""
configdir = os.environ['MPLCONFIGDIR'] = (
tempfile.mkdtemp(prefix='matplotlib-'))
atexit.register(shutil.rmtree, configdir)
return configdir
def _get_xdg_config_dir():
"""
Return the XDG configuration directory, according to the `XDG
base directory spec
<http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html>`_.
"""
return (os.environ.get('XDG_CONFIG_HOME')
or (str(Path(get_home(), ".config"))
if get_home()
else None))
def _get_xdg_cache_dir():
"""
Return the XDG cache directory, according to the `XDG
base directory spec
<http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html>`_.
"""
return (os.environ.get('XDG_CACHE_HOME')
or (str(Path(get_home(), ".cache"))
if get_home()
else None))
def _get_config_or_cache_dir(xdg_base):
configdir = os.environ.get('MPLCONFIGDIR')
if configdir:
configdir = Path(configdir).resolve()
elif sys.platform.startswith(('linux', 'freebsd')) and xdg_base:
configdir = Path(xdg_base, "matplotlib")
elif get_home():
configdir = Path(get_home(), ".matplotlib")
else:
configdir = None
if configdir:
try:
configdir.mkdir(parents=True, exist_ok=True)
except OSError:
pass
else:
if os.access(str(configdir), os.W_OK) and configdir.is_dir():
return str(configdir)
return _create_tmp_config_or_cache_dir()
@_logged_cached('CONFIGDIR=%s')
def get_configdir():
"""
Return the string representing the configuration directory.
The directory is chosen as follows:
1. If the MPLCONFIGDIR environment variable is supplied, choose that.
2a. On Linux, follow the XDG specification and look first in
`$XDG_CONFIG_HOME`, if defined, or `$HOME/.config`.
2b. On other platforms, choose `$HOME/.matplotlib`.
3. If the chosen directory exists and is writable, use that as the
configuration directory.
4. If possible, create a temporary directory, and use it as the
configuration directory.
5. A writable directory could not be found or created; return None.
"""
return _get_config_or_cache_dir(_get_xdg_config_dir())
@_logged_cached('CACHEDIR=%s')
def get_cachedir():
"""
Return the location of the cache directory.
The procedure used to find the directory is the same as for
_get_config_dir, except using `$XDG_CACHE_HOME`/`~/.cache` instead.
"""
return _get_config_or_cache_dir(_get_xdg_cache_dir())
def _get_data_path():
'get the path to matplotlib data'
if 'MATPLOTLIBDATA' in os.environ:
path = os.environ['MATPLOTLIBDATA']
if not os.path.isdir(path):
raise RuntimeError('Path in environment MATPLOTLIBDATA not a '
'directory')
cbook.warn_deprecated(
"3.1", name="MATPLOTLIBDATA", obj_type="environment variable")
return path
def get_candidate_paths():
yield Path(__file__).with_name('mpl-data')
# setuptools' namespace_packages may hijack this init file
# so need to try something known to be in Matplotlib, not basemap.
import matplotlib.afm
yield Path(matplotlib.afm.__file__).with_name('mpl-data')
# py2exe zips pure python, so still need special check.
if getattr(sys, 'frozen', None):
yield Path(sys.executable).with_name('mpl-data')
# Try again assuming we need to step up one more directory.
yield Path(sys.executable).parent.with_name('mpl-data')
# Try again assuming sys.path[0] is a dir not a exe.
yield Path(sys.path[0]) / 'mpl-data'
for path in get_candidate_paths():
if path.is_dir():
return str(path)
raise RuntimeError('Could not find the matplotlib data files')
@_logged_cached('matplotlib data path: %s')
def get_data_path():
if defaultParams['datapath'][0] is None:
defaultParams['datapath'][0] = _get_data_path()
return defaultParams['datapath'][0]
@cbook.deprecated("3.1")
def get_py2exe_datafiles():
data_path = Path(get_data_path())
d = {}
for path in filter(Path.is_file, data_path.glob("**/*")):
(d.setdefault(str(path.parent.relative_to(data_path.parent)), [])
.append(str(path)))
return list(d.items())
def matplotlib_fname():
"""
Get the location of the config file.
The file location is determined in the following order
- ``$PWD/matplotlibrc``
- ``$MATPLOTLIBRC`` if it is not a directory
- ``$MATPLOTLIBRC/matplotlibrc``
- ``$MPLCONFIGDIR/matplotlibrc``
- On Linux,
- ``$XDG_CONFIG_HOME/matplotlib/matplotlibrc`` (if ``$XDG_CONFIG_HOME``
is defined)
- or ``$HOME/.config/matplotlib/matplotlibrc`` (if ``$XDG_CONFIG_HOME``
is not defined)
- On other platforms,
- ``$HOME/.matplotlib/matplotlibrc`` if ``$HOME`` is defined
- Lastly, it looks in ``$MATPLOTLIBDATA/matplotlibrc``, which should always
exist.
"""
def gen_candidates():
yield os.path.join(os.getcwd(), 'matplotlibrc')
try:
matplotlibrc = os.environ['MATPLOTLIBRC']
except KeyError:
pass
else:
yield matplotlibrc
yield os.path.join(matplotlibrc, 'matplotlibrc')
yield os.path.join(get_configdir(), 'matplotlibrc')
yield os.path.join(get_data_path(), 'matplotlibrc')
for fname in gen_candidates():
if os.path.exists(fname) and not os.path.isdir(fname):
return fname
raise RuntimeError("Could not find matplotlibrc file; your Matplotlib "
"install is broken")
# rcParams deprecated and automatically mapped to another key.
# Values are tuples of (version, new_name, f_old2new, f_new2old).
_deprecated_map = {}
# rcParams deprecated; some can manually be mapped to another key.
# Values are tuples of (version, new_name_or_None).
_deprecated_ignore_map = {
'pgf.debug': ('3.0', None),
}
# rcParams deprecated; can use None to suppress warnings; remain actually
# listed in the rcParams (not included in _all_deprecated).
# Values are tuples of (version,)
_deprecated_remain_as_none = {
'text.latex.unicode': ('3.0',),
'savefig.frameon': ('3.1',),
'verbose.fileo': ('3.1',),
'verbose.level': ('3.1',),
}
_all_deprecated = {*_deprecated_map, *_deprecated_ignore_map}
class RcParams(MutableMapping, dict):
"""
A dictionary object including validation
validating functions are defined and associated with rc parameters in
:mod:`matplotlib.rcsetup`
"""
validate = {key: converter
for key, (default, converter) in defaultParams.items()
if key not in _all_deprecated}
@cbook.deprecated("3.0")
@property
def msg_depr(self):
return "%s is deprecated and replaced with %s; please use the latter."
@cbook.deprecated("3.0")
@property
def msg_depr_ignore(self):
return "%s is deprecated and ignored. Use %s instead."
@cbook.deprecated("3.0")
@property
def msg_depr_set(self):
return ("%s is deprecated. Please remove it from your matplotlibrc "
"and/or style files.")
@cbook.deprecated("3.0")
@property
def msg_obsolete(self):
return ("%s is obsolete. Please remove it from your matplotlibrc "
"and/or style files.")
@cbook.deprecated("3.0")
@property
def msg_backend_obsolete(self):
return ("The {} rcParam was deprecated in version 2.2. In order to "
"force the use of a specific Qt binding, either import that "
"binding first, or set the QT_API environment variable.")
# validate values on the way in
def __init__(self, *args, **kwargs):
self.update(*args, **kwargs)
def __setitem__(self, key, val):
try:
if key in _deprecated_map:
version, alt_key, alt_val, inverse_alt = _deprecated_map[key]
cbook.warn_deprecated(
version, name=key, obj_type="rcparam", alternative=alt_key)
key = alt_key
val = alt_val(val)
elif key in _deprecated_remain_as_none and val is not None:
version, = _deprecated_remain_as_none[key]
cbook.warn_deprecated(
version, name=key, obj_type="rcparam")
elif key in _deprecated_ignore_map:
version, alt_key = _deprecated_ignore_map[key]
cbook.warn_deprecated(
version, name=key, obj_type="rcparam", alternative=alt_key)
return
elif key == 'examples.directory':
cbook.warn_deprecated(
"3.0", name=key, obj_type="rcparam", addendum="In the "
"future, examples will be found relative to the "
"'datapath' directory.")
elif key == 'backend':
if val is rcsetup._auto_backend_sentinel:
if 'backend' in self:
return
try:
cval = self.validate[key](val)
except ValueError as ve:
raise ValueError("Key %s: %s" % (key, str(ve)))
dict.__setitem__(self, key, cval)
except KeyError:
raise KeyError(
f"{key} is not a valid rc parameter (see rcParams.keys() for "
f"a list of valid parameters)")
def __getitem__(self, key):
if key in _deprecated_map:
version, alt_key, alt_val, inverse_alt = _deprecated_map[key]
cbook.warn_deprecated(
version, name=key, obj_type="rcparam", alternative=alt_key)
return inverse_alt(dict.__getitem__(self, alt_key))
elif key in _deprecated_ignore_map:
version, alt_key = _deprecated_ignore_map[key]
cbook.warn_deprecated(
version, name=key, obj_type="rcparam", alternative=alt_key)
return dict.__getitem__(self, alt_key) if alt_key else None
elif key == 'examples.directory':
cbook.warn_deprecated(
"3.0", name=key, obj_type="rcparam", addendum="In the future, "
"examples will be found relative to the 'datapath' directory.")
elif key == "backend":
val = dict.__getitem__(self, key)
if val is rcsetup._auto_backend_sentinel:
from matplotlib import pyplot as plt
plt.switch_backend(rcsetup._auto_backend_sentinel)
return dict.__getitem__(self, key)
def __repr__(self):
class_name = self.__class__.__name__
indent = len(class_name) + 1
repr_split = pprint.pformat(dict(self), indent=1,
width=80 - indent).split('\n')
repr_indented = ('\n' + ' ' * indent).join(repr_split)
return '{}({})'.format(class_name, repr_indented)
def __str__(self):
return '\n'.join(map('{0[0]}: {0[1]}'.format, sorted(self.items())))
def __iter__(self):
"""Yield sorted list of keys."""
with cbook._suppress_matplotlib_deprecation_warning():
yield from sorted(dict.__iter__(self))
def __len__(self):
return dict.__len__(self)
def find_all(self, pattern):
"""
Return the subset of this RcParams dictionary whose keys match,
using :func:`re.search`, the given ``pattern``.
.. note::
Changes to the returned dictionary are *not* propagated to
the parent RcParams dictionary.
"""
pattern_re = re.compile(pattern)
return RcParams((key, value)
for key, value in self.items()
if pattern_re.search(key))
def copy(self):
return {k: dict.__getitem__(self, k) for k in self}
def rc_params(fail_on_error=False):
"""Return a :class:`matplotlib.RcParams` instance from the
default matplotlib rc file.
"""
return rc_params_from_file(matplotlib_fname(), fail_on_error)
URL_REGEX = re.compile(r'^http://|^https://|^ftp://|^file:')
def is_url(filename):
"""Return True if string is an http, ftp, or file URL path."""
return URL_REGEX.match(filename) is not None
@contextlib.contextmanager
def _open_file_or_url(fname):
if is_url(fname):
import urllib.request
with urllib.request.urlopen(fname) as f:
yield (line.decode('utf-8') for line in f)
else:
fname = os.path.expanduser(fname)
encoding = locale.getpreferredencoding(do_setlocale=False)
if encoding is None:
encoding = "utf-8"
with open(fname, encoding=encoding) as f:
yield f
_error_details_fmt = 'line #%d\n\t"%s"\n\tin file "%s"'
def _rc_params_in_file(fname, fail_on_error=False):
"""Return :class:`matplotlib.RcParams` from the contents of the given file.
Unlike `rc_params_from_file`, the configuration class only contains the
parameters specified in the file (i.e. default values are not filled in).
"""
cnt = 0
rc_temp = {}
with _open_file_or_url(fname) as fd:
try:
for line in fd:
cnt += 1
strippedline = line.split('#', 1)[0].strip()
if not strippedline:
continue
tup = strippedline.split(':', 1)
if len(tup) != 2:
error_details = _error_details_fmt % (cnt, line, fname)
_log.warning('Illegal %s', error_details)
continue
key, val = tup
key = key.strip()
val = val.strip()
if key in rc_temp:
_log.warning('Duplicate key in file %r line #%d.',
fname, cnt)
rc_temp[key] = (val, line, cnt)
except UnicodeDecodeError:
_log.warning('Cannot decode configuration file %s with encoding '
'%s, check LANG and LC_* variables.',
fname,
locale.getpreferredencoding(do_setlocale=False)
or 'utf-8 (default)')
raise
config = RcParams()
for key, (val, line, cnt) in rc_temp.items():
if key in defaultParams:
if fail_on_error:
config[key] = val # try to convert to proper type or raise
else:
try:
config[key] = val # try to convert to proper type or skip
except Exception as msg:
error_details = _error_details_fmt % (cnt, line, fname)
_log.warning('Bad val %r on %s\n\t%s',
val, error_details, msg)
elif key in _deprecated_ignore_map:
version, alt_key = _deprecated_ignore_map[key]
cbook.warn_deprecated(
version, name=key, alternative=alt_key,
addendum="Please update your matplotlibrc.")
else:
print("""
Bad key "%s" on line %d in
%s.
You probably need to get an updated matplotlibrc file from
http://github.com/matplotlib/matplotlib/blob/master/matplotlibrc.template
or from the matplotlib source distribution""" % (key, cnt, fname),
file=sys.stderr)
return config
def rc_params_from_file(fname, fail_on_error=False, use_default_template=True):
"""Return :class:`matplotlib.RcParams` from the contents of the given file.
Parameters
----------
fname : str
Name of file parsed for matplotlib settings.
fail_on_error : bool
If True, raise an error when the parser fails to convert a parameter.
use_default_template : bool
If True, initialize with default parameters before updating with those
in the given file. If False, the configuration class only contains the
parameters specified in the file. (Useful for updating dicts.)
"""
config_from_file = _rc_params_in_file(fname, fail_on_error)
if not use_default_template:
return config_from_file
iter_params = defaultParams.items()
with cbook._suppress_matplotlib_deprecation_warning():
config = RcParams([(key, default) for key, (default, _) in iter_params
if key not in _all_deprecated])
config.update(config_from_file)
if config['datapath'] is None:
config['datapath'] = get_data_path()
if "".join(config['text.latex.preamble']):
_log.info("""
*****************************************************************
You have the following UNSUPPORTED LaTeX preamble customizations:
%s
Please do not ask for support with these customizations active.
*****************************************************************
""", '\n'.join(config['text.latex.preamble']))
_log.debug('loaded rc file %s', fname)
return config
# this is the instance used by the matplotlib classes
rcParams = rc_params()
# Don't trigger deprecation warning when just fetching.
if dict.__getitem__(rcParams, 'examples.directory'):
# paths that are intended to be relative to matplotlib_fname()
# are allowed for the examples.directory parameter.
# However, we will need to fully qualify the path because
# Sphinx requires absolute paths.
if not os.path.isabs(rcParams['examples.directory']):
_basedir, _fname = os.path.split(matplotlib_fname())
# Sometimes matplotlib_fname() can return relative paths,
# Also, using realpath() guarantees that Sphinx will use
# the same path that matplotlib sees (in case of weird symlinks).
_basedir = os.path.realpath(_basedir)
_fullpath = os.path.join(_basedir, rcParams['examples.directory'])
rcParams['examples.directory'] = _fullpath
with cbook._suppress_matplotlib_deprecation_warning():
rcParamsOrig = RcParams(rcParams.copy())
rcParamsDefault = RcParams([(key, default) for key, (default, converter) in
defaultParams.items()
if key not in _all_deprecated])
rcParams['ps.usedistiller'] = checkdep_ps_distiller(
rcParams['ps.usedistiller'])
if rcParams['axes.formatter.use_locale']:
locale.setlocale(locale.LC_ALL, '')
def rc(group, **kwargs):
"""
Set the current rc params. *group* is the grouping for the rc, e.g.,
for ``lines.linewidth`` the group is ``lines``, for
``axes.facecolor``, the group is ``axes``, and so on. Group may
also be a list or tuple of group names, e.g., (*xtick*, *ytick*).
*kwargs* is a dictionary attribute name/value pairs, e.g.,::
rc('lines', linewidth=2, color='r')
sets the current rc params and is equivalent to::
rcParams['lines.linewidth'] = 2
rcParams['lines.color'] = 'r'
The following aliases are available to save typing for interactive
users:
===== =================
Alias Property
===== =================
'lw' 'linewidth'
'ls' 'linestyle'
'c' 'color'
'fc' 'facecolor'
'ec' 'edgecolor'
'mew' 'markeredgewidth'
'aa' 'antialiased'
===== =================
Thus you could abbreviate the above rc command as::
rc('lines', lw=2, c='r')
Note you can use python's kwargs dictionary facility to store
dictionaries of default parameters. e.g., you can customize the
font rc as follows::
font = {'family' : 'monospace',
'weight' : 'bold',
'size' : 'larger'}
rc('font', **font) # pass in the font dict as kwargs
This enables you to easily switch between several configurations. Use
``matplotlib.style.use('default')`` or :func:`~matplotlib.rcdefaults` to
restore the default rc params after changes.
"""
aliases = {
'lw': 'linewidth',
'ls': 'linestyle',
'c': 'color',
'fc': 'facecolor',
'ec': 'edgecolor',
'mew': 'markeredgewidth',
'aa': 'antialiased',
}
if isinstance(group, str):
group = (group,)
for g in group:
for k, v in kwargs.items():
name = aliases.get(k) or k
key = '%s.%s' % (g, name)
try:
rcParams[key] = v
except KeyError:
raise KeyError(('Unrecognized key "%s" for group "%s" and '
'name "%s"') % (key, g, name))
def rcdefaults():
"""
Restore the rc params from Matplotlib's internal default style.
Style-blacklisted rc params (defined in
`matplotlib.style.core.STYLE_BLACKLIST`) are not updated.
See Also
--------
rc_file_defaults
Restore the rc params from the rc file originally loaded by Matplotlib.
matplotlib.style.use :
Use a specific style file. Call ``style.use('default')`` to restore
the default style.
"""
# Deprecation warnings were already handled when creating rcParamsDefault,
# no need to reemit them here.
with cbook._suppress_matplotlib_deprecation_warning():
from .style.core import STYLE_BLACKLIST
rcParams.clear()
rcParams.update({k: v for k, v in rcParamsDefault.items()
if k not in STYLE_BLACKLIST})
def rc_file_defaults():
"""
Restore the rc params from the original rc file loaded by Matplotlib.
Style-blacklisted rc params (defined in
`matplotlib.style.core.STYLE_BLACKLIST`) are not updated.
"""
# Deprecation warnings were already handled when creating rcParamsOrig, no
# need to reemit them here.
with cbook._suppress_matplotlib_deprecation_warning():
from .style.core import STYLE_BLACKLIST
rcParams.update({k: rcParamsOrig[k] for k in rcParamsOrig
if k not in STYLE_BLACKLIST})
def rc_file(fname, *, use_default_template=True):
"""
Update rc params from file.
Style-blacklisted rc params (defined in
`matplotlib.style.core.STYLE_BLACKLIST`) are not updated.
Parameters
----------
fname : str
Name of file parsed for matplotlib settings.
use_default_template : bool
If True, initialize with default parameters before updating with those
in the given file. If False, the current configuration persists
and only the parameters specified in the file are updated.
"""
# Deprecation warnings were already handled in rc_params_from_file, no need
# to reemit them here.
with cbook._suppress_matplotlib_deprecation_warning():
from .style.core import STYLE_BLACKLIST
rc_from_file = rc_params_from_file(
fname, use_default_template=use_default_template)
rcParams.update({k: rc_from_file[k] for k in rc_from_file
if k not in STYLE_BLACKLIST})
class rc_context:
"""
Return a context manager for managing rc settings.
This allows one to do::
with mpl.rc_context(fname='screen.rc'):
plt.plot(x, a)
with mpl.rc_context(fname='print.rc'):
plt.plot(x, b)
plt.plot(x, c)
The 'a' vs 'x' and 'c' vs 'x' plots would have settings from
'screen.rc', while the 'b' vs 'x' plot would have settings from
'print.rc'.
A dictionary can also be passed to the context manager::
with mpl.rc_context(rc={'text.usetex': True}, fname='screen.rc'):
plt.plot(x, a)
The 'rc' dictionary takes precedence over the settings loaded from
'fname'. Passing a dictionary only is also valid. For example a
common usage is::
with mpl.rc_context(rc={'interactive': False}):
fig, ax = plt.subplots()
ax.plot(range(3), range(3))
fig.savefig('A.png', format='png')
plt.close(fig)
"""
# While it may seem natural to implement rc_context using
# contextlib.contextmanager, that would entail always calling the finally:
# clause of the contextmanager (which restores the original rcs) including
# during garbage collection; as a result, something like `plt.xkcd();
# gc.collect()` would result in the style being lost (as `xkcd()` is
# implemented on top of rc_context, and nothing is holding onto context
# manager except possibly circular references.
def __init__(self, rc=None, fname=None):
self._orig = rcParams.copy()
try:
if fname:
rc_file(fname)
if rc:
rcParams.update(rc)
except Exception:
self.__fallback()
raise
def __fallback(self):
# If anything goes wrong, revert to the original rcs.
updated_backend = self._orig['backend']
dict.update(rcParams, self._orig)
# except for the backend. If the context block triggered resolving
# the auto backend resolution keep that value around
if self._orig['backend'] is rcsetup._auto_backend_sentinel:
rcParams['backend'] = updated_backend
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, exc_tb):
self.__fallback()
@cbook._rename_parameter("3.1", "arg", "backend")
def use(backend, warn=False, force=True):
"""
Select the backend used for rendering and GUI integration.
Parameters
----------
backend : str
The backend to switch to. This can either be one of the standard
backend names, which are case-insensitive:
- interactive backends:
GTK3Agg, GTK3Cairo, MacOSX, nbAgg,
Qt4Agg, Qt4Cairo, Qt5Agg, Qt5Cairo,
TkAgg, TkCairo, WebAgg, WX, WXAgg, WXCairo
- non-interactive backends:
agg, cairo, pdf, pgf, ps, svg, template
or a string of the form: ``module://my.module.name``.
warn : bool, optional, default: False
If True and not *force*, warn that the call will have no effect if
this is called after pyplot has been imported and a backend is set up.
force : bool, optional, default: True
If True, attempt to switch the backend. An ImportError is raised if
an interactive backend is selected, but another interactive
backend has already started.
See Also
--------
:ref:`backends`
matplotlib.get_backend
"""
name = validate_backend(backend)
if dict.__getitem__(rcParams, 'backend') == name:
# Nothing to do if the requested backend is already set
pass
elif 'matplotlib.pyplot' in sys.modules:
# pyplot has already been imported (which triggered backend selection)
# and the requested backend is different from the current one.
if force:
# if we are going to force switching the backend, pull in
# `switch_backend` from pyplot (which is already imported).
from matplotlib.pyplot import switch_backend
switch_backend(name)
elif warn:
# Only if we are not going to force the switch *and* warn is True,
# then direct users to `plt.switch_backend`.
cbook._warn_external(
"matplotlib.pyplot has already been imported, "
"this call will have no effect.")
else:
# Finally if pyplot is not imported update both rcParams and
# rcDefaults so restoring the defaults later with rcdefaults
# won't change the backend. This is a bit of overkill as 'backend'
# is already in style.core.STYLE_BLACKLIST, but better to be safe.
rcParams['backend'] = rcParamsDefault['backend'] = name
if os.environ.get('MPLBACKEND'):
rcParams['backend'] = os.environ.get('MPLBACKEND')
def get_backend():
"""
Return the name of the current backend.
See Also
--------
matplotlib.use
"""
return rcParams['backend']
def interactive(b):
"""
Set interactive mode to boolean b.
If b is True, then draw after every plotting command, e.g., after xlabel
"""
rcParams['interactive'] = b
def is_interactive():
'Return true if plot mode is interactive'
return rcParams['interactive']
@cbook.deprecated("3.1", alternative="rcParams['tk.window_focus']")
def tk_window_focus():
"""Return true if focus maintenance under TkAgg on win32 is on.
This currently works only for python.exe and IPython.exe.
Both IDLE and Pythonwin.exe fail badly when tk_window_focus is on."""
if rcParams['backend'] != 'TkAgg':
return False
return rcParams['tk.window_focus']
default_test_modules = [
'matplotlib.tests',
'matplotlib.sphinxext.tests',
'mpl_toolkits.tests',
]
def _init_tests():
# CPython's faulthandler since v3.6 handles exceptions on Windows
# https://bugs.python.org/issue23848 but until v3.6.4 it was printing
# non-fatal exceptions https://bugs.python.org/issue30557
import platform
if not (sys.platform == 'win32' and
(3, 6) < sys.version_info < (3, 6, 4) and
platform.python_implementation() == 'CPython'):
import faulthandler
faulthandler.enable()
# The version of FreeType to install locally for running the
# tests. This must match the value in `setupext.py`
LOCAL_FREETYPE_VERSION = '2.6.1'
from matplotlib import ft2font
if (ft2font.__freetype_version__ != LOCAL_FREETYPE_VERSION or
ft2font.__freetype_build_type__ != 'local'):
_log.warning(
"Matplotlib is not built with the correct FreeType version to run "
"tests. Set local_freetype=True in setup.cfg and rebuild. "
"Expect many image comparison failures below. "
"Expected freetype version {0}. "
"Found freetype version {1}. "
"Freetype build type is {2}local".format(
LOCAL_FREETYPE_VERSION,
ft2font.__freetype_version__,
"" if ft2font.__freetype_build_type__ == 'local' else "not "))
try:
import pytest
except ImportError:
print("matplotlib.test requires pytest to run.")
raise
@cbook._delete_parameter("3.2", "switch_backend_warn")
def test(verbosity=None, coverage=False, switch_backend_warn=True,
recursionlimit=0, **kwargs):
"""Run the matplotlib test suite."""
_init_tests()
if not os.path.isdir(os.path.join(os.path.dirname(__file__), 'tests')):
raise ImportError("Matplotlib test data is not installed")
old_backend = get_backend()
old_recursionlimit = sys.getrecursionlimit()
try:
use('agg')
if recursionlimit:
sys.setrecursionlimit(recursionlimit)
import pytest
args = kwargs.pop('argv', [])
provide_default_modules = True
use_pyargs = True
for arg in args:
if any(arg.startswith(module_path)
for module_path in default_test_modules):
provide_default_modules = False
break
if os.path.exists(arg):
provide_default_modules = False
use_pyargs = False
break
if use_pyargs:
args += ['--pyargs']
if provide_default_modules:
args += default_test_modules
if coverage:
args += ['--cov']
if verbosity:
args += ['-' + 'v' * verbosity]
retcode = pytest.main(args, **kwargs)
finally:
if old_backend.lower() != 'agg':
use(old_backend)
if recursionlimit:
sys.setrecursionlimit(old_recursionlimit)
return retcode
test.__test__ = False # pytest: this function is not a test
def _replacer(data, value):
"""
Either returns ``data[value]`` or passes ``data`` back, converts either to
a sequence.
"""
try:
# if key isn't a string don't bother
if isinstance(value, str):
# try to use __getitem__
value = data[value]
except Exception:
# key does not exist, silently fall back to key
pass
return sanitize_sequence(value)
def _label_from_arg(y, default_name):
try:
return y.name
except AttributeError:
if isinstance(default_name, str):
return default_name
return None
_DATA_DOC_APPENDIX = """
.. note::
In addition to the above described arguments, this function can take a
**data** keyword argument. If such a **data** argument is given, the
following arguments are replaced by **data[<arg>]**:
{replaced}
Objects passed as **data** must support item access (``data[<arg>]``) and
membership test (``<arg> in data``).
"""
def _add_data_doc(docstring, replace_names):
"""Add documentation for a *data* field to the given docstring.
Parameters
----------
docstring : str
The input docstring.
replace_names : list of str or None
The list of parameter names which arguments should be replaced by
``data[name]`` (if ``data[name]`` does not throw an exception). If
None, replacement is attempted for all arguments.
Returns
-------
The augmented docstring.
"""
docstring = inspect.cleandoc(docstring) if docstring is not None else ""
repl = ("* All positional and all keyword arguments."
if replace_names is None else
""
if len(replace_names) == 0 else
"* All arguments with the following names: {}.".format(
", ".join(map(repr, sorted(replace_names)))))
return docstring + _DATA_DOC_APPENDIX.format(replaced=repl)
def _preprocess_data(func=None, *, replace_names=None, label_namer=None):
"""
A decorator to add a 'data' kwarg to a function.
::
@_preprocess_data()
def func(ax, *args, **kwargs): ...
is a function with signature ``decorated(ax, *args, data=None, **kwargs)``
with the following behavior:
- if called with ``data=None``, forward the other arguments to ``func``;
- otherwise, *data* must be a mapping; for any argument passed in as a
string ``name``, replace the argument by ``data[name]`` (if this does not
throw an exception), then forward the arguments to ``func``.
In either case, any argument that is a `MappingView` is also converted to a
list.
Parameters
----------
replace_names : list of str or None, optional, default: None
The list of parameter names for which lookup into *data* should be
attempted. If None, replacement is attempted for all arguments.
label_namer : string, optional, default: None
If set e.g. to "namer" (which must be a kwarg in the function's
signature -- not as ``**kwargs``), if the *namer* argument passed in is
a (string) key of *data* and no *label* kwarg is passed, then use the
(string) value of the *namer* as *label*. ::
@_preprocess_data(label_namer="foo")
def func(foo, label=None): ...
func("key", data={"key": value})
# is equivalent to
func.__wrapped__(value, label="key")
"""
if func is None: # Return the actual decorator.
return functools.partial(
_preprocess_data,
replace_names=replace_names, label_namer=label_namer)
sig = inspect.signature(func)
varargs_name = None
varkwargs_name = None
arg_names = []
params = list(sig.parameters.values())
for p in params:
if p.kind is Parameter.VAR_POSITIONAL:
varargs_name = p.name
elif p.kind is Parameter.VAR_KEYWORD:
varkwargs_name = p.name
else:
arg_names.append(p.name)
data_param = Parameter("data", Parameter.KEYWORD_ONLY, default=None)
if varkwargs_name:
params.insert(-1, data_param)
else:
params.append(data_param)
new_sig = sig.replace(parameters=params)
arg_names = arg_names[1:] # remove the first "ax" / self arg
if replace_names is not None:
replace_names = set(replace_names)
assert (replace_names or set()) <= set(arg_names) or varkwargs_name, (
"Matplotlib internal error: invalid replace_names ({!r}) for {!r}"
.format(replace_names, func.__name__))
assert label_namer is None or label_namer in arg_names, (
"Matplotlib internal error: invalid label_namer ({!r}) for {!r}"
.format(label_namer, func.__name__))
@functools.wraps(func)
def inner(ax, *args, data=None, **kwargs):
if data is None:
return func(ax, *map(sanitize_sequence, args), **kwargs)
bound = new_sig.bind(ax, *args, **kwargs)
needs_label = (label_namer
and "label" not in bound.arguments
and "label" not in bound.kwargs)
auto_label = (bound.arguments.get(label_namer)
or bound.kwargs.get(label_namer))
for k, v in bound.arguments.items():
if k == varkwargs_name:
for k1, v1 in v.items():
if replace_names is None or k1 in replace_names:
v[k1] = _replacer(data, v1)
elif k == varargs_name:
if replace_names is None:
bound.arguments[k] = tuple(_replacer(data, v1) for v1 in v)
else:
if replace_names is None or k in replace_names:
bound.arguments[k] = _replacer(data, v)
bound.apply_defaults()
del bound.arguments["data"]
if needs_label:
all_kwargs = {**bound.arguments, **bound.kwargs}
# label_namer will be in all_kwargs as we asserted above that
# `label_namer is None or label_namer in arg_names`.
label = _label_from_arg(all_kwargs[label_namer], auto_label)
if "label" in arg_names:
bound.arguments["label"] = label
try:
bound.arguments.move_to_end(varkwargs_name)
except KeyError:
pass
else:
bound.arguments.setdefault(varkwargs_name, {})["label"] = label
return func(*bound.args, **bound.kwargs)
inner.__doc__ = _add_data_doc(inner.__doc__, replace_names)
inner.__signature__ = new_sig
return inner
_log.debug('matplotlib version %s', __version__)
_log.debug('interactive is %s', is_interactive())
_log.debug('platform is %s', sys.platform)
_log.debug('loaded modules: %s', list(sys.modules))
|
e5cf66ffa452acdbaff18bd29cc93ba8312572b3afe1e7ba068a0bc23aa3b71d
|
import inspect
import textwrap
import numpy as np
from numpy import ma
from matplotlib import cbook, docstring, rcParams
from matplotlib.ticker import (
NullFormatter, ScalarFormatter, LogFormatterSciNotation, LogitFormatter,
NullLocator, LogLocator, AutoLocator, AutoMinorLocator,
SymmetricalLogLocator, LogitLocator)
from matplotlib.transforms import Transform, IdentityTransform
class ScaleBase(object):
"""
The base class for all scales.
Scales are separable transformations, working on a single dimension.
Any subclasses will want to override:
- :attr:`name`
- :meth:`get_transform`
- :meth:`set_default_locators_and_formatters`
And optionally:
- :meth:`limit_range_for_scale`
"""
def __init__(self, axis, **kwargs):
r"""
Construct a new scale.
Notes
-----
The following note is for scale implementors.
For back-compatibility reasons, scales take an `~matplotlib.axis.Axis`
object as first argument. However, this argument should not
be used: a single scale object should be usable by multiple
`~matplotlib.axis.Axis`\es at the same time.
"""
def get_transform(self):
"""
Return the :class:`~matplotlib.transforms.Transform` object
associated with this scale.
"""
raise NotImplementedError()
def set_default_locators_and_formatters(self, axis):
"""
Set the :class:`~matplotlib.ticker.Locator` and
:class:`~matplotlib.ticker.Formatter` objects on the given
axis to match this scale.
"""
raise NotImplementedError()
def limit_range_for_scale(self, vmin, vmax, minpos):
"""
Returns the range *vmin*, *vmax*, possibly limited to the
domain supported by this scale.
*minpos* should be the minimum positive value in the data.
This is used by log scales to determine a minimum value.
"""
return vmin, vmax
class LinearScale(ScaleBase):
"""
The default linear scale.
"""
name = 'linear'
def __init__(self, axis, **kwargs):
# This method is present only to prevent inheritance of the base class'
# constructor docstring, which would otherwise end up interpolated into
# the docstring of Axis.set_scale.
"""
"""
super().__init__(axis, **kwargs)
def set_default_locators_and_formatters(self, axis):
"""
Set the locators and formatters to reasonable defaults for
linear scaling.
"""
axis.set_major_locator(AutoLocator())
axis.set_major_formatter(ScalarFormatter())
axis.set_minor_formatter(NullFormatter())
# update the minor locator for x and y axis based on rcParams
if (axis.axis_name == 'x' and rcParams['xtick.minor.visible']
or axis.axis_name == 'y' and rcParams['ytick.minor.visible']):
axis.set_minor_locator(AutoMinorLocator())
else:
axis.set_minor_locator(NullLocator())
def get_transform(self):
"""
The transform for linear scaling is just the
:class:`~matplotlib.transforms.IdentityTransform`.
"""
return IdentityTransform()
class FuncTransform(Transform):
"""
A simple transform that takes and arbitrary function for the
forward and inverse transform.
"""
input_dims = 1
output_dims = 1
is_separable = True
has_inverse = True
def __init__(self, forward, inverse):
"""
Parameters
----------
forward : callable
The forward function for the transform. This function must have
an inverse and, for best behavior, be monotonic.
It must have the signature::
def forward(values: array-like) -> array-like
inverse : callable
The inverse of the forward function. Signature as ``forward``.
"""
super().__init__()
if callable(forward) and callable(inverse):
self._forward = forward
self._inverse = inverse
else:
raise ValueError('arguments to FuncTransform must '
'be functions')
def transform_non_affine(self, values):
return self._forward(values)
def inverted(self):
return FuncTransform(self._inverse, self._forward)
class FuncScale(ScaleBase):
"""
Provide an arbitrary scale with user-supplied function for the axis.
"""
name = 'function'
def __init__(self, axis, functions):
"""
Parameters
----------
axis: the axis for the scale
functions : (callable, callable)
two-tuple of the forward and inverse functions for the scale.
The forward function must be monotonic.
Both functions must have the signature::
def forward(values: array-like) -> array-like
"""
forward, inverse = functions
transform = FuncTransform(forward, inverse)
self._transform = transform
def get_transform(self):
"""
The transform for arbitrary scaling
"""
return self._transform
def set_default_locators_and_formatters(self, axis):
"""
Set the locators and formatters to the same defaults as the
linear scale.
"""
axis.set_major_locator(AutoLocator())
axis.set_major_formatter(ScalarFormatter())
axis.set_minor_formatter(NullFormatter())
# update the minor locator for x and y axis based on rcParams
if (axis.axis_name == 'x' and rcParams['xtick.minor.visible']
or axis.axis_name == 'y' and rcParams['ytick.minor.visible']):
axis.set_minor_locator(AutoMinorLocator())
else:
axis.set_minor_locator(NullLocator())
@cbook.deprecated("3.1", alternative="LogTransform")
class LogTransformBase(Transform):
input_dims = 1
output_dims = 1
is_separable = True
has_inverse = True
def __init__(self, nonpos='clip'):
Transform.__init__(self)
self._clip = {"clip": True, "mask": False}[nonpos]
def transform_non_affine(self, a):
return LogTransform.transform_non_affine(self, a)
def __str__(self):
return "{}({!r})".format(
type(self).__name__, "clip" if self._clip else "mask")
@cbook.deprecated("3.1", alternative="InvertedLogTransform")
class InvertedLogTransformBase(Transform):
input_dims = 1
output_dims = 1
is_separable = True
has_inverse = True
def transform_non_affine(self, a):
return ma.power(self.base, a)
def __str__(self):
return "{}()".format(type(self).__name__)
@cbook.deprecated("3.1", alternative="LogTransform")
class Log10Transform(LogTransformBase):
base = 10.0
def inverted(self):
return InvertedLog10Transform()
@cbook.deprecated("3.1", alternative="InvertedLogTransform")
class InvertedLog10Transform(InvertedLogTransformBase):
base = 10.0
def inverted(self):
return Log10Transform()
@cbook.deprecated("3.1", alternative="LogTransform")
class Log2Transform(LogTransformBase):
base = 2.0
def inverted(self):
return InvertedLog2Transform()
@cbook.deprecated("3.1", alternative="InvertedLogTransform")
class InvertedLog2Transform(InvertedLogTransformBase):
base = 2.0
def inverted(self):
return Log2Transform()
@cbook.deprecated("3.1", alternative="LogTransform")
class NaturalLogTransform(LogTransformBase):
base = np.e
def inverted(self):
return InvertedNaturalLogTransform()
@cbook.deprecated("3.1", alternative="InvertedLogTransform")
class InvertedNaturalLogTransform(InvertedLogTransformBase):
base = np.e
def inverted(self):
return NaturalLogTransform()
class LogTransform(Transform):
input_dims = 1
output_dims = 1
is_separable = True
has_inverse = True
def __init__(self, base, nonpos='clip'):
Transform.__init__(self)
self.base = base
self._clip = {"clip": True, "mask": False}[nonpos]
def __str__(self):
return "{}(base={}, nonpos={!r})".format(
type(self).__name__, self.base, "clip" if self._clip else "mask")
def transform_non_affine(self, a):
# Ignore invalid values due to nans being passed to the transform.
with np.errstate(divide="ignore", invalid="ignore"):
log = {np.e: np.log, 2: np.log2, 10: np.log10}.get(self.base)
if log: # If possible, do everything in a single call to Numpy.
out = log(a)
else:
out = np.log(a)
out /= np.log(self.base)
if self._clip:
# SVG spec says that conforming viewers must support values up
# to 3.4e38 (C float); however experiments suggest that
# Inkscape (which uses cairo for rendering) runs into cairo's
# 24-bit limit (which is apparently shared by Agg).
# Ghostscript (used for pdf rendering appears to overflow even
# earlier, with the max value around 2 ** 15 for the tests to
# pass. On the other hand, in practice, we want to clip beyond
# np.log10(np.nextafter(0, 1)) ~ -323
# so 1000 seems safe.
out[a <= 0] = -1000
return out
def inverted(self):
return InvertedLogTransform(self.base)
class InvertedLogTransform(InvertedLogTransformBase):
input_dims = 1
output_dims = 1
is_separable = True
has_inverse = True
def __init__(self, base):
Transform.__init__(self)
self.base = base
def __str__(self):
return "{}(base={})".format(type(self).__name__, self.base)
def transform_non_affine(self, a):
return ma.power(self.base, a)
def inverted(self):
return LogTransform(self.base)
class LogScale(ScaleBase):
"""
A standard logarithmic scale. Care is taken to only plot positive values.
"""
name = 'log'
# compatibility shim
LogTransformBase = LogTransformBase
Log10Transform = Log10Transform
InvertedLog10Transform = InvertedLog10Transform
Log2Transform = Log2Transform
InvertedLog2Transform = InvertedLog2Transform
NaturalLogTransform = NaturalLogTransform
InvertedNaturalLogTransform = InvertedNaturalLogTransform
LogTransform = LogTransform
InvertedLogTransform = InvertedLogTransform
def __init__(self, axis, **kwargs):
"""
*basex*/*basey*:
The base of the logarithm
*nonposx*/*nonposy*: {'mask', 'clip'}
non-positive values in *x* or *y* can be masked as
invalid, or clipped to a very small positive number
*subsx*/*subsy*:
Where to place the subticks between each major tick.
Should be a sequence of integers. For example, in a log10
scale: ``[2, 3, 4, 5, 6, 7, 8, 9]``
will place 8 logarithmically spaced minor ticks between
each major tick.
"""
if axis.axis_name == 'x':
base = kwargs.pop('basex', 10.0)
subs = kwargs.pop('subsx', None)
nonpos = kwargs.pop('nonposx', 'clip')
cbook._check_in_list(['mask', 'clip'], nonposx=nonpos)
else:
base = kwargs.pop('basey', 10.0)
subs = kwargs.pop('subsy', None)
nonpos = kwargs.pop('nonposy', 'clip')
cbook._check_in_list(['mask', 'clip'], nonposy=nonpos)
if len(kwargs):
raise ValueError(("provided too many kwargs, can only pass "
"{'basex', 'subsx', nonposx'} or "
"{'basey', 'subsy', nonposy'}. You passed ") +
"{!r}".format(kwargs))
if base <= 0 or base == 1:
raise ValueError('The log base cannot be <= 0 or == 1')
self._transform = self.LogTransform(base, nonpos)
self.subs = subs
@property
def base(self):
return self._transform.base
def set_default_locators_and_formatters(self, axis):
"""
Set the locators and formatters to specialized versions for
log scaling.
"""
axis.set_major_locator(LogLocator(self.base))
axis.set_major_formatter(LogFormatterSciNotation(self.base))
axis.set_minor_locator(LogLocator(self.base, self.subs))
axis.set_minor_formatter(
LogFormatterSciNotation(self.base,
labelOnlyBase=(self.subs is not None)))
def get_transform(self):
"""
Return a :class:`~matplotlib.transforms.Transform` instance
appropriate for the given logarithm base.
"""
return self._transform
def limit_range_for_scale(self, vmin, vmax, minpos):
"""
Limit the domain to positive values.
"""
if not np.isfinite(minpos):
minpos = 1e-300 # This value should rarely if ever
# end up with a visible effect.
return (minpos if vmin <= 0 else vmin,
minpos if vmax <= 0 else vmax)
class FuncScaleLog(LogScale):
"""
Provide an arbitrary scale with user-supplied function for the axis and
then put on a logarithmic axes.
"""
name = 'functionlog'
def __init__(self, axis, functions, base=10):
"""
Parameters
----------
axis: the axis for the scale
functions : (callable, callable)
two-tuple of the forward and inverse functions for the scale.
The forward function must be monotonic.
Both functions must have the signature::
def forward(values: array-like) -> array-like
base : float
logarithmic base of the scale (default = 10)
"""
forward, inverse = functions
self.subs = None
self._transform = FuncTransform(forward, inverse) + LogTransform(base)
@property
def base(self):
return self._transform._b.base # Base of the LogTransform.
def get_transform(self):
"""
The transform for arbitrary scaling
"""
return self._transform
class SymmetricalLogTransform(Transform):
input_dims = 1
output_dims = 1
is_separable = True
has_inverse = True
def __init__(self, base, linthresh, linscale):
Transform.__init__(self)
self.base = base
self.linthresh = linthresh
self.linscale = linscale
self._linscale_adj = (linscale / (1.0 - self.base ** -1))
self._log_base = np.log(base)
def transform_non_affine(self, a):
sign = np.sign(a)
masked = ma.masked_inside(a,
-self.linthresh,
self.linthresh,
copy=False)
log = sign * self.linthresh * (
self._linscale_adj +
ma.log(np.abs(masked) / self.linthresh) / self._log_base)
if masked.mask.any():
return ma.where(masked.mask, a * self._linscale_adj, log)
else:
return log
def inverted(self):
return InvertedSymmetricalLogTransform(self.base, self.linthresh,
self.linscale)
class InvertedSymmetricalLogTransform(Transform):
input_dims = 1
output_dims = 1
is_separable = True
has_inverse = True
def __init__(self, base, linthresh, linscale):
Transform.__init__(self)
symlog = SymmetricalLogTransform(base, linthresh, linscale)
self.base = base
self.linthresh = linthresh
self.invlinthresh = symlog.transform(linthresh)
self.linscale = linscale
self._linscale_adj = (linscale / (1.0 - self.base ** -1))
def transform_non_affine(self, a):
sign = np.sign(a)
masked = ma.masked_inside(a, -self.invlinthresh,
self.invlinthresh, copy=False)
exp = sign * self.linthresh * (
ma.power(self.base, (sign * (masked / self.linthresh))
- self._linscale_adj))
if masked.mask.any():
return ma.where(masked.mask, a / self._linscale_adj, exp)
else:
return exp
def inverted(self):
return SymmetricalLogTransform(self.base,
self.linthresh, self.linscale)
class SymmetricalLogScale(ScaleBase):
"""
The symmetrical logarithmic scale is logarithmic in both the
positive and negative directions from the origin.
Since the values close to zero tend toward infinity, there is a
need to have a range around zero that is linear. The parameter
*linthresh* allows the user to specify the size of this range
(-*linthresh*, *linthresh*).
"""
name = 'symlog'
# compatibility shim
SymmetricalLogTransform = SymmetricalLogTransform
InvertedSymmetricalLogTransform = InvertedSymmetricalLogTransform
def __init__(self, axis, **kwargs):
"""
*basex*/*basey*:
The base of the logarithm
*linthreshx*/*linthreshy*:
A single float which defines the range (-*x*, *x*), within
which the plot is linear. This avoids having the plot go to
infinity around zero.
*subsx*/*subsy*:
Where to place the subticks between each major tick.
Should be a sequence of integers. For example, in a log10
scale: ``[2, 3, 4, 5, 6, 7, 8, 9]``
will place 8 logarithmically spaced minor ticks between
each major tick.
*linscalex*/*linscaley*:
This allows the linear range (-*linthresh* to *linthresh*)
to be stretched relative to the logarithmic range. Its
value is the number of decades to use for each half of the
linear range. For example, when *linscale* == 1.0 (the
default), the space used for the positive and negative
halves of the linear range will be equal to one decade in
the logarithmic range.
"""
if axis.axis_name == 'x':
base = kwargs.pop('basex', 10.0)
linthresh = kwargs.pop('linthreshx', 2.0)
subs = kwargs.pop('subsx', None)
linscale = kwargs.pop('linscalex', 1.0)
else:
base = kwargs.pop('basey', 10.0)
linthresh = kwargs.pop('linthreshy', 2.0)
subs = kwargs.pop('subsy', None)
linscale = kwargs.pop('linscaley', 1.0)
if base <= 1.0:
raise ValueError("'basex/basey' must be larger than 1")
if linthresh <= 0.0:
raise ValueError("'linthreshx/linthreshy' must be positive")
if linscale <= 0.0:
raise ValueError("'linscalex/linthreshy' must be positive")
self._transform = self.SymmetricalLogTransform(base,
linthresh,
linscale)
self.base = base
self.linthresh = linthresh
self.linscale = linscale
self.subs = subs
def set_default_locators_and_formatters(self, axis):
"""
Set the locators and formatters to specialized versions for
symmetrical log scaling.
"""
axis.set_major_locator(SymmetricalLogLocator(self.get_transform()))
axis.set_major_formatter(LogFormatterSciNotation(self.base))
axis.set_minor_locator(SymmetricalLogLocator(self.get_transform(),
self.subs))
axis.set_minor_formatter(NullFormatter())
def get_transform(self):
"""
Return a :class:`SymmetricalLogTransform` instance.
"""
return self._transform
class LogitTransform(Transform):
input_dims = 1
output_dims = 1
is_separable = True
has_inverse = True
def __init__(self, nonpos='mask'):
Transform.__init__(self)
self._nonpos = nonpos
self._clip = {"clip": True, "mask": False}[nonpos]
def transform_non_affine(self, a):
"""logit transform (base 10), masked or clipped"""
with np.errstate(divide="ignore", invalid="ignore"):
out = np.log10(a / (1 - a))
if self._clip: # See LogTransform for choice of clip value.
out[a <= 0] = -1000
out[1 <= a] = 1000
return out
def inverted(self):
return LogisticTransform(self._nonpos)
def __str__(self):
return "{}({!r})".format(type(self).__name__,
"clip" if self._clip else "mask")
class LogisticTransform(Transform):
input_dims = 1
output_dims = 1
is_separable = True
has_inverse = True
def __init__(self, nonpos='mask'):
Transform.__init__(self)
self._nonpos = nonpos
def transform_non_affine(self, a):
"""logistic transform (base 10)"""
return 1.0 / (1 + 10**(-a))
def inverted(self):
return LogitTransform(self._nonpos)
def __str__(self):
return "{}({!r})".format(type(self).__name__, self._nonpos)
class LogitScale(ScaleBase):
"""
Logit scale for data between zero and one, both excluded.
This scale is similar to a log scale close to zero and to one, and almost
linear around 0.5. It maps the interval ]0, 1[ onto ]-infty, +infty[.
"""
name = 'logit'
def __init__(self, axis, nonpos='mask'):
"""
*nonpos*: {'mask', 'clip'}
values beyond ]0, 1[ can be masked as invalid, or clipped to a number
very close to 0 or 1
"""
cbook._check_in_list(['mask', 'clip'], nonpos=nonpos)
self._transform = LogitTransform(nonpos)
def get_transform(self):
"""
Return a :class:`LogitTransform` instance.
"""
return self._transform
def set_default_locators_and_formatters(self, axis):
# ..., 0.01, 0.1, 0.5, 0.9, 0.99, ...
axis.set_major_locator(LogitLocator())
axis.set_major_formatter(LogitFormatter())
axis.set_minor_locator(LogitLocator(minor=True))
axis.set_minor_formatter(LogitFormatter())
def limit_range_for_scale(self, vmin, vmax, minpos):
"""
Limit the domain to values between 0 and 1 (excluded).
"""
if not np.isfinite(minpos):
minpos = 1e-7 # This value should rarely if ever
# end up with a visible effect.
return (minpos if vmin <= 0 else vmin,
1 - minpos if vmax >= 1 else vmax)
_scale_mapping = {
'linear': LinearScale,
'log': LogScale,
'symlog': SymmetricalLogScale,
'logit': LogitScale,
'function': FuncScale,
'functionlog': FuncScaleLog,
}
def get_scale_names():
return sorted(_scale_mapping)
def scale_factory(scale, axis, **kwargs):
"""
Return a scale class by name.
Parameters
----------
scale : {%(names)s}
axis : Axis
"""
scale = scale.lower()
if scale not in _scale_mapping:
raise ValueError("Unknown scale type '%s'" % scale)
return _scale_mapping[scale](axis, **kwargs)
if scale_factory.__doc__:
scale_factory.__doc__ = scale_factory.__doc__ % {
"names": ", ".join(get_scale_names())}
def register_scale(scale_class):
"""
Register a new kind of scale.
*scale_class* must be a subclass of :class:`ScaleBase`.
"""
_scale_mapping[scale_class.name] = scale_class
@cbook.deprecated(
'3.1', message='get_scale_docs() is considered private API since '
'3.1 and will be removed from the public API in 3.3.')
def get_scale_docs():
"""
Helper function for generating docstrings related to scales.
"""
return _get_scale_docs()
def _get_scale_docs():
"""
Helper function for generating docstrings related to scales.
"""
docs = []
for name, scale_class in _scale_mapping.items():
docs.extend([
f" {name!r}",
"",
textwrap.indent(inspect.getdoc(scale_class.__init__), " " * 8),
""
])
return "\n".join(docs)
docstring.interpd.update(
scale=' | '.join([repr(x) for x in get_scale_names()]),
scale_docs=_get_scale_docs().rstrip(),
)
|
589fd3fd84f94c0e0a20aab5f77eb26ac94670bdafdb1002e341b7fa58e37c46
|
"""
The rcsetup module contains the default values and the validation code for
customization using matplotlib's rc settings.
Each rc setting is assigned a default value and a function used to validate
any attempted changes to that setting. The default values and validation
functions are defined in the rcsetup module, and are used to construct the
rcParams global object which stores the settings and is referenced throughout
matplotlib.
These default values should be consistent with the default matplotlibrc file
that actually reflects the values given here. Any additions or deletions to the
parameter set listed here should also be visited to the
:file:`matplotlibrc.template` in matplotlib's root source directory.
"""
from collections.abc import Iterable, Mapping
from functools import reduce
import operator
import os
import re
from matplotlib import cbook
from matplotlib.cbook import ls_mapper
from matplotlib.fontconfig_pattern import parse_fontconfig_pattern
from matplotlib.colors import is_color_like
# Don't let the original cycler collide with our validating cycler
from cycler import Cycler, cycler as ccycler
# The capitalized forms are needed for ipython at present; this may
# change for later versions.
interactive_bk = ['GTK3Agg', 'GTK3Cairo',
'MacOSX',
'nbAgg',
'Qt4Agg', 'Qt4Cairo', 'Qt5Agg', 'Qt5Cairo',
'TkAgg', 'TkCairo',
'WebAgg',
'WX', 'WXAgg', 'WXCairo']
non_interactive_bk = ['agg', 'cairo',
'pdf', 'pgf', 'ps', 'svg', 'template']
all_backends = interactive_bk + non_interactive_bk
class ValidateInStrings(object):
def __init__(self, key, valid, ignorecase=False):
'valid is a list of legal strings'
self.key = key
self.ignorecase = ignorecase
def func(s):
if ignorecase:
return s.lower()
else:
return s
self.valid = {func(k): k for k in valid}
def __call__(self, s):
if self.ignorecase:
s = s.lower()
if s in self.valid:
return self.valid[s]
raise ValueError('Unrecognized %s string %r: valid strings are %s'
% (self.key, s, list(self.valid.values())))
def _listify_validator(scalar_validator, allow_stringlist=False):
def f(s):
if isinstance(s, str):
try:
return [scalar_validator(v.strip()) for v in s.split(',')
if v.strip()]
except Exception:
if allow_stringlist:
# Sometimes, a list of colors might be a single string
# of single-letter colornames. So give that a shot.
return [scalar_validator(v.strip())
for v in s if v.strip()]
else:
raise
# We should allow any generic sequence type, including generators,
# Numpy ndarrays, and pandas data structures. However, unordered
# sequences, such as sets, should be allowed but discouraged unless the
# user desires pseudorandom behavior.
elif isinstance(s, Iterable) and not isinstance(s, Mapping):
# The condition on this list comprehension will preserve the
# behavior of filtering out any empty strings (behavior was
# from the original validate_stringlist()), while allowing
# any non-string/text scalar values such as numbers and arrays.
return [scalar_validator(v) for v in s
if not isinstance(v, str) or v]
else:
raise ValueError("{!r} must be of type: string or non-dictionary "
"iterable".format(s))
try:
f.__name__ = "{}list".format(scalar_validator.__name__)
except AttributeError: # class instance.
f.__name__ = "{}List".format(type(scalar_validator).__name__)
f.__doc__ = scalar_validator.__doc__
return f
def validate_any(s):
return s
validate_anylist = _listify_validator(validate_any)
def validate_path_exists(s):
"""If s is a path, return s, else False"""
if s is None:
return None
if os.path.exists(s):
return s
else:
raise RuntimeError('"%s" should be a path but it does not exist' % s)
def validate_bool(b):
"""Convert b to a boolean or raise"""
if isinstance(b, str):
b = b.lower()
if b in ('t', 'y', 'yes', 'on', 'true', '1', 1, True):
return True
elif b in ('f', 'n', 'no', 'off', 'false', '0', 0, False):
return False
else:
raise ValueError('Could not convert "%s" to boolean' % b)
def validate_bool_maybe_none(b):
'Convert b to a boolean or raise'
if isinstance(b, str):
b = b.lower()
if b is None or b == 'none':
return None
if b in ('t', 'y', 'yes', 'on', 'true', '1', 1, True):
return True
elif b in ('f', 'n', 'no', 'off', 'false', '0', 0, False):
return False
else:
raise ValueError('Could not convert "%s" to boolean' % b)
def validate_float(s):
"""convert s to float or raise"""
try:
return float(s)
except ValueError:
raise ValueError('Could not convert "%s" to float' % s)
validate_floatlist = _listify_validator(validate_float)
def validate_float_or_None(s):
"""convert s to float, None or raise"""
# values directly from the rc file can only be strings,
# so we need to recognize the string "None" and convert
# it into the object. We will be case-sensitive here to
# avoid confusion between string values of 'none', which
# can be a valid string value for some other parameters.
if s is None or s == 'None':
return None
try:
return float(s)
except ValueError:
raise ValueError('Could not convert "%s" to float or None' % s)
def validate_string_or_None(s):
"""convert s to string or raise"""
if s is None:
return None
try:
return validate_string(s)
except ValueError:
raise ValueError('Could not convert "%s" to string' % s)
def _validate_tex_preamble(s):
if s is None or s == 'None':
return ""
try:
if isinstance(s, str):
return s
elif isinstance(s, Iterable):
return '\n'.join(s)
else:
raise TypeError
except TypeError:
raise ValueError('Could not convert "%s" to string' % s)
def validate_axisbelow(s):
try:
return validate_bool(s)
except ValueError:
if isinstance(s, str):
s = s.lower()
if s.startswith('line'):
return 'line'
raise ValueError('%s cannot be interpreted as'
' True, False, or "line"' % s)
def validate_dpi(s):
"""confirm s is string 'figure' or convert s to float or raise"""
if s == 'figure':
return s
try:
return float(s)
except ValueError:
raise ValueError('"%s" is not string "figure" or'
' could not convert "%s" to float' % (s, s))
def validate_int(s):
"""convert s to int or raise"""
try:
return int(s)
except ValueError:
raise ValueError('Could not convert "%s" to int' % s)
def validate_int_or_None(s):
"""if not None, tries to validate as an int"""
if s == 'None':
s = None
if s is None:
return None
try:
return int(s)
except ValueError:
raise ValueError('Could not convert "%s" to int' % s)
def validate_fonttype(s):
"""
confirm that this is a Postscript of PDF font type that we know how to
convert to
"""
fonttypes = {'type3': 3,
'truetype': 42}
try:
fonttype = validate_int(s)
except ValueError:
try:
return fonttypes[s.lower()]
except KeyError:
raise ValueError(
'Supported Postscript/PDF font types are %s' % list(fonttypes))
else:
if fonttype not in fonttypes.values():
raise ValueError(
'Supported Postscript/PDF font types are %s' %
list(fonttypes.values()))
return fonttype
_validate_standard_backends = ValidateInStrings(
'backend', all_backends, ignorecase=True)
_auto_backend_sentinel = object()
def validate_backend(s):
backend = (
s if s is _auto_backend_sentinel or s.startswith("module://")
else _validate_standard_backends(s))
return backend
@cbook.deprecated("3.1")
def validate_qt4(s):
if s is None:
return None
return ValidateInStrings("backend.qt4", ['PyQt4', 'PySide', 'PyQt4v2'])(s)
@cbook.deprecated("3.1")
def validate_qt5(s):
if s is None:
return None
return ValidateInStrings("backend.qt5", ['PyQt5', 'PySide2'])(s)
def validate_toolbar(s):
validator = ValidateInStrings(
'toolbar',
['None', 'toolbar2', 'toolmanager'],
ignorecase=True)
return validator(s)
_seq_err_msg = ('You must supply exactly {n} values, you provided {num} '
'values: {s}')
_str_err_msg = ('You must supply exactly {n} comma-separated values, you '
'provided {num} comma-separated values: {s}')
class validate_nseq_float(object):
def __init__(self, n=None, allow_none=False):
self.n = n
self.allow_none = allow_none
def __call__(self, s):
"""return a seq of n floats or raise"""
if isinstance(s, str):
s = [x.strip() for x in s.split(',')]
err_msg = _str_err_msg
else:
err_msg = _seq_err_msg
if self.n is not None and len(s) != self.n:
raise ValueError(err_msg.format(n=self.n, num=len(s), s=s))
try:
return [float(val)
if not self.allow_none or val is not None
else val
for val in s]
except ValueError:
raise ValueError('Could not convert all entries to floats')
class validate_nseq_int(object):
def __init__(self, n=None):
self.n = n
def __call__(self, s):
"""return a seq of n ints or raise"""
if isinstance(s, str):
s = [x.strip() for x in s.split(',')]
err_msg = _str_err_msg
else:
err_msg = _seq_err_msg
if self.n is not None and len(s) != self.n:
raise ValueError(err_msg.format(n=self.n, num=len(s), s=s))
try:
return [int(val) for val in s]
except ValueError:
raise ValueError('Could not convert all entries to ints')
def validate_color_or_inherit(s):
'return a valid color arg'
if s == 'inherit':
return s
return validate_color(s)
def validate_color_or_auto(s):
if s == 'auto':
return s
return validate_color(s)
def validate_color_for_prop_cycle(s):
# Special-case the N-th color cycle syntax, this obviously can not
# go in the color cycle.
if isinstance(s, bytes):
match = re.match(b'^C[0-9]$', s)
if match is not None:
raise ValueError('Can not put cycle reference ({cn!r}) in '
'prop_cycler'.format(cn=s))
elif isinstance(s, str):
match = re.match('^C[0-9]$', s)
if match is not None:
raise ValueError('Can not put cycle reference ({cn!r}) in '
'prop_cycler'.format(cn=s))
return validate_color(s)
def validate_color(s):
'return a valid color arg'
try:
if s.lower() == 'none':
return 'none'
except AttributeError:
pass
if isinstance(s, str):
if len(s) == 6 or len(s) == 8:
stmp = '#' + s
if is_color_like(stmp):
return stmp
if is_color_like(s):
return s
# If it is still valid, it must be a tuple.
colorarg = s
msg = ''
if s.find(',') >= 0:
# get rid of grouping symbols
stmp = ''.join([c for c in s if c.isdigit() or c == '.' or c == ','])
vals = stmp.split(',')
if len(vals) not in [3, 4]:
msg = '\nColor tuples must be of length 3 or 4'
else:
try:
colorarg = [float(val) for val in vals]
except ValueError:
msg = '\nCould not convert all entries to floats'
if not msg and is_color_like(colorarg):
return colorarg
raise ValueError('%s does not look like a color arg%s' % (s, msg))
validate_colorlist = _listify_validator(validate_color, allow_stringlist=True)
validate_colorlist.__doc__ = 'return a list of colorspecs'
def validate_string(s):
if isinstance(s, str):
# Always leave str as str and unicode as unicode
return s
else:
return str(s)
validate_stringlist = _listify_validator(str)
validate_stringlist.__doc__ = 'return a list'
validate_orientation = ValidateInStrings(
'orientation', ['landscape', 'portrait'])
def validate_aspect(s):
if s in ('auto', 'equal'):
return s
try:
return float(s)
except ValueError:
raise ValueError('not a valid aspect specification')
def validate_fontsize_None(s):
if s is None or s == 'None':
return None
else:
return validate_fontsize(s)
def validate_fontsize(s):
fontsizes = ['xx-small', 'x-small', 'small', 'medium', 'large',
'x-large', 'xx-large', 'smaller', 'larger']
if isinstance(s, str):
s = s.lower()
if s in fontsizes:
return s
try:
return float(s)
except ValueError:
raise ValueError("%s is not a valid font size. Valid font sizes "
"are %s." % (s, ", ".join(fontsizes)))
validate_fontsizelist = _listify_validator(validate_fontsize)
def validate_font_properties(s):
parse_fontconfig_pattern(s)
return s
validate_fontset = ValidateInStrings(
'fontset',
['dejavusans', 'dejavuserif', 'cm', 'stix', 'stixsans', 'custom'])
def validate_mathtext_default(s):
if s == "circled":
cbook.warn_deprecated(
"3.1", message="Support for setting the mathtext.default rcParam "
"to 'circled' is deprecated since %(since)s and will be removed "
"%(removal)s.")
return ValidateInStrings(
'default',
"rm cal it tt sf bf default bb frak circled scr regular".split())(s)
_validate_alignment = ValidateInStrings(
'alignment',
['center', 'top', 'bottom', 'baseline',
'center_baseline'])
_validate_verbose = ValidateInStrings(
'verbose',
['silent', 'helpful', 'debug', 'debug-annoying'])
@cbook.deprecated("3.1")
def validate_verbose(s):
return _validate_verbose(s)
def validate_whiskers(s):
if s == 'range':
return 'range'
else:
try:
v = validate_nseq_float(2)(s)
return v
except (TypeError, ValueError):
try:
v = float(s)
return v
except ValueError:
raise ValueError("Not a valid whisker value ['range', float, "
"(float, float)]")
def update_savefig_format(value):
# The old savefig.extension could also have a value of "auto", but
# the new savefig.format does not. We need to fix this here.
value = validate_string(value)
if value == 'auto':
value = 'png'
return value
validate_ps_papersize = ValidateInStrings(
'ps_papersize',
['auto', 'letter', 'legal', 'ledger',
'a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'a10',
'b0', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8', 'b9', 'b10',
], ignorecase=True)
def validate_ps_distiller(s):
if isinstance(s, str):
s = s.lower()
if s in ('none', None):
return None
elif s in ('false', False):
return False
elif s in ('ghostscript', 'xpdf'):
return s
else:
raise ValueError('matplotlibrc ps.usedistiller must either be none, '
'ghostscript or xpdf')
validate_joinstyle = ValidateInStrings('joinstyle',
['miter', 'round', 'bevel'],
ignorecase=True)
validate_joinstylelist = _listify_validator(validate_joinstyle)
validate_capstyle = ValidateInStrings('capstyle',
['butt', 'round', 'projecting'],
ignorecase=True)
validate_capstylelist = _listify_validator(validate_capstyle)
validate_fillstyle = ValidateInStrings('markers.fillstyle',
['full', 'left', 'right', 'bottom',
'top', 'none'])
validate_fillstylelist = _listify_validator(validate_fillstyle)
_validate_negative_linestyle = ValidateInStrings('negative_linestyle',
['solid', 'dashed'],
ignorecase=True)
def validate_markevery(s):
"""
Validate the markevery property of a Line2D object.
Parameters
----------
s : None, int, float, slice, length-2 tuple of ints,
length-2 tuple of floats, list of ints
Returns
-------
s : None, int, float, slice, length-2 tuple of ints,
length-2 tuple of floats, list of ints
"""
# Validate s against type slice
if isinstance(s, slice):
return s
# Validate s against type tuple
if isinstance(s, tuple):
tupMaxLength = 2
tupType = type(s[0])
if len(s) != tupMaxLength:
raise TypeError("'markevery' tuple must have a length of "
"%d" % (tupMaxLength))
if tupType is int and not all(isinstance(e, int) for e in s):
raise TypeError("'markevery' tuple with first element of "
"type int must have all elements of type "
"int")
if tupType is float and not all(isinstance(e, float) for e in s):
raise TypeError("'markevery' tuple with first element of "
"type float must have all elements of type "
"float")
if tupType is not float and tupType is not int:
raise TypeError("'markevery' tuple contains an invalid type")
# Validate s against type list
elif isinstance(s, list):
if not all(isinstance(e, int) for e in s):
raise TypeError("'markevery' list must have all elements of "
"type int")
# Validate s against type float int and None
elif not isinstance(s, (float, int)):
if s is not None:
raise TypeError("'markevery' is of an invalid type")
return s
validate_markeverylist = _listify_validator(validate_markevery)
validate_legend_loc = ValidateInStrings(
'legend_loc',
['best',
'upper right',
'upper left',
'lower left',
'lower right',
'right',
'center left',
'center right',
'lower center',
'upper center',
'center'], ignorecase=True)
def validate_svg_fonttype(s):
if s in ["none", "path"]:
return s
raise ValueError("Unrecognized svg.fonttype string '{}'; "
"valid strings are 'none', 'path'")
def validate_hinting(s):
if s in (True, False):
return s
if s.lower() in ('auto', 'native', 'either', 'none'):
return s.lower()
raise ValueError("hinting should be 'auto', 'native', 'either' or 'none'")
validate_pgf_texsystem = ValidateInStrings('pgf.texsystem',
['xelatex', 'lualatex', 'pdflatex'])
validate_movie_writer = ValidateInStrings('animation.writer',
['ffmpeg', 'ffmpeg_file',
'avconv', 'avconv_file',
'imagemagick', 'imagemagick_file',
'html'])
validate_movie_frame_fmt = ValidateInStrings('animation.frame_format',
['png', 'jpeg', 'tiff', 'raw', 'rgba'])
validate_axis_locator = ValidateInStrings('major', ['minor', 'both', 'major'])
validate_movie_html_fmt = ValidateInStrings('animation.html',
['html5', 'jshtml', 'none'])
def validate_bbox(s):
if isinstance(s, str):
s = s.lower()
if s == 'tight':
return s
if s == 'standard':
return None
raise ValueError("bbox should be 'tight' or 'standard'")
elif s is not None:
# Backwards compatibility. None is equivalent to 'standard'.
raise ValueError("bbox should be 'tight' or 'standard'")
return s
def validate_sketch(s):
if isinstance(s, str):
s = s.lower()
if s == 'none' or s is None:
return None
if isinstance(s, str):
result = tuple([float(v.strip()) for v in s.split(',')])
elif isinstance(s, (list, tuple)):
result = tuple([float(v) for v in s])
if len(result) != 3:
raise ValueError("path.sketch must be a tuple (scale, length, randomness)")
return result
class ValidateInterval(object):
"""
Value must be in interval
"""
def __init__(self, vmin, vmax, closedmin=True, closedmax=True):
self.vmin = vmin
self.vmax = vmax
self.cmin = closedmin
self.cmax = closedmax
def __call__(self, s):
try:
s = float(s)
except ValueError:
raise RuntimeError('Value must be a float; found "%s"' % s)
if self.cmin and s < self.vmin:
raise RuntimeError('Value must be >= %f; found "%f"' %
(self.vmin, s))
elif not self.cmin and s <= self.vmin:
raise RuntimeError('Value must be > %f; found "%f"' %
(self.vmin, s))
if self.cmax and s > self.vmax:
raise RuntimeError('Value must be <= %f; found "%f"' %
(self.vmax, s))
elif not self.cmax and s >= self.vmax:
raise RuntimeError('Value must be < %f; found "%f"' %
(self.vmax, s))
return s
validate_grid_axis = ValidateInStrings('axes.grid.axis', ['x', 'y', 'both'])
def validate_hatch(s):
"""
Validate a hatch pattern.
A hatch pattern string can have any sequence of the following
characters: ``\\ / | - + * . x o O``.
"""
if not isinstance(s, str):
raise ValueError("Hatch pattern must be a string")
unknown = set(s) - {'\\', '/', '|', '-', '+', '*', '.', 'x', 'o', 'O'}
if unknown:
raise ValueError("Unknown hatch symbol(s): %s" % list(unknown))
return s
validate_hatchlist = _listify_validator(validate_hatch)
validate_dashlist = _listify_validator(validate_nseq_float(allow_none=True))
_prop_validators = {
'color': _listify_validator(validate_color_for_prop_cycle,
allow_stringlist=True),
'linewidth': validate_floatlist,
'linestyle': validate_stringlist,
'facecolor': validate_colorlist,
'edgecolor': validate_colorlist,
'joinstyle': validate_joinstylelist,
'capstyle': validate_capstylelist,
'fillstyle': validate_fillstylelist,
'markerfacecolor': validate_colorlist,
'markersize': validate_floatlist,
'markeredgewidth': validate_floatlist,
'markeredgecolor': validate_colorlist,
'markevery': validate_markeverylist,
'alpha': validate_floatlist,
'marker': validate_stringlist,
'hatch': validate_hatchlist,
'dashes': validate_dashlist,
}
_prop_aliases = {
'c': 'color',
'lw': 'linewidth',
'ls': 'linestyle',
'fc': 'facecolor',
'ec': 'edgecolor',
'mfc': 'markerfacecolor',
'mec': 'markeredgecolor',
'mew': 'markeredgewidth',
'ms': 'markersize',
}
def cycler(*args, **kwargs):
"""
Creates a `~cycler.Cycler` object much like :func:`cycler.cycler`,
but includes input validation.
Call signatures::
cycler(cycler)
cycler(label=values[, label2=values2[, ...]])
cycler(label, values)
Form 1 copies a given `~cycler.Cycler` object.
Form 2 creates a `~cycler.Cycler` which cycles over one or more
properties simultaneously. If multiple properties are given, their
value lists must have the same length.
Form 3 creates a `~cycler.Cycler` for a single property. This form
exists for compatibility with the original cycler. Its use is
discouraged in favor of the kwarg form, i.e. ``cycler(label=values)``.
Parameters
----------
cycler : Cycler
Copy constructor for Cycler.
label : str
The property key. Must be a valid `.Artist` property.
For example, 'color' or 'linestyle'. Aliases are allowed,
such as 'c' for 'color' and 'lw' for 'linewidth'.
values : iterable
Finite-length iterable of the property values. These values
are validated and will raise a ValueError if invalid.
Returns
-------
cycler : Cycler
A new :class:`~cycler.Cycler` for the given properties.
Examples
--------
Creating a cycler for a single property:
>>> c = cycler(color=['red', 'green', 'blue'])
Creating a cycler for simultaneously cycling over multiple properties
(e.g. red circle, green plus, blue cross):
>>> c = cycler(color=['red', 'green', 'blue'],
... marker=['o', '+', 'x'])
"""
if args and kwargs:
raise TypeError("cycler() can only accept positional OR keyword "
"arguments -- not both.")
elif not args and not kwargs:
raise TypeError("cycler() must have positional OR keyword arguments")
if len(args) == 1:
if not isinstance(args[0], Cycler):
raise TypeError("If only one positional argument given, it must "
" be a Cycler instance.")
return validate_cycler(args[0])
elif len(args) == 2:
pairs = [(args[0], args[1])]
elif len(args) > 2:
raise TypeError("No more than 2 positional arguments allowed")
else:
pairs = kwargs.items()
validated = []
for prop, vals in pairs:
norm_prop = _prop_aliases.get(prop, prop)
validator = _prop_validators.get(norm_prop, None)
if validator is None:
raise TypeError("Unknown artist property: %s" % prop)
vals = validator(vals)
# We will normalize the property names as well to reduce
# the amount of alias handling code elsewhere.
validated.append((norm_prop, vals))
return reduce(operator.add, (ccycler(k, v) for k, v in validated))
def validate_cycler(s):
'return a Cycler object from a string repr or the object itself'
if isinstance(s, str):
try:
# TODO: We might want to rethink this...
# While I think I have it quite locked down,
# it is execution of arbitrary code without
# sanitation.
# Combine this with the possibility that rcparams
# might come from the internet (future plans), this
# could be downright dangerous.
# I locked it down by only having the 'cycler()' function
# available.
# UPDATE: Partly plugging a security hole.
# I really should have read this:
# http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html
# We should replace this eval with a combo of PyParsing and
# ast.literal_eval()
if '.__' in s.replace(' ', ''):
raise ValueError("'%s' seems to have dunder methods. Raising"
" an exception for your safety")
s = eval(s, {'cycler': cycler, '__builtins__': {}})
except BaseException as e:
raise ValueError("'%s' is not a valid cycler construction: %s" %
(s, e))
# Should make sure what comes from the above eval()
# is a Cycler object.
if isinstance(s, Cycler):
cycler_inst = s
else:
raise ValueError("object was not a string or Cycler instance: %s" % s)
unknowns = cycler_inst.keys - (set(_prop_validators) | set(_prop_aliases))
if unknowns:
raise ValueError("Unknown artist properties: %s" % unknowns)
# Not a full validation, but it'll at least normalize property names
# A fuller validation would require v0.10 of cycler.
checker = set()
for prop in cycler_inst.keys:
norm_prop = _prop_aliases.get(prop, prop)
if norm_prop != prop and norm_prop in cycler_inst.keys:
raise ValueError("Cannot specify both '{0}' and alias '{1}'"
" in the same prop_cycle".format(norm_prop, prop))
if norm_prop in checker:
raise ValueError("Another property was already aliased to '{0}'."
" Collision normalizing '{1}'.".format(norm_prop,
prop))
checker.update([norm_prop])
# This is just an extra-careful check, just in case there is some
# edge-case I haven't thought of.
assert len(checker) == len(cycler_inst.keys)
# Now, it should be safe to mutate this cycler
for prop in cycler_inst.keys:
norm_prop = _prop_aliases.get(prop, prop)
cycler_inst.change_key(prop, norm_prop)
for key, vals in cycler_inst.by_key().items():
_prop_validators[key](vals)
return cycler_inst
def validate_hist_bins(s):
valid_strs = ["auto", "sturges", "fd", "doane", "scott", "rice", "sqrt"]
if isinstance(s, str) and s in valid_strs:
return s
try:
return int(s)
except (TypeError, ValueError):
pass
try:
return validate_floatlist(s)
except ValueError:
pass
raise ValueError("'hist.bins' must be one of {}, an int or"
" a sequence of floats".format(valid_strs))
def validate_animation_writer_path(p):
# Make sure it's a string and then figure out if the animations
# are already loaded and reset the writers (which will validate
# the path on next call)
if not isinstance(p, str):
raise ValueError("path must be a (unicode) string")
from sys import modules
# set dirty, so that the next call to the registry will re-evaluate
# the state.
# only set dirty if already loaded. If not loaded, the load will
# trigger the checks.
if "matplotlib.animation" in modules:
modules["matplotlib.animation"].writers.set_dirty()
return p
def validate_webagg_address(s):
if s is not None:
import socket
try:
socket.inet_aton(s)
except socket.error as e:
raise ValueError("'webagg.address' is not a valid IP address")
return s
raise ValueError("'webagg.address' is not a valid IP address")
# A validator dedicated to the named line styles, based on the items in
# ls_mapper, and a list of possible strings read from Line2D.set_linestyle
_validate_named_linestyle = ValidateInStrings(
'linestyle',
[*ls_mapper.keys(), *ls_mapper.values(), 'None', 'none', ' ', ''],
ignorecase=True)
def _validate_linestyle(ls):
"""
A validator for all possible line styles, the named ones *and*
the on-off ink sequences.
"""
# Look first for a valid named line style, like '--' or 'solid' Also
# includes bytes(-arrays) here (they all fail _validate_named_linestyle);
# otherwise, if *ls* is of even-length, it will be passed to the instance
# of validate_nseq_float, which will return an absurd on-off ink
# sequence...
if isinstance(ls, (str, bytes, bytearray)):
return _validate_named_linestyle(ls)
# Look for an on-off ink sequence (in points) *of even length*.
# Offset is set to None.
try:
if len(ls) % 2 != 0:
raise ValueError("the linestyle sequence {!r} is not of even "
"length.".format(ls))
return (None, validate_nseq_float()(ls))
except (ValueError, TypeError):
# TypeError can be raised inside the instance of validate_nseq_float,
# by wrong types passed to float(), like NoneType.
raise ValueError("linestyle {!r} is not a valid on-off ink "
"sequence.".format(ls))
validate_axes_titlelocation = ValidateInStrings('axes.titlelocation', ['left', 'center', 'right'])
# a map from key -> value, converter
defaultParams = {
'backend': [_auto_backend_sentinel, validate_backend],
'backend_fallback': [True, validate_bool],
'webagg.port': [8988, validate_int],
'webagg.address': ['127.0.0.1', validate_webagg_address],
'webagg.open_in_browser': [True, validate_bool],
'webagg.port_retries': [50, validate_int],
'toolbar': ['toolbar2', validate_toolbar],
'datapath': [None, validate_path_exists], # handled by
# _get_data_path_cached
'interactive': [False, validate_bool],
'timezone': ['UTC', validate_string],
# the verbosity setting
'verbose.level': ['silent', _validate_verbose],
'verbose.fileo': ['sys.stdout', validate_string],
# line props
'lines.linewidth': [1.5, validate_float], # line width in points
'lines.linestyle': ['-', _validate_linestyle], # solid line
'lines.color': ['C0', validate_color], # first color in color cycle
'lines.marker': ['None', validate_string], # marker name
'lines.markerfacecolor': ['auto', validate_color_or_auto], # default color
'lines.markeredgecolor': ['auto', validate_color_or_auto], # default color
'lines.markeredgewidth': [1.0, validate_float],
'lines.markersize': [6, validate_float], # markersize, in points
'lines.antialiased': [True, validate_bool], # antialiased (no jaggies)
'lines.dash_joinstyle': ['round', validate_joinstyle],
'lines.solid_joinstyle': ['round', validate_joinstyle],
'lines.dash_capstyle': ['butt', validate_capstyle],
'lines.solid_capstyle': ['projecting', validate_capstyle],
'lines.dashed_pattern': [[3.7, 1.6], validate_nseq_float(allow_none=True)],
'lines.dashdot_pattern': [[6.4, 1.6, 1, 1.6],
validate_nseq_float(allow_none=True)],
'lines.dotted_pattern': [[1, 1.65], validate_nseq_float(allow_none=True)],
'lines.scale_dashes': [True, validate_bool],
# marker props
'markers.fillstyle': ['full', validate_fillstyle],
## patch props
'patch.linewidth': [1.0, validate_float], # line width in points
'patch.edgecolor': ['black', validate_color],
'patch.force_edgecolor': [False, validate_bool],
'patch.facecolor': ['C0', validate_color], # first color in cycle
'patch.antialiased': [True, validate_bool], # antialiased (no jaggies)
## hatch props
'hatch.color': ['black', validate_color],
'hatch.linewidth': [1.0, validate_float],
## Histogram properties
'hist.bins': [10, validate_hist_bins],
## Boxplot properties
'boxplot.notch': [False, validate_bool],
'boxplot.vertical': [True, validate_bool],
'boxplot.whiskers': [1.5, validate_whiskers],
'boxplot.bootstrap': [None, validate_int_or_None],
'boxplot.patchartist': [False, validate_bool],
'boxplot.showmeans': [False, validate_bool],
'boxplot.showcaps': [True, validate_bool],
'boxplot.showbox': [True, validate_bool],
'boxplot.showfliers': [True, validate_bool],
'boxplot.meanline': [False, validate_bool],
'boxplot.flierprops.color': ['black', validate_color],
'boxplot.flierprops.marker': ['o', validate_string],
'boxplot.flierprops.markerfacecolor': ['none', validate_color_or_auto],
'boxplot.flierprops.markeredgecolor': ['black', validate_color],
'boxplot.flierprops.markeredgewidth': [1.0, validate_float],
'boxplot.flierprops.markersize': [6, validate_float],
'boxplot.flierprops.linestyle': ['none', _validate_linestyle],
'boxplot.flierprops.linewidth': [1.0, validate_float],
'boxplot.boxprops.color': ['black', validate_color],
'boxplot.boxprops.linewidth': [1.0, validate_float],
'boxplot.boxprops.linestyle': ['-', _validate_linestyle],
'boxplot.whiskerprops.color': ['black', validate_color],
'boxplot.whiskerprops.linewidth': [1.0, validate_float],
'boxplot.whiskerprops.linestyle': ['-', _validate_linestyle],
'boxplot.capprops.color': ['black', validate_color],
'boxplot.capprops.linewidth': [1.0, validate_float],
'boxplot.capprops.linestyle': ['-', _validate_linestyle],
'boxplot.medianprops.color': ['C1', validate_color],
'boxplot.medianprops.linewidth': [1.0, validate_float],
'boxplot.medianprops.linestyle': ['-', _validate_linestyle],
'boxplot.meanprops.color': ['C2', validate_color],
'boxplot.meanprops.marker': ['^', validate_string],
'boxplot.meanprops.markerfacecolor': ['C2', validate_color],
'boxplot.meanprops.markeredgecolor': ['C2', validate_color],
'boxplot.meanprops.markersize': [6, validate_float],
'boxplot.meanprops.linestyle': ['--', _validate_linestyle],
'boxplot.meanprops.linewidth': [1.0, validate_float],
## font props
'font.family': [['sans-serif'], validate_stringlist], # used by text object
'font.style': ['normal', validate_string],
'font.variant': ['normal', validate_string],
'font.stretch': ['normal', validate_string],
'font.weight': ['normal', validate_string],
'font.size': [10, validate_float], # Base font size in points
'font.serif': [['DejaVu Serif', 'Bitstream Vera Serif',
'Computer Modern Roman',
'New Century Schoolbook', 'Century Schoolbook L',
'Utopia', 'ITC Bookman', 'Bookman',
'Nimbus Roman No9 L', 'Times New Roman',
'Times', 'Palatino', 'Charter', 'serif'],
validate_stringlist],
'font.sans-serif': [['DejaVu Sans', 'Bitstream Vera Sans',
'Computer Modern Sans Serif',
'Lucida Grande', 'Verdana', 'Geneva', 'Lucid',
'Arial', 'Helvetica', 'Avant Garde', 'sans-serif'],
validate_stringlist],
'font.cursive': [['Apple Chancery', 'Textile', 'Zapf Chancery',
'Sand', 'Script MT', 'Felipa', 'cursive'],
validate_stringlist],
'font.fantasy': [['Comic Sans MS', 'Chicago', 'Charcoal', 'Impact',
'Western', 'Humor Sans', 'xkcd', 'fantasy'],
validate_stringlist],
'font.monospace': [['DejaVu Sans Mono', 'Bitstream Vera Sans Mono',
'Computer Modern Typewriter',
'Andale Mono', 'Nimbus Mono L', 'Courier New',
'Courier', 'Fixed', 'Terminal', 'monospace'],
validate_stringlist],
# text props
'text.color': ['black', validate_color],
'text.usetex': [False, validate_bool],
'text.latex.unicode': [True, validate_bool],
'text.latex.preamble': ['', _validate_tex_preamble],
'text.latex.preview': [False, validate_bool],
'text.hinting': ['auto', validate_hinting],
'text.hinting_factor': [8, validate_int],
'text.antialiased': [True, validate_bool],
'mathtext.cal': ['cursive', validate_font_properties],
'mathtext.rm': ['sans', validate_font_properties],
'mathtext.tt': ['monospace', validate_font_properties],
'mathtext.it': ['sans:italic', validate_font_properties],
'mathtext.bf': ['sans:bold', validate_font_properties],
'mathtext.sf': ['sans', validate_font_properties],
'mathtext.fontset': ['dejavusans', validate_fontset],
'mathtext.default': ['it', validate_mathtext_default],
'mathtext.fallback_to_cm': [True, validate_bool],
'image.aspect': ['equal', validate_aspect], # equal, auto, a number
'image.interpolation': ['nearest', validate_string],
'image.cmap': ['viridis', validate_string], # gray, jet, etc.
'image.lut': [256, validate_int], # lookup table
'image.origin': ['upper',
ValidateInStrings('image.origin', ['upper', 'lower'])],
'image.resample': [True, validate_bool],
# Specify whether vector graphics backends will combine all images on a
# set of axes into a single composite image
'image.composite_image': [True, validate_bool],
# contour props
'contour.negative_linestyle': ['dashed', _validate_linestyle],
'contour.corner_mask': [True, validate_bool],
# errorbar props
'errorbar.capsize': [0, validate_float],
# axes props
'axes.axisbelow': ['line', validate_axisbelow],
'axes.facecolor': ['white', validate_color], # background color
'axes.edgecolor': ['black', validate_color], # edge color
'axes.linewidth': [0.8, validate_float], # edge linewidth
'axes.spines.left': [True, validate_bool], # Set visibility of axes
'axes.spines.right': [True, validate_bool], # 'spines', the lines
'axes.spines.bottom': [True, validate_bool], # around the chart
'axes.spines.top': [True, validate_bool], # denoting data boundary
'axes.titlesize': ['large', validate_fontsize], # fontsize of the
# axes title
'axes.titlelocation': ['center', validate_axes_titlelocation], # alignment of axes title
'axes.titleweight': ['normal', validate_string], # font weight of axes title
'axes.titlepad': [6.0, validate_float], # pad from axes top to title in points
'axes.grid': [False, validate_bool], # display grid or not
'axes.grid.which': ['major', validate_axis_locator], # set whether the gid are by
# default draw on 'major'
# 'minor' or 'both' kind of
# axis locator
'axes.grid.axis': ['both', validate_grid_axis], # grid type:
# 'x', 'y', or 'both'
'axes.labelsize': ['medium', validate_fontsize], # fontsize of the
# x any y labels
'axes.labelpad': [4.0, validate_float], # space between label and axis
'axes.labelweight': ['normal', validate_string], # fontsize of the x any y labels
'axes.labelcolor': ['black', validate_color], # color of axis label
'axes.formatter.limits': [[-7, 7], validate_nseq_int(2)],
# use scientific notation if log10
# of the axis range is smaller than the
# first or larger than the second
'axes.formatter.use_locale': [False, validate_bool],
# Use the current locale to format ticks
'axes.formatter.use_mathtext': [False, validate_bool],
'axes.formatter.min_exponent': [0, validate_int], # minimum exponent to format in scientific notation
'axes.formatter.useoffset': [True, validate_bool],
'axes.formatter.offset_threshold': [4, validate_int],
'axes.unicode_minus': [True, validate_bool],
# This entry can be either a cycler object or a
# string repr of a cycler-object, which gets eval()'ed
# to create the object.
'axes.prop_cycle': [
ccycler('color',
['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728',
'#9467bd', '#8c564b', '#e377c2', '#7f7f7f',
'#bcbd22', '#17becf']),
validate_cycler],
# If 'data', axes limits are set close to the data.
# If 'round_numbers' axes limits are set to the nearest round numbers.
'axes.autolimit_mode': [
'data',
ValidateInStrings('autolimit_mode', ['data', 'round_numbers'])],
'axes.xmargin': [0.05, ValidateInterval(0, 1,
closedmin=True,
closedmax=True)], # margin added to xaxis
'axes.ymargin': [0.05, ValidateInterval(0, 1,
closedmin=True,
closedmax=True)], # margin added to yaxis
'polaraxes.grid': [True, validate_bool], # display polar grid or
# not
'axes3d.grid': [True, validate_bool], # display 3d grid
# scatter props
'scatter.marker': ['o', validate_string],
'scatter.edgecolors': ['face', validate_string],
# TODO validate that these are valid datetime format strings
'date.autoformatter.year': ['%Y', validate_string],
'date.autoformatter.month': ['%Y-%m', validate_string],
'date.autoformatter.day': ['%Y-%m-%d', validate_string],
'date.autoformatter.hour': ['%m-%d %H', validate_string],
'date.autoformatter.minute': ['%d %H:%M', validate_string],
'date.autoformatter.second': ['%H:%M:%S', validate_string],
'date.autoformatter.microsecond': ['%M:%S.%f', validate_string],
#legend properties
'legend.fancybox': [True, validate_bool],
'legend.loc': ['best', validate_legend_loc],
# the number of points in the legend line
'legend.numpoints': [1, validate_int],
# the number of points in the legend line for scatter
'legend.scatterpoints': [1, validate_int],
'legend.fontsize': ['medium', validate_fontsize],
'legend.title_fontsize': [None, validate_fontsize_None],
# the relative size of legend markers vs. original
'legend.markerscale': [1.0, validate_float],
'legend.shadow': [False, validate_bool],
# whether or not to draw a frame around legend
'legend.frameon': [True, validate_bool],
# alpha value of the legend frame
'legend.framealpha': [0.8, validate_float_or_None],
## the following dimensions are in fraction of the font size
'legend.borderpad': [0.4, validate_float], # units are fontsize
# the vertical space between the legend entries
'legend.labelspacing': [0.5, validate_float],
# the length of the legend lines
'legend.handlelength': [2., validate_float],
# the length of the legend lines
'legend.handleheight': [0.7, validate_float],
# the space between the legend line and legend text
'legend.handletextpad': [.8, validate_float],
# the border between the axes and legend edge
'legend.borderaxespad': [0.5, validate_float],
# the border between the axes and legend edge
'legend.columnspacing': [2., validate_float],
'legend.facecolor': ['inherit', validate_color_or_inherit],
'legend.edgecolor': ['0.8', validate_color_or_inherit],
# tick properties
'xtick.top': [False, validate_bool], # draw ticks on the top side
'xtick.bottom': [True, validate_bool], # draw ticks on the bottom side
'xtick.labeltop': [False, validate_bool], # draw label on the top
'xtick.labelbottom': [True, validate_bool], # draw label on the bottom
'xtick.major.size': [3.5, validate_float], # major xtick size in points
'xtick.minor.size': [2, validate_float], # minor xtick size in points
'xtick.major.width': [0.8, validate_float], # major xtick width in points
'xtick.minor.width': [0.6, validate_float], # minor xtick width in points
'xtick.major.pad': [3.5, validate_float], # distance to label in points
'xtick.minor.pad': [3.4, validate_float], # distance to label in points
'xtick.color': ['black', validate_color], # color of the xtick labels
'xtick.minor.visible': [False, validate_bool], # visibility of the x axis minor ticks
'xtick.minor.top': [True, validate_bool], # draw x axis top minor ticks
'xtick.minor.bottom': [True, validate_bool], # draw x axis bottom minor ticks
'xtick.major.top': [True, validate_bool], # draw x axis top major ticks
'xtick.major.bottom': [True, validate_bool], # draw x axis bottom major ticks
# fontsize of the xtick labels
'xtick.labelsize': ['medium', validate_fontsize],
'xtick.direction': ['out', validate_string], # direction of xticks
'xtick.alignment': ["center", _validate_alignment],
'ytick.left': [True, validate_bool], # draw ticks on the left side
'ytick.right': [False, validate_bool], # draw ticks on the right side
'ytick.labelleft': [True, validate_bool], # draw tick labels on the left side
'ytick.labelright': [False, validate_bool], # draw tick labels on the right side
'ytick.major.size': [3.5, validate_float], # major ytick size in points
'ytick.minor.size': [2, validate_float], # minor ytick size in points
'ytick.major.width': [0.8, validate_float], # major ytick width in points
'ytick.minor.width': [0.6, validate_float], # minor ytick width in points
'ytick.major.pad': [3.5, validate_float], # distance to label in points
'ytick.minor.pad': [3.4, validate_float], # distance to label in points
'ytick.color': ['black', validate_color], # color of the ytick labels
'ytick.minor.visible': [False, validate_bool], # visibility of the y axis minor ticks
'ytick.minor.left': [True, validate_bool], # draw y axis left minor ticks
'ytick.minor.right': [True, validate_bool], # draw y axis right minor ticks
'ytick.major.left': [True, validate_bool], # draw y axis left major ticks
'ytick.major.right': [True, validate_bool], # draw y axis right major ticks
# fontsize of the ytick labels
'ytick.labelsize': ['medium', validate_fontsize],
'ytick.direction': ['out', validate_string], # direction of yticks
'ytick.alignment': ["center_baseline", _validate_alignment],
'grid.color': ['#b0b0b0', validate_color], # grid color
'grid.linestyle': ['-', _validate_linestyle], # solid
'grid.linewidth': [0.8, validate_float], # in points
'grid.alpha': [1.0, validate_float],
## figure props
# figure title
'figure.titlesize': ['large', validate_fontsize],
'figure.titleweight': ['normal', validate_string],
# figure size in inches: width by height
'figure.figsize': [[6.4, 4.8], validate_nseq_float(2)],
'figure.dpi': [100, validate_float], # DPI
'figure.facecolor': ['white', validate_color],
'figure.edgecolor': ['white', validate_color],
'figure.frameon': [True, validate_bool],
'figure.autolayout': [False, validate_bool],
'figure.max_open_warning': [20, validate_int],
'figure.subplot.left': [0.125, ValidateInterval(0, 1, closedmin=True,
closedmax=True)],
'figure.subplot.right': [0.9, ValidateInterval(0, 1, closedmin=True,
closedmax=True)],
'figure.subplot.bottom': [0.11, ValidateInterval(0, 1, closedmin=True,
closedmax=True)],
'figure.subplot.top': [0.88, ValidateInterval(0, 1, closedmin=True,
closedmax=True)],
'figure.subplot.wspace': [0.2, ValidateInterval(0, 1, closedmin=True,
closedmax=False)],
'figure.subplot.hspace': [0.2, ValidateInterval(0, 1, closedmin=True,
closedmax=False)],
# do constrained_layout.
'figure.constrained_layout.use': [False, validate_bool],
# wspace and hspace are fraction of adjacent subplots to use
# for space. Much smaller than above because we don't need
# room for the text.
'figure.constrained_layout.hspace': [0.02, ValidateInterval(
0, 1, closedmin=True, closedmax=False)],
'figure.constrained_layout.wspace': [0.02, ValidateInterval(
0, 1, closedmin=True, closedmax=False)],
# This is a buffer around the axes in inches. This is 3pts.
'figure.constrained_layout.h_pad': [0.04167, validate_float],
'figure.constrained_layout.w_pad': [0.04167, validate_float],
## Saving figure's properties
'savefig.dpi': ['figure', validate_dpi], # DPI
'savefig.facecolor': ['white', validate_color],
'savefig.edgecolor': ['white', validate_color],
'savefig.frameon': [True, validate_bool],
'savefig.orientation': ['portrait', validate_orientation],
'savefig.jpeg_quality': [95, validate_int],
# value checked by backend at runtime
'savefig.format': ['png', update_savefig_format],
# options are 'tight', or 'standard'. 'standard' validates to None.
'savefig.bbox': ['standard', validate_bbox],
'savefig.pad_inches': [0.1, validate_float],
# default directory in savefig dialog box
'savefig.directory': ['~', validate_string],
'savefig.transparent': [False, validate_bool],
# Maintain shell focus for TkAgg
'tk.window_focus': [False, validate_bool],
# Set the papersize/type
'ps.papersize': ['letter', validate_ps_papersize],
'ps.useafm': [False, validate_bool],
# use ghostscript or xpdf to distill ps output
'ps.usedistiller': [False, validate_ps_distiller],
'ps.distiller.res': [6000, validate_int], # dpi
'ps.fonttype': [3, validate_fonttype], # 3 (Type3) or 42 (Truetype)
# compression level from 0 to 9; 0 to disable
'pdf.compression': [6, validate_int],
# ignore any color-setting commands from the frontend
'pdf.inheritcolor': [False, validate_bool],
# use only the 14 PDF core fonts embedded in every PDF viewing application
'pdf.use14corefonts': [False, validate_bool],
'pdf.fonttype': [3, validate_fonttype], # 3 (Type3) or 42 (Truetype)
'pgf.debug': [False, validate_bool], # output debug information
# choose latex application for creating pdf files (xelatex/lualatex)
'pgf.texsystem': ['xelatex', validate_pgf_texsystem],
# use matplotlib rc settings for font configuration
'pgf.rcfonts': [True, validate_bool],
# provide a custom preamble for the latex process
'pgf.preamble': ['', _validate_tex_preamble],
# write raster image data directly into the svg file
'svg.image_inline': [True, validate_bool],
# True to save all characters as paths in the SVG
'svg.fonttype': ['path', validate_svg_fonttype],
'svg.hashsalt': [None, validate_string_or_None],
# set this when you want to generate hardcopy docstring
'docstring.hardcopy': [False, validate_bool],
'path.simplify': [True, validate_bool],
'path.simplify_threshold': [1.0 / 9.0, ValidateInterval(0.0, 1.0)],
'path.snap': [True, validate_bool],
'path.sketch': [None, validate_sketch],
'path.effects': [[], validate_any],
'agg.path.chunksize': [0, validate_int], # 0 to disable chunking;
# key-mappings (multi-character mappings should be a list/tuple)
'keymap.fullscreen': [['f', 'ctrl+f'], validate_stringlist],
'keymap.home': [['h', 'r', 'home'], validate_stringlist],
'keymap.back': [['left', 'c', 'backspace', 'MouseButton.BACK'],
validate_stringlist],
'keymap.forward': [['right', 'v', 'MouseButton.FORWARD'],
validate_stringlist],
'keymap.pan': [['p'], validate_stringlist],
'keymap.zoom': [['o'], validate_stringlist],
'keymap.save': [['s', 'ctrl+s'], validate_stringlist],
'keymap.quit': [['ctrl+w', 'cmd+w', 'q'], validate_stringlist],
'keymap.quit_all': [['W', 'cmd+W', 'Q'], validate_stringlist],
'keymap.grid': [['g'], validate_stringlist],
'keymap.grid_minor': [['G'], validate_stringlist],
'keymap.yscale': [['l'], validate_stringlist],
'keymap.xscale': [['k', 'L'], validate_stringlist],
'keymap.all_axes': [['a'], validate_stringlist],
'keymap.help': [['f1'], validate_stringlist],
'keymap.copy': [['ctrl+c', 'cmd+c'], validate_stringlist],
# sample data
'examples.directory': ['', validate_string],
# Animation settings
'animation.html': ['none', validate_movie_html_fmt],
# Limit, in MB, of size of base64 encoded animation in HTML
# (i.e. IPython notebook)
'animation.embed_limit': [20, validate_float],
'animation.writer': ['ffmpeg', validate_movie_writer],
'animation.codec': ['h264', validate_string],
'animation.bitrate': [-1, validate_int],
# Controls image format when frames are written to disk
'animation.frame_format': ['png', validate_movie_frame_fmt],
# Additional arguments for HTML writer
'animation.html_args': [[], validate_stringlist],
# Path to ffmpeg binary. If just binary name, subprocess uses $PATH.
'animation.ffmpeg_path': ['ffmpeg', validate_animation_writer_path],
# Additional arguments for ffmpeg movie writer (using pipes)
'animation.ffmpeg_args': [[], validate_stringlist],
# Path to AVConv binary. If just binary name, subprocess uses $PATH.
'animation.avconv_path': ['avconv', validate_animation_writer_path],
# Additional arguments for avconv movie writer (using pipes)
'animation.avconv_args': [[], validate_stringlist],
# Path to convert binary. If just binary name, subprocess uses $PATH.
'animation.convert_path': ['convert', validate_animation_writer_path],
# Additional arguments for convert movie writer (using pipes)
'animation.convert_args': [[], validate_stringlist],
# Classic (pre 2.0) compatibility mode
# This is used for things that are hard to make backward compatible
# with a sane rcParam alone. This does *not* turn on classic mode
# altogether. For that use `matplotlib.style.use('classic')`.
'_internal.classic_mode': [False, validate_bool]
}
|
26e3f130e3598b965c58ea0765d85fd499535eed75c30a279150026c4db9c6d5
|
"""
This module provides the routine to adjust subplot layouts so that there are
no overlapping axes or axes decorations. All axes decorations are dealt with
(labels, ticks, titles, ticklabels) and some dependent artists are also dealt
with (colorbar, suptitle, legend).
Layout is done via :meth:`~matplotlib.gridspec`, with one constraint per
gridspec, so it is possible to have overlapping axes if the gridspecs
overlap (i.e. using :meth:`~matplotlib.gridspec.GridSpecFromSubplotSpec`).
Axes placed using ``figure.subplots()`` or ``figure.add_subplots()`` will
participate in the layout. Axes manually placed via ``figure.add_axes()``
will not.
See Tutorial: :doc:`/tutorials/intermediate/constrainedlayout_guide`
"""
# Development Notes:
# What gets a layoutbox:
# - figure
# - gridspec
# - subplotspec
# EITHER:
# - axes + pos for the axes (i.e. the total area taken by axis and
# the actual "position" argument that needs to be sent to
# ax.set_position.)
# - The axes layout box will also encompass the legend, and that is
# how legends get included (axes legends, not figure legends)
# - colorbars are siblings of the axes if they are single-axes
# colorbars
# OR:
# - a gridspec can be inside a subplotspec.
# - subplotspec
# EITHER:
# - axes...
# OR:
# - gridspec... with arbitrary nesting...
# - colorbars are siblings of the subplotspecs if they are multi-axes
# colorbars.
# - suptitle:
# - right now suptitles are just stacked atop everything else in figure.
# Could imagine suptitles being gridspec suptitles, but not implemented
#
# Todo: AnchoredOffsetbox connected to gridspecs or axes. This would
# be more general way to add extra-axes annotations.
import logging
import numpy as np
import matplotlib.cbook as cbook
import matplotlib._layoutbox as layoutbox
_log = logging.getLogger(__name__)
def _in_same_column(colnum0min, colnum0max, colnumCmin, colnumCmax):
return (colnumCmin <= colnum0min <= colnumCmax
or colnumCmin <= colnum0max <= colnumCmax)
def _in_same_row(rownum0min, rownum0max, rownumCmin, rownumCmax):
return (rownumCmin <= rownum0min <= rownumCmax
or rownumCmin <= rownum0max <= rownumCmax)
def _axes_all_finite_sized(fig):
"""
helper function to make sure all axes in the
figure have a finite width and height. If not, return False
"""
for ax in fig.axes:
if ax._layoutbox is not None:
newpos = ax._poslayoutbox.get_rect()
if newpos[2] <= 0 or newpos[3] <= 0:
return False
return True
######################################################
def do_constrained_layout(fig, renderer, h_pad, w_pad,
hspace=None, wspace=None):
"""
Do the constrained_layout. Called at draw time in
``figure.constrained_layout()``
Parameters
----------
fig : Figure
is the ``figure`` instance to do the layout in.
renderer : Renderer
the renderer to use.
h_pad, w_pad : float
are in figure-normalized units, and are a padding around the axes
elements.
hspace, wspace : float
are in fractions of the subplot sizes.
"""
''' Steps:
1. get a list of unique gridspecs in this figure. Each gridspec will be
constrained separately.
2. Check for gaps in the gridspecs. i.e. if not every axes slot in the
gridspec has been filled. If empty, add a ghost axis that is made so
that it cannot be seen (though visible=True). This is needed to make
a blank spot in the layout.
3. Compare the tight_bbox of each axes to its `position`, and assume that
the difference is the space needed by the elements around the edge of
the axes (decorations) like the title, ticklabels, x-labels, etc. This
can include legends who overspill the axes boundaries.
4. Constrain gridspec elements to line up:
a) if colnum0 != colnumC, the two subplotspecs are stacked next to
each other, with the appropriate order.
b) if colnum0 == colnumC, line up the left or right side of the
_poslayoutbox (depending if it is the min or max num that is equal).
c) do the same for rows...
5. The above doesn't constrain relative sizes of the _poslayoutboxes at
all, and indeed zero-size is a solution that the solver often finds more
convenient than expanding the sizes. Right now the solution is to compare
subplotspec sizes (i.e. drowsC and drows0) and constrain the larger
_poslayoutbox to be larger than the ratio of the sizes. i.e. if drows0 >
drowsC, then ax._poslayoutbox > axc._poslayoutbox * drowsC / drows0. This
works fine *if* the decorations are similar between the axes. If the
larger subplotspec has much larger axes decorations, then the constraint
above is incorrect.
We need the greater than in the above, in general, rather than an equals
sign. Consider the case of the left column having 2 rows, and the right
column having 1 row. We want the top and bottom of the _poslayoutboxes to
line up. So that means if there are decorations on the left column axes
they will be smaller than half as large as the right hand axis.
This can break down if the decoration size for the right hand axis (the
margins) is very large. There must be a math way to check for this case.
'''
invTransFig = fig.transFigure.inverted().transform_bbox
# list of unique gridspecs that contain child axes:
gss = set()
for ax in fig.axes:
if hasattr(ax, 'get_subplotspec'):
gs = ax.get_subplotspec().get_gridspec()
if gs._layoutbox is not None:
gss.add(gs)
if len(gss) == 0:
cbook._warn_external('There are no gridspecs with layoutboxes. '
'Possibly did not call parent GridSpec with the'
' figure= keyword')
if fig._layoutbox.constrained_layout_called < 1:
for gs in gss:
# fill in any empty gridspec slots w/ ghost axes...
_make_ghost_gridspec_slots(fig, gs)
for nnn in range(2):
# do the algorithm twice. This has to be done because decorators
# change size after the first re-position (i.e. x/yticklabels get
# larger/smaller). This second reposition tends to be much milder,
# so doing twice makes things work OK.
for ax in fig.axes:
_log.debug(ax._layoutbox)
if ax._layoutbox is not None:
# make margins for each layout box based on the size of
# the decorators.
_make_layout_margins(ax, renderer, h_pad, w_pad)
# do layout for suptitle.
if fig._suptitle is not None and fig._suptitle._layoutbox is not None:
sup = fig._suptitle
bbox = invTransFig(sup.get_window_extent(renderer=renderer))
height = bbox.y1 - bbox.y0
if np.isfinite(height):
sup._layoutbox.edit_height(height+h_pad)
# OK, the above lines up ax._poslayoutbox with ax._layoutbox
# now we need to
# 1) arrange the subplotspecs. We do it at this level because
# the subplotspecs are meant to contain other dependent axes
# like colorbars or legends.
# 2) line up the right and left side of the ax._poslayoutbox
# that have the same subplotspec maxes.
if fig._layoutbox.constrained_layout_called < 1:
# arrange the subplotspecs... This is all done relative to each
# other. Some subplotspecs contain axes, and others contain
# gridspecs the ones that contain gridspecs are a set proportion
# of their parent gridspec. The ones that contain axes are
# not so constrained.
figlb = fig._layoutbox
for child in figlb.children:
if child._is_gridspec_layoutbox():
# This routine makes all the subplot spec containers
# have the correct arrangement. It just stacks the
# subplot layoutboxes in the correct order...
_arrange_subplotspecs(child, hspace=hspace, wspace=wspace)
for gs in gss:
_align_spines(fig, gs)
fig._layoutbox.constrained_layout_called += 1
fig._layoutbox.update_variables()
# check if any axes collapsed to zero. If not, don't change positions:
if _axes_all_finite_sized(fig):
# Now set the position of the axes...
for ax in fig.axes:
if ax._layoutbox is not None:
newpos = ax._poslayoutbox.get_rect()
# Now set the new position.
# ax.set_position will zero out the layout for
# this axis, allowing users to hard-code the position,
# so this does the same w/o zeroing layout.
ax._set_position(newpos, which='original')
else:
cbook._warn_external('constrained_layout not applied. At least '
'one axes collapsed to zero width or height.')
def _make_ghost_gridspec_slots(fig, gs):
"""
Check for unoccupied gridspec slots and make ghost axes for these
slots... Do for each gs separately. This is a pretty big kludge
but shouldn't have too much ill effect. The worst is that
someone querying the figure will wonder why there are more
axes than they thought.
"""
nrows, ncols = gs.get_geometry()
hassubplotspec = np.zeros(nrows * ncols, dtype=bool)
axs = []
for ax in fig.axes:
if (hasattr(ax, 'get_subplotspec')
and ax._layoutbox is not None
and ax.get_subplotspec().get_gridspec() == gs):
axs += [ax]
for ax in axs:
ss0 = ax.get_subplotspec()
hassubplotspec[ss0.num1:(ss0.num2 + 1)] = True
for nn, hss in enumerate(hassubplotspec):
if not hss:
# this gridspec slot doesn't have an axis so we
# make a "ghost".
ax = fig.add_subplot(gs[nn])
ax.set_frame_on(False)
ax.set_xticks([])
ax.set_yticks([])
ax.set_facecolor((1, 0, 0, 0))
def _make_layout_margins(ax, renderer, h_pad, w_pad):
"""
For each axes, make a margin between the *pos* layoutbox and the
*axes* layoutbox be a minimum size that can accommodate the
decorations on the axis.
"""
fig = ax.figure
invTransFig = fig.transFigure.inverted().transform_bbox
pos = ax.get_position(original=True)
tightbbox = ax.get_tightbbox(renderer=renderer)
bbox = invTransFig(tightbbox)
# this can go wrong:
if not (np.isfinite(bbox.width) and np.isfinite(bbox.height)):
# just abort, this is likely a bad set of co-ordinates that
# is transitory...
return
# use stored h_pad if it exists
h_padt = ax._poslayoutbox.h_pad
if h_padt is None:
h_padt = h_pad
w_padt = ax._poslayoutbox.w_pad
if w_padt is None:
w_padt = w_pad
ax._poslayoutbox.edit_left_margin_min(-bbox.x0 +
pos.x0 + w_padt)
ax._poslayoutbox.edit_right_margin_min(bbox.x1 -
pos.x1 + w_padt)
ax._poslayoutbox.edit_bottom_margin_min(
-bbox.y0 + pos.y0 + h_padt)
ax._poslayoutbox.edit_top_margin_min(bbox.y1-pos.y1+h_padt)
_log.debug('left %f', (-bbox.x0 + pos.x0 + w_pad))
_log.debug('right %f', (bbox.x1 - pos.x1 + w_pad))
_log.debug('bottom %f', (-bbox.y0 + pos.y0 + h_padt))
_log.debug('bbox.y0 %f', bbox.y0)
_log.debug('pos.y0 %f', pos.y0)
# Sometimes its possible for the solver to collapse
# rather than expand axes, so they all have zero height
# or width. This stops that... It *should* have been
# taken into account w/ pref_width...
if fig._layoutbox.constrained_layout_called < 1:
ax._poslayoutbox.constrain_height_min(20, strength='weak')
ax._poslayoutbox.constrain_width_min(20, strength='weak')
ax._layoutbox.constrain_height_min(20, strength='weak')
ax._layoutbox.constrain_width_min(20, strength='weak')
ax._poslayoutbox.constrain_top_margin(0, strength='weak')
ax._poslayoutbox.constrain_bottom_margin(0,
strength='weak')
ax._poslayoutbox.constrain_right_margin(0, strength='weak')
ax._poslayoutbox.constrain_left_margin(0, strength='weak')
def _align_spines(fig, gs):
"""
- Align right/left and bottom/top spines of appropriate subplots.
- Compare size of subplotspec including height and width ratios
and make sure that the axes spines are at least as large
as they should be.
"""
# for each gridspec...
nrows, ncols = gs.get_geometry()
width_ratios = gs.get_width_ratios()
height_ratios = gs.get_height_ratios()
if width_ratios is None:
width_ratios = np.ones(ncols)
if height_ratios is None:
height_ratios = np.ones(nrows)
# get axes in this gridspec....
axs = []
for ax in fig.axes:
if (hasattr(ax, 'get_subplotspec')
and ax._layoutbox is not None):
if ax.get_subplotspec().get_gridspec() == gs:
axs += [ax]
rownummin = np.zeros(len(axs), dtype=np.int8)
rownummax = np.zeros(len(axs), dtype=np.int8)
colnummin = np.zeros(len(axs), dtype=np.int8)
colnummax = np.zeros(len(axs), dtype=np.int8)
width = np.zeros(len(axs))
height = np.zeros(len(axs))
for n, ax in enumerate(axs):
ss0 = ax.get_subplotspec()
rownummin[n], colnummin[n] = divmod(ss0.num1, ncols)
rownummax[n], colnummax[n] = divmod(ss0.num2, ncols)
width[n] = np.sum(
width_ratios[colnummin[n]:(colnummax[n] + 1)])
height[n] = np.sum(
height_ratios[rownummin[n]:(rownummax[n] + 1)])
for nn, ax in enumerate(axs[:-1]):
# now compare ax to all the axs:
#
# If the subplotspecs have the same colnumXmax, then line
# up their right sides. If they have the same min, then
# line up their left sides (and vertical equivalents).
rownum0min, colnum0min = rownummin[nn], colnummin[nn]
rownum0max, colnum0max = rownummax[nn], colnummax[nn]
width0, height0 = width[nn], height[nn]
alignleft = False
alignright = False
alignbot = False
aligntop = False
alignheight = False
alignwidth = False
for mm in range(nn+1, len(axs)):
axc = axs[mm]
rownumCmin, colnumCmin = rownummin[mm], colnummin[mm]
rownumCmax, colnumCmax = rownummax[mm], colnummax[mm]
widthC, heightC = width[mm], height[mm]
# Horizontally align axes spines if they have the
# same min or max:
if not alignleft and colnum0min == colnumCmin:
# we want the _poslayoutboxes to line up on left
# side of the axes spines...
layoutbox.align([ax._poslayoutbox,
axc._poslayoutbox],
'left')
alignleft = True
if not alignright and colnum0max == colnumCmax:
# line up right sides of _poslayoutbox
layoutbox.align([ax._poslayoutbox,
axc._poslayoutbox],
'right')
alignright = True
# Vertically align axes spines if they have the
# same min or max:
if not aligntop and rownum0min == rownumCmin:
# line up top of _poslayoutbox
_log.debug('rownum0min == rownumCmin')
layoutbox.align([ax._poslayoutbox, axc._poslayoutbox],
'top')
aligntop = True
if not alignbot and rownum0max == rownumCmax:
# line up bottom of _poslayoutbox
_log.debug('rownum0max == rownumCmax')
layoutbox.align([ax._poslayoutbox, axc._poslayoutbox],
'bottom')
alignbot = True
###########
# Now we make the widths and heights of position boxes
# similar. (i.e the spine locations)
# This allows vertically stacked subplots to have
# different sizes if they occupy different amounts
# of the gridspec: i.e.
# gs = gridspec.GridSpec(3,1)
# ax1 = gs[0,:]
# ax2 = gs[1:,:]
# then drows0 = 1, and drowsC = 2, and ax2
# should be at least twice as large as ax1.
# But it can be more than twice as large because
# it needs less room for the labeling.
#
# For height, this only needs to be done if the
# subplots share a column. For width if they
# share a row.
drowsC = (rownumCmax - rownumCmin + 1)
drows0 = (rownum0max - rownum0min + 1)
dcolsC = (colnumCmax - colnumCmin + 1)
dcols0 = (colnum0max - colnum0min + 1)
if not alignheight and drows0 == drowsC:
ax._poslayoutbox.constrain_height(
axc._poslayoutbox.height * height0 / heightC)
alignheight = True
elif _in_same_column(colnum0min, colnum0max,
colnumCmin, colnumCmax):
if height0 > heightC:
ax._poslayoutbox.constrain_height_min(
axc._poslayoutbox.height * height0 / heightC)
# these constraints stop the smaller axes from
# being allowed to go to zero height...
axc._poslayoutbox.constrain_height_min(
ax._poslayoutbox.height * heightC /
(height0*1.8))
elif height0 < heightC:
axc._poslayoutbox.constrain_height_min(
ax._poslayoutbox.height * heightC / height0)
ax._poslayoutbox.constrain_height_min(
ax._poslayoutbox.height * height0 /
(heightC*1.8))
# widths...
if not alignwidth and dcols0 == dcolsC:
ax._poslayoutbox.constrain_width(
axc._poslayoutbox.width * width0 / widthC)
alignwidth = True
elif _in_same_row(rownum0min, rownum0max,
rownumCmin, rownumCmax):
if width0 > widthC:
ax._poslayoutbox.constrain_width_min(
axc._poslayoutbox.width * width0 / widthC)
axc._poslayoutbox.constrain_width_min(
ax._poslayoutbox.width * widthC /
(width0*1.8))
elif width0 < widthC:
axc._poslayoutbox.constrain_width_min(
ax._poslayoutbox.width * widthC / width0)
ax._poslayoutbox.constrain_width_min(
axc._poslayoutbox.width * width0 /
(widthC*1.8))
def _arrange_subplotspecs(gs, hspace=0, wspace=0):
"""
arrange the subplotspec children of this gridspec, and then recursively
do the same of any gridspec children of those gridspecs...
"""
sschildren = []
for child in gs.children:
if child._is_subplotspec_layoutbox():
for child2 in child.children:
# check for gridspec children...
if child2._is_gridspec_layoutbox():
_arrange_subplotspecs(child2, hspace=hspace, wspace=wspace)
sschildren += [child]
# now arrange the subplots...
for child0 in sschildren:
ss0 = child0.artist
nrows, ncols = ss0.get_gridspec().get_geometry()
rowNum0min, colNum0min = divmod(ss0.num1, ncols)
rowNum0max, colNum0max = divmod(ss0.num2, ncols)
sschildren = sschildren[1:]
for childc in sschildren:
ssc = childc.artist
rowNumCmin, colNumCmin = divmod(ssc.num1, ncols)
rowNumCmax, colNumCmax = divmod(ssc.num2, ncols)
# OK, this tells us the relative layout of ax
# with axc
thepad = wspace / ncols
if colNum0max < colNumCmin:
layoutbox.hstack([ss0._layoutbox, ssc._layoutbox],
padding=thepad)
if colNumCmax < colNum0min:
layoutbox.hstack([ssc._layoutbox, ss0._layoutbox],
padding=thepad)
####
# vertical alignment
thepad = hspace / nrows
if rowNum0max < rowNumCmin:
layoutbox.vstack([ss0._layoutbox,
ssc._layoutbox],
padding=thepad)
if rowNumCmax < rowNum0min:
layoutbox.vstack([ssc._layoutbox,
ss0._layoutbox],
padding=thepad)
def layoutcolorbarsingle(ax, cax, shrink, aspect, location, pad=0.05):
"""
Do the layout for a colorbar, to not overly pollute colorbar.py
`pad` is in fraction of the original axis size.
"""
axlb = ax._layoutbox
axpos = ax._poslayoutbox
axsslb = ax.get_subplotspec()._layoutbox
lb = layoutbox.LayoutBox(
parent=axsslb,
name=axsslb.name + '.cbar',
artist=cax)
if location in ('left', 'right'):
lbpos = layoutbox.LayoutBox(
parent=lb,
name=lb.name + '.pos',
tightwidth=False,
pos=True,
subplot=False,
artist=cax)
if location == 'right':
# arrange to right of parent axis
layoutbox.hstack([axlb, lb], padding=pad * axlb.width,
strength='strong')
else:
layoutbox.hstack([lb, axlb], padding=pad * axlb.width)
# constrain the height and center...
layoutbox.match_heights([axpos, lbpos], [1, shrink])
layoutbox.align([axpos, lbpos], 'v_center')
# set the width of the pos box
lbpos.constrain_width(shrink * axpos.height * (1/aspect),
strength='strong')
elif location in ('bottom', 'top'):
lbpos = layoutbox.LayoutBox(
parent=lb,
name=lb.name + '.pos',
tightheight=True,
pos=True,
subplot=False,
artist=cax)
if location == 'bottom':
layoutbox.vstack([axlb, lb], padding=pad * axlb.height)
else:
layoutbox.vstack([lb, axlb], padding=pad * axlb.height)
# constrain the height and center...
layoutbox.match_widths([axpos, lbpos],
[1, shrink], strength='strong')
layoutbox.align([axpos, lbpos], 'h_center')
# set the height of the pos box
lbpos.constrain_height(axpos.width * aspect * shrink,
strength='medium')
return lb, lbpos
def _getmaxminrowcolumn(axs):
# helper to get the min/max rows and columns of a list of axes.
maxrow = -100000
minrow = 1000000
maxax = None
minax = None
maxcol = -100000
mincol = 1000000
maxax_col = None
minax_col = None
for ax in axs:
subspec = ax.get_subplotspec()
nrows, ncols, row_start, row_stop, col_start, col_stop = \
subspec.get_rows_columns()
if row_stop > maxrow:
maxrow = row_stop
maxax = ax
if row_start < minrow:
minrow = row_start
minax = ax
if col_stop > maxcol:
maxcol = col_stop
maxax_col = ax
if col_start < mincol:
mincol = col_start
minax_col = ax
return (minrow, maxrow, minax, maxax, mincol, maxcol, minax_col, maxax_col)
def layoutcolorbargridspec(parents, cax, shrink, aspect, location, pad=0.05):
"""
Do the layout for a colorbar, to not overly pollute colorbar.py
`pad` is in fraction of the original axis size.
"""
gs = parents[0].get_subplotspec().get_gridspec()
# parent layout box....
gslb = gs._layoutbox
lb = layoutbox.LayoutBox(parent=gslb.parent,
name=gslb.parent.name + '.cbar',
artist=cax)
# figure out the row and column extent of the parents.
(minrow, maxrow, minax_row, maxax_row,
mincol, maxcol, minax_col, maxax_col) = _getmaxminrowcolumn(parents)
if location in ('left', 'right'):
lbpos = layoutbox.LayoutBox(
parent=lb,
name=lb.name + '.pos',
tightwidth=False,
pos=True,
subplot=False,
artist=cax)
for ax in parents:
if location == 'right':
order = [ax._layoutbox, lb]
else:
order = [lb, ax._layoutbox]
layoutbox.hstack(order, padding=pad * gslb.width,
strength='strong')
# constrain the height and center...
# This isn't quite right. We'd like the colorbar
# pos to line up w/ the axes poss, not the size of the
# gs.
# Horizontal Layout: need to check all the axes in this gridspec
for ch in gslb.children:
subspec = ch.artist
nrows, ncols, row_start, row_stop, col_start, col_stop = \
subspec.get_rows_columns()
if location == 'right':
if col_stop <= maxcol:
order = [subspec._layoutbox, lb]
# arrange to right of the parents
if col_start > maxcol:
order = [lb, subspec._layoutbox]
elif location == 'left':
if col_start >= mincol:
order = [lb, subspec._layoutbox]
if col_stop < mincol:
order = [subspec._layoutbox, lb]
layoutbox.hstack(order, padding=pad * gslb.width,
strength='strong')
# Vertical layout:
maxposlb = minax_row._poslayoutbox
minposlb = maxax_row._poslayoutbox
# now we want the height of the colorbar pos to be
# set by the top and bottom of the min/max axes...
# bottom top
# b t
# h = (top-bottom)*shrink
# b = bottom + (top-bottom - h) / 2.
lbpos.constrain_height(
(maxposlb.top - minposlb.bottom) *
shrink, strength='strong')
lbpos.constrain_bottom(
(maxposlb.top - minposlb.bottom) *
(1 - shrink)/2 + minposlb.bottom,
strength='strong')
# set the width of the pos box
lbpos.constrain_width(lbpos.height * (shrink / aspect),
strength='strong')
elif location in ('bottom', 'top'):
lbpos = layoutbox.LayoutBox(
parent=lb,
name=lb.name + '.pos',
tightheight=True,
pos=True,
subplot=False,
artist=cax)
for ax in parents:
if location == 'bottom':
order = [ax._layoutbox, lb]
else:
order = [lb, ax._layoutbox]
layoutbox.vstack(order, padding=pad * gslb.width,
strength='strong')
# Vertical Layout: need to check all the axes in this gridspec
for ch in gslb.children:
subspec = ch.artist
nrows, ncols, row_start, row_stop, col_start, col_stop = \
subspec.get_rows_columns()
if location == 'bottom':
if row_stop <= minrow:
order = [subspec._layoutbox, lb]
if row_start > maxrow:
order = [lb, subspec._layoutbox]
elif location == 'top':
if row_stop < minrow:
order = [subspec._layoutbox, lb]
if row_start >= maxrow:
order = [lb, subspec._layoutbox]
layoutbox.vstack(order, padding=pad * gslb.width,
strength='strong')
# Do horizontal layout...
maxposlb = maxax_col._poslayoutbox
minposlb = minax_col._poslayoutbox
lbpos.constrain_width((maxposlb.right - minposlb.left) *
shrink)
lbpos.constrain_left(
(maxposlb.right - minposlb.left) *
(1-shrink)/2 + minposlb.left)
# set the height of the pos box
lbpos.constrain_height(lbpos.width * shrink * aspect,
strength='medium')
return lb, lbpos
|
b4125ca6233674a4814d188dfc484a7c7652cd9fc549b05d58e8b86cd39ae3dd
|
"""
Tick locating and formatting
============================
This module contains classes to support completely configurable tick
locating and formatting. Although the locators know nothing about major
or minor ticks, they are used by the Axis class to support major and
minor tick locating and formatting. Generic tick locators and
formatters are provided, as well as domain specific custom ones.
Default Formatter
-----------------
The default formatter identifies when the x-data being plotted is a
small range on top of a large offset. To reduce the chances that the
ticklabels overlap, the ticks are labeled as deltas from a fixed offset.
For example::
ax.plot(np.arange(2000, 2010), range(10))
will have tick of 0-9 with an offset of +2e3. If this is not desired
turn off the use of the offset on the default formatter::
ax.get_xaxis().get_major_formatter().set_useOffset(False)
set the rcParam ``axes.formatter.useoffset=False`` to turn it off
globally, or set a different formatter.
Tick locating
-------------
The Locator class is the base class for all tick locators. The locators
handle autoscaling of the view limits based on the data limits, and the
choosing of tick locations. A useful semi-automatic tick locator is
`MultipleLocator`. It is initialized with a base, e.g., 10, and it picks
axis limits and ticks that are multiples of that base.
The Locator subclasses defined here are
:class:`AutoLocator`
`MaxNLocator` with simple defaults. This is the default tick locator for
most plotting.
:class:`MaxNLocator`
Finds up to a max number of intervals with ticks at nice locations.
:class:`LinearLocator`
Space ticks evenly from min to max.
:class:`LogLocator`
Space ticks logarithmically from min to max.
:class:`MultipleLocator`
Ticks and range are a multiple of base; either integer or float.
:class:`FixedLocator`
Tick locations are fixed.
:class:`IndexLocator`
Locator for index plots (e.g., where ``x = range(len(y))``).
:class:`NullLocator`
No ticks.
:class:`SymmetricalLogLocator`
Locator for use with with the symlog norm; works like `LogLocator` for the
part outside of the threshold and adds 0 if inside the limits.
:class:`LogitLocator`
Locator for logit scaling.
:class:`OldAutoLocator`
Choose a `MultipleLocator` and dynamically reassign it for intelligent
ticking during navigation.
:class:`AutoMinorLocator`
Locator for minor ticks when the axis is linear and the
major ticks are uniformly spaced. Subdivides the major
tick interval into a specified number of minor intervals,
defaulting to 4 or 5 depending on the major interval.
There are a number of locators specialized for date locations - see
the `dates` module.
You can define your own locator by deriving from Locator. You must
override the ``__call__`` method, which returns a sequence of locations,
and you will probably want to override the autoscale method to set the
view limits from the data limits.
If you want to override the default locator, use one of the above or a custom
locator and pass it to the x or y axis instance. The relevant methods are::
ax.xaxis.set_major_locator(xmajor_locator)
ax.xaxis.set_minor_locator(xminor_locator)
ax.yaxis.set_major_locator(ymajor_locator)
ax.yaxis.set_minor_locator(yminor_locator)
The default minor locator is `NullLocator`, i.e., no minor ticks on by default.
Tick formatting
---------------
Tick formatting is controlled by classes derived from Formatter. The formatter
operates on a single tick value and returns a string to the axis.
:class:`NullFormatter`
No labels on the ticks.
:class:`IndexFormatter`
Set the strings from a list of labels.
:class:`FixedFormatter`
Set the strings manually for the labels.
:class:`FuncFormatter`
User defined function sets the labels.
:class:`StrMethodFormatter`
Use string `format` method.
:class:`FormatStrFormatter`
Use an old-style sprintf format string.
:class:`ScalarFormatter`
Default formatter for scalars: autopick the format string.
:class:`LogFormatter`
Formatter for log axes.
:class:`LogFormatterExponent`
Format values for log axis using ``exponent = log_base(value)``.
:class:`LogFormatterMathtext`
Format values for log axis using ``exponent = log_base(value)``
using Math text.
:class:`LogFormatterSciNotation`
Format values for log axis using scientific notation.
:class:`LogitFormatter`
Probability formatter.
:class:`EngFormatter`
Format labels in engineering notation
:class:`PercentFormatter`
Format labels as a percentage
You can derive your own formatter from the Formatter base class by
simply overriding the ``__call__`` method. The formatter class has
access to the axis view and data limits.
To control the major and minor tick label formats, use one of the
following methods::
ax.xaxis.set_major_formatter(xmajor_formatter)
ax.xaxis.set_minor_formatter(xminor_formatter)
ax.yaxis.set_major_formatter(ymajor_formatter)
ax.yaxis.set_minor_formatter(yminor_formatter)
See :doc:`/gallery/ticks_and_spines/major_minor_demo` for an
example of setting major and minor ticks. See the :mod:`matplotlib.dates`
module for more information and examples of using date locators and formatters.
"""
import itertools
import logging
import locale
import math
import numpy as np
from matplotlib import rcParams
from matplotlib import cbook
from matplotlib import transforms as mtransforms
_log = logging.getLogger(__name__)
__all__ = ('TickHelper', 'Formatter', 'FixedFormatter',
'NullFormatter', 'FuncFormatter', 'FormatStrFormatter',
'StrMethodFormatter', 'ScalarFormatter', 'LogFormatter',
'LogFormatterExponent', 'LogFormatterMathtext',
'IndexFormatter', 'LogFormatterSciNotation',
'LogitFormatter', 'EngFormatter', 'PercentFormatter',
'Locator', 'IndexLocator', 'FixedLocator', 'NullLocator',
'LinearLocator', 'LogLocator', 'AutoLocator',
'MultipleLocator', 'MaxNLocator', 'AutoMinorLocator',
'SymmetricalLogLocator', 'LogitLocator')
def _mathdefault(s):
return '\\mathdefault{%s}' % s
class _DummyAxis(object):
def __init__(self, minpos=0):
self.dataLim = mtransforms.Bbox.unit()
self.viewLim = mtransforms.Bbox.unit()
self._minpos = minpos
def get_view_interval(self):
return self.viewLim.intervalx
def set_view_interval(self, vmin, vmax):
self.viewLim.intervalx = vmin, vmax
def get_minpos(self):
return self._minpos
def get_data_interval(self):
return self.dataLim.intervalx
def set_data_interval(self, vmin, vmax):
self.dataLim.intervalx = vmin, vmax
def get_tick_space(self):
# Just use the long-standing default of nbins==9
return 9
class TickHelper(object):
axis = None
def set_axis(self, axis):
self.axis = axis
def create_dummy_axis(self, **kwargs):
if self.axis is None:
self.axis = _DummyAxis(**kwargs)
def set_view_interval(self, vmin, vmax):
self.axis.set_view_interval(vmin, vmax)
def set_data_interval(self, vmin, vmax):
self.axis.set_data_interval(vmin, vmax)
def set_bounds(self, vmin, vmax):
self.set_view_interval(vmin, vmax)
self.set_data_interval(vmin, vmax)
class Formatter(TickHelper):
"""
Create a string based on a tick value and location.
"""
# some classes want to see all the locs to help format
# individual ones
locs = []
def __call__(self, x, pos=None):
"""
Return the format for tick value *x* at position pos.
``pos=None`` indicates an unspecified location.
"""
raise NotImplementedError('Derived must override')
def format_ticks(self, values):
"""Return the tick labels for all the ticks at once."""
self.set_locs(values)
return [self(value, i) for i, value in enumerate(values)]
def format_data(self, value):
"""
Returns the full string representation of the value with the
position unspecified.
"""
return self.__call__(value)
def format_data_short(self, value):
"""
Return a short string version of the tick value.
Defaults to the position-independent long value.
"""
return self.format_data(value)
def get_offset(self):
return ''
def set_locs(self, locs):
self.locs = locs
def fix_minus(self, s):
"""
Some classes may want to replace a hyphen for minus with the
proper unicode symbol (U+2212) for typographical correctness.
The default is to not replace it.
Note, if you use this method, e.g., in :meth:`format_data` or
call, you probably don't want to use it for
:meth:`format_data_short` since the toolbar uses this for
interactive coord reporting and I doubt we can expect GUIs
across platforms will handle the unicode correctly. So for
now the classes that override :meth:`fix_minus` should have an
explicit :meth:`format_data_short` method
"""
return s
def _set_locator(self, locator):
"""Subclasses may want to override this to set a locator."""
pass
class IndexFormatter(Formatter):
"""
Format the position x to the nearest i-th label where ``i = int(x + 0.5)``.
Positions where ``i < 0`` or ``i > len(list)`` have no tick labels.
Parameters
----------
labels : list
List of labels.
"""
def __init__(self, labels):
self.labels = labels
self.n = len(labels)
def __call__(self, x, pos=None):
"""
Return the format for tick value `x` at position pos.
The position is ignored and the value is rounded to the nearest
integer, which is used to look up the label.
"""
i = int(x + 0.5)
if i < 0 or i >= self.n:
return ''
else:
return self.labels[i]
class NullFormatter(Formatter):
"""
Always return the empty string.
"""
def __call__(self, x, pos=None):
"""
Returns an empty string for all inputs.
"""
return ''
class FixedFormatter(Formatter):
"""
Return fixed strings for tick labels based only on position, not value.
"""
def __init__(self, seq):
"""
Set the sequence of strings that will be used for labels.
"""
self.seq = seq
self.offset_string = ''
def __call__(self, x, pos=None):
"""
Returns the label that matches the position regardless of the
value.
For positions ``pos < len(seq)``, return `seq[i]` regardless of
`x`. Otherwise return empty string. `seq` is the sequence of
strings that this object was initialized with.
"""
if pos is None or pos >= len(self.seq):
return ''
else:
return self.seq[pos]
def get_offset(self):
return self.offset_string
def set_offset_string(self, ofs):
self.offset_string = ofs
class FuncFormatter(Formatter):
"""
Use a user-defined function for formatting.
The function should take in two inputs (a tick value ``x`` and a
position ``pos``), and return a string containing the corresponding
tick label.
"""
def __init__(self, func):
self.func = func
def __call__(self, x, pos=None):
"""
Return the value of the user defined function.
`x` and `pos` are passed through as-is.
"""
return self.func(x, pos)
class FormatStrFormatter(Formatter):
"""
Use an old-style ('%' operator) format string to format the tick.
The format string should have a single variable format (%) in it.
It will be applied to the value (not the position) of the tick.
"""
def __init__(self, fmt):
self.fmt = fmt
def __call__(self, x, pos=None):
"""
Return the formatted label string.
Only the value `x` is formatted. The position is ignored.
"""
return self.fmt % x
class StrMethodFormatter(Formatter):
"""
Use a new-style format string (as used by `str.format()`)
to format the tick.
The field used for the value must be labeled `x` and the field used
for the position must be labeled `pos`.
"""
def __init__(self, fmt):
self.fmt = fmt
def __call__(self, x, pos=None):
"""
Return the formatted label string.
`x` and `pos` are passed to `str.format` as keyword arguments
with those exact names.
"""
return self.fmt.format(x=x, pos=pos)
class OldScalarFormatter(Formatter):
"""
Tick location is a plain old number.
"""
def __call__(self, x, pos=None):
"""
Return the format for tick val `x` based on the width of the axis.
The position `pos` is ignored.
"""
xmin, xmax = self.axis.get_view_interval()
# If the number is not too big and it's an int, format it as an int.
if abs(x) < 1e4 and x == int(x):
return '%d' % x
d = abs(xmax - xmin)
fmt = ('%1.3e' if d < 1e-2 else
'%1.3f' if d <= 1 else
'%1.2f' if d <= 10 else
'%1.1f' if d <= 1e5 else
'%1.1e')
s = fmt % x
tup = s.split('e')
if len(tup) == 2:
mantissa = tup[0].rstrip('0').rstrip('.')
sign = tup[1][0].replace('+', '')
exponent = tup[1][1:].lstrip('0')
s = '%se%s%s' % (mantissa, sign, exponent)
else:
s = s.rstrip('0').rstrip('.')
return s
@cbook.deprecated("3.1")
def pprint_val(self, x, d):
"""
Formats the value `x` based on the size of the axis range `d`.
"""
# If the number is not too big and it's an int, format it as an int.
if abs(x) < 1e4 and x == int(x):
return '%d' % x
if d < 1e-2:
fmt = '%1.3e'
elif d < 1e-1:
fmt = '%1.3f'
elif d > 1e5:
fmt = '%1.1e'
elif d > 10:
fmt = '%1.1f'
elif d > 1:
fmt = '%1.2f'
else:
fmt = '%1.3f'
s = fmt % x
tup = s.split('e')
if len(tup) == 2:
mantissa = tup[0].rstrip('0').rstrip('.')
sign = tup[1][0].replace('+', '')
exponent = tup[1][1:].lstrip('0')
s = '%se%s%s' % (mantissa, sign, exponent)
else:
s = s.rstrip('0').rstrip('.')
return s
class ScalarFormatter(Formatter):
"""
Format tick values as a number.
Tick value is interpreted as a plain old number. If
``useOffset==True`` and the data range is much smaller than the data
average, then an offset will be determined such that the tick labels
are meaningful. Scientific notation is used for ``data < 10^-n`` or
``data >= 10^m``, where ``n`` and ``m`` are the power limits set
using ``set_powerlimits((n,m))``. The defaults for these are
controlled by the ``axes.formatter.limits`` rc parameter.
"""
def __init__(self, useOffset=None, useMathText=None, useLocale=None):
# useOffset allows plotting small data ranges with large offsets: for
# example: [1+1e-9,1+2e-9,1+3e-9] useMathText will render the offset
# and scientific notation in mathtext
if useOffset is None:
useOffset = rcParams['axes.formatter.useoffset']
self._offset_threshold = rcParams['axes.formatter.offset_threshold']
self.set_useOffset(useOffset)
self._usetex = rcParams['text.usetex']
if useMathText is None:
useMathText = rcParams['axes.formatter.use_mathtext']
self.set_useMathText(useMathText)
self.orderOfMagnitude = 0
self.format = ''
self._scientific = True
self._powerlimits = rcParams['axes.formatter.limits']
if useLocale is None:
useLocale = rcParams['axes.formatter.use_locale']
self._useLocale = useLocale
def get_useOffset(self):
return self._useOffset
def set_useOffset(self, val):
if val in [True, False]:
self.offset = 0
self._useOffset = val
else:
self._useOffset = False
self.offset = val
useOffset = property(fget=get_useOffset, fset=set_useOffset)
def get_useLocale(self):
return self._useLocale
def set_useLocale(self, val):
if val is None:
self._useLocale = rcParams['axes.formatter.use_locale']
else:
self._useLocale = val
useLocale = property(fget=get_useLocale, fset=set_useLocale)
def get_useMathText(self):
return self._useMathText
def set_useMathText(self, val):
if val is None:
self._useMathText = rcParams['axes.formatter.use_mathtext']
else:
self._useMathText = val
useMathText = property(fget=get_useMathText, fset=set_useMathText)
def fix_minus(self, s):
"""
Replace hyphens with a unicode minus.
"""
if rcParams['text.usetex'] or not rcParams['axes.unicode_minus']:
return s
else:
return s.replace('-', '\N{MINUS SIGN}')
def __call__(self, x, pos=None):
"""
Return the format for tick value `x` at position `pos`.
"""
if len(self.locs) == 0:
return ''
else:
xp = (x - self.offset) / (10. ** self.orderOfMagnitude)
if np.abs(xp) < 1e-8:
xp = 0
if self._useLocale:
s = locale.format_string(self.format, (xp,))
else:
s = self.format % xp
return self.fix_minus(s)
def set_scientific(self, b):
"""
Turn scientific notation on or off.
See Also
--------
ScalarFormatter.set_powerlimits
"""
self._scientific = bool(b)
def set_powerlimits(self, lims):
"""
Sets size thresholds for scientific notation.
Parameters
----------
lims : (min_exp, max_exp)
A tuple containing the powers of 10 that determine the switchover
threshold. Numbers below ``10**min_exp`` and above ``10**max_exp``
will be displayed in scientific notation.
For example, ``formatter.set_powerlimits((-3, 4))`` sets the
pre-2007 default in which scientific notation is used for
numbers less than 1e-3 or greater than 1e4.
See Also
--------
ScalarFormatter.set_scientific
"""
if len(lims) != 2:
raise ValueError("'lims' must be a sequence of length 2")
self._powerlimits = lims
def format_data_short(self, value):
"""
Return a short formatted string representation of a number.
"""
if self._useLocale:
return locale.format_string('%-12g', (value,))
else:
return '%-12g' % value
def format_data(self, value):
"""
Return a formatted string representation of a number.
"""
if self._useLocale:
s = locale.format_string('%1.10e', (value,))
else:
s = '%1.10e' % value
s = self._formatSciNotation(s)
return self.fix_minus(s)
def get_offset(self):
"""
Return scientific notation, plus offset.
"""
if len(self.locs) == 0:
return ''
s = ''
if self.orderOfMagnitude or self.offset:
offsetStr = ''
sciNotStr = ''
if self.offset:
offsetStr = self.format_data(self.offset)
if self.offset > 0:
offsetStr = '+' + offsetStr
if self.orderOfMagnitude:
if self._usetex or self._useMathText:
sciNotStr = self.format_data(10 ** self.orderOfMagnitude)
else:
sciNotStr = '1e%d' % self.orderOfMagnitude
if self._useMathText:
if sciNotStr != '':
sciNotStr = r'\times%s' % _mathdefault(sciNotStr)
s = ''.join(('$', sciNotStr, _mathdefault(offsetStr), '$'))
elif self._usetex:
if sciNotStr != '':
sciNotStr = r'\times%s' % sciNotStr
s = ''.join(('$', sciNotStr, offsetStr, '$'))
else:
s = ''.join((sciNotStr, offsetStr))
return self.fix_minus(s)
def set_locs(self, locs):
"""
Set the locations of the ticks.
"""
self.locs = locs
if len(self.locs) > 0:
if self._useOffset:
self._compute_offset()
self._set_order_of_magnitude()
self._set_format()
def _compute_offset(self):
locs = self.locs
# Restrict to visible ticks.
vmin, vmax = sorted(self.axis.get_view_interval())
locs = np.asarray(locs)
locs = locs[(vmin <= locs) & (locs <= vmax)]
if not len(locs):
self.offset = 0
return
lmin, lmax = locs.min(), locs.max()
# Only use offset if there are at least two ticks and every tick has
# the same sign.
if lmin == lmax or lmin <= 0 <= lmax:
self.offset = 0
return
# min, max comparing absolute values (we want division to round towards
# zero so we work on absolute values).
abs_min, abs_max = sorted([abs(float(lmin)), abs(float(lmax))])
sign = math.copysign(1, lmin)
# What is the smallest power of ten such that abs_min and abs_max are
# equal up to that precision?
# Note: Internally using oom instead of 10 ** oom avoids some numerical
# accuracy issues.
oom_max = np.ceil(math.log10(abs_max))
oom = 1 + next(oom for oom in itertools.count(oom_max, -1)
if abs_min // 10 ** oom != abs_max // 10 ** oom)
if (abs_max - abs_min) / 10 ** oom <= 1e-2:
# Handle the case of straddling a multiple of a large power of ten
# (relative to the span).
# What is the smallest power of ten such that abs_min and abs_max
# are no more than 1 apart at that precision?
oom = 1 + next(oom for oom in itertools.count(oom_max, -1)
if abs_max // 10 ** oom - abs_min // 10 ** oom > 1)
# Only use offset if it saves at least _offset_threshold digits.
n = self._offset_threshold - 1
self.offset = (sign * (abs_max // 10 ** oom) * 10 ** oom
if abs_max // 10 ** oom >= 10**n
else 0)
def _set_order_of_magnitude(self):
# if scientific notation is to be used, find the appropriate exponent
# if using an numerical offset, find the exponent after applying the
# offset. When lower power limit = upper <> 0, use provided exponent.
if not self._scientific:
self.orderOfMagnitude = 0
return
if self._powerlimits[0] == self._powerlimits[1] != 0:
# fixed scaling when lower power limit = upper <> 0.
self.orderOfMagnitude = self._powerlimits[0]
return
# restrict to visible ticks
vmin, vmax = sorted(self.axis.get_view_interval())
locs = np.asarray(self.locs)
locs = locs[(vmin <= locs) & (locs <= vmax)]
locs = np.abs(locs)
if not len(locs):
self.orderOfMagnitude = 0
return
if self.offset:
oom = math.floor(math.log10(vmax - vmin))
else:
if locs[0] > locs[-1]:
val = locs[0]
else:
val = locs[-1]
if val == 0:
oom = 0
else:
oom = math.floor(math.log10(val))
if oom <= self._powerlimits[0]:
self.orderOfMagnitude = oom
elif oom >= self._powerlimits[1]:
self.orderOfMagnitude = oom
else:
self.orderOfMagnitude = 0
def _set_format(self):
# set the format string to format all the ticklabels
if len(self.locs) < 2:
# Temporarily augment the locations with the axis end points.
_locs = [*self.locs, *self.axis.get_view_interval()]
else:
_locs = self.locs
locs = (np.asarray(_locs) - self.offset) / 10. ** self.orderOfMagnitude
loc_range = np.ptp(locs)
# Curvilinear coordinates can yield two identical points.
if loc_range == 0:
loc_range = np.max(np.abs(locs))
# Both points might be zero.
if loc_range == 0:
loc_range = 1
if len(self.locs) < 2:
# We needed the end points only for the loc_range calculation.
locs = locs[:-2]
loc_range_oom = int(math.floor(math.log10(loc_range)))
# first estimate:
sigfigs = max(0, 3 - loc_range_oom)
# refined estimate:
thresh = 1e-3 * 10 ** loc_range_oom
while sigfigs >= 0:
if np.abs(locs - np.round(locs, decimals=sigfigs)).max() < thresh:
sigfigs -= 1
else:
break
sigfigs += 1
self.format = '%1.' + str(sigfigs) + 'f'
if self._usetex:
self.format = '$%s$' % self.format
elif self._useMathText:
self.format = '$%s$' % _mathdefault(self.format)
@cbook.deprecated("3.1")
def pprint_val(self, x):
xp = (x - self.offset) / (10. ** self.orderOfMagnitude)
if np.abs(xp) < 1e-8:
xp = 0
if self._useLocale:
return locale.format_string(self.format, (xp,))
else:
return self.format % xp
def _formatSciNotation(self, s):
# transform 1e+004 into 1e4, for example
if self._useLocale:
decimal_point = locale.localeconv()['decimal_point']
positive_sign = locale.localeconv()['positive_sign']
else:
decimal_point = '.'
positive_sign = '+'
tup = s.split('e')
try:
significand = tup[0].rstrip('0').rstrip(decimal_point)
sign = tup[1][0].replace(positive_sign, '')
exponent = tup[1][1:].lstrip('0')
if self._useMathText or self._usetex:
if significand == '1' and exponent != '':
# reformat 1x10^y as 10^y
significand = ''
if exponent:
exponent = '10^{%s%s}' % (sign, exponent)
if significand and exponent:
return r'%s{\times}%s' % (significand, exponent)
else:
return r'%s%s' % (significand, exponent)
else:
s = ('%se%s%s' % (significand, sign, exponent)).rstrip('e')
return s
except IndexError:
return s
class LogFormatter(Formatter):
"""
Base class for formatting ticks on a log or symlog scale.
It may be instantiated directly, or subclassed.
Parameters
----------
base : float, optional, default: 10.
Base of the logarithm used in all calculations.
labelOnlyBase : bool, optional, default: False
If True, label ticks only at integer powers of base.
This is normally True for major ticks and False for
minor ticks.
minor_thresholds : (subset, all), optional, default: (1, 0.4)
If labelOnlyBase is False, these two numbers control
the labeling of ticks that are not at integer powers of
base; normally these are the minor ticks. The controlling
parameter is the log of the axis data range. In the typical
case where base is 10 it is the number of decades spanned
by the axis, so we can call it 'numdec'. If ``numdec <= all``,
all minor ticks will be labeled. If ``all < numdec <= subset``,
then only a subset of minor ticks will be labeled, so as to
avoid crowding. If ``numdec > subset`` then no minor ticks will
be labeled.
linthresh : None or float, optional, default: None
If a symmetric log scale is in use, its ``linthresh``
parameter must be supplied here.
Notes
-----
The `set_locs` method must be called to enable the subsetting
logic controlled by the ``minor_thresholds`` parameter.
In some cases such as the colorbar, there is no distinction between
major and minor ticks; the tick locations might be set manually,
or by a locator that puts ticks at integer powers of base and
at intermediate locations. For this situation, disable the
minor_thresholds logic by using ``minor_thresholds=(np.inf, np.inf)``,
so that all ticks will be labeled.
To disable labeling of minor ticks when 'labelOnlyBase' is False,
use ``minor_thresholds=(0, 0)``. This is the default for the
"classic" style.
Examples
--------
To label a subset of minor ticks when the view limits span up
to 2 decades, and all of the ticks when zoomed in to 0.5 decades
or less, use ``minor_thresholds=(2, 0.5)``.
To label all minor ticks when the view limits span up to 1.5
decades, use ``minor_thresholds=(1.5, 1.5)``.
"""
def __init__(self, base=10.0, labelOnlyBase=False,
minor_thresholds=None,
linthresh=None):
self._base = float(base)
self.labelOnlyBase = labelOnlyBase
if minor_thresholds is None:
if rcParams['_internal.classic_mode']:
minor_thresholds = (0, 0)
else:
minor_thresholds = (1, 0.4)
self.minor_thresholds = minor_thresholds
self._sublabels = None
self._linthresh = linthresh
def base(self, base):
"""
Change the *base* for labeling.
.. warning::
Should always match the base used for :class:`LogLocator`
"""
self._base = base
def label_minor(self, labelOnlyBase):
"""
Switch minor tick labeling on or off.
Parameters
----------
labelOnlyBase : bool
If True, label ticks only at integer powers of base.
"""
self.labelOnlyBase = labelOnlyBase
def set_locs(self, locs=None):
"""
Use axis view limits to control which ticks are labeled.
The *locs* parameter is ignored in the present algorithm.
"""
if np.isinf(self.minor_thresholds[0]):
self._sublabels = None
return
# Handle symlog case:
linthresh = self._linthresh
if linthresh is None:
try:
linthresh = self.axis.get_transform().linthresh
except AttributeError:
pass
vmin, vmax = self.axis.get_view_interval()
if vmin > vmax:
vmin, vmax = vmax, vmin
if linthresh is None and vmin <= 0:
# It's probably a colorbar with
# a format kwarg setting a LogFormatter in the manner
# that worked with 1.5.x, but that doesn't work now.
self._sublabels = {1} # label powers of base
return
b = self._base
if linthresh is not None: # symlog
# Only compute the number of decades in the logarithmic part of the
# axis
numdec = 0
if vmin < -linthresh:
rhs = min(vmax, -linthresh)
numdec += math.log(vmin / rhs) / math.log(b)
if vmax > linthresh:
lhs = max(vmin, linthresh)
numdec += math.log(vmax / lhs) / math.log(b)
else:
vmin = math.log(vmin) / math.log(b)
vmax = math.log(vmax) / math.log(b)
numdec = abs(vmax - vmin)
if numdec > self.minor_thresholds[0]:
# Label only bases
self._sublabels = {1}
elif numdec > self.minor_thresholds[1]:
# Add labels between bases at log-spaced coefficients;
# include base powers in case the locations include
# "major" and "minor" points, as in colorbar.
c = np.logspace(0, 1, int(b)//2 + 1, base=b)
self._sublabels = set(np.round(c))
# For base 10, this yields (1, 2, 3, 4, 6, 10).
else:
# Label all integer multiples of base**n.
self._sublabels = set(np.arange(1, b + 1))
def _num_to_string(self, x, vmin, vmax):
if x > 10000:
s = '%1.0e' % x
elif x < 1:
s = '%1.0e' % x
else:
s = self._pprint_val(x, vmax - vmin)
return s
def __call__(self, x, pos=None):
"""
Return the format for tick val *x*.
"""
if x == 0.0: # Symlog
return '0'
x = abs(x)
b = self._base
# only label the decades
fx = math.log(x) / math.log(b)
is_x_decade = is_close_to_int(fx)
exponent = np.round(fx) if is_x_decade else np.floor(fx)
coeff = np.round(x / b ** exponent)
if self.labelOnlyBase and not is_x_decade:
return ''
if self._sublabels is not None and coeff not in self._sublabels:
return ''
vmin, vmax = self.axis.get_view_interval()
vmin, vmax = mtransforms.nonsingular(vmin, vmax, expander=0.05)
s = self._num_to_string(x, vmin, vmax)
return self.fix_minus(s)
def format_data(self, value):
b = self.labelOnlyBase
self.labelOnlyBase = False
value = cbook.strip_math(self.__call__(value))
self.labelOnlyBase = b
return value
def format_data_short(self, value):
"""
Return a short formatted string representation of a number.
"""
return '%-12g' % value
@cbook.deprecated("3.1")
def pprint_val(self, *args, **kwargs):
return self._pprint_val(*args, **kwargs)
def _pprint_val(self, x, d):
# If the number is not too big and it's an int, format it as an int.
if abs(x) < 1e4 and x == int(x):
return '%d' % x
fmt = ('%1.3e' if d < 1e-2 else
'%1.3f' if d <= 1 else
'%1.2f' if d <= 10 else
'%1.1f' if d <= 1e5 else
'%1.1e')
s = fmt % x
tup = s.split('e')
if len(tup) == 2:
mantissa = tup[0].rstrip('0').rstrip('.')
exponent = int(tup[1])
if exponent:
s = '%se%d' % (mantissa, exponent)
else:
s = mantissa
else:
s = s.rstrip('0').rstrip('.')
return s
class LogFormatterExponent(LogFormatter):
"""
Format values for log axis using ``exponent = log_base(value)``.
"""
def _num_to_string(self, x, vmin, vmax):
fx = math.log(x) / math.log(self._base)
if abs(fx) > 10000:
s = '%1.0g' % fx
elif abs(fx) < 1:
s = '%1.0g' % fx
else:
fd = math.log(vmax - vmin) / math.log(self._base)
s = self._pprint_val(fx, fd)
return s
class LogFormatterMathtext(LogFormatter):
"""
Format values for log axis using ``exponent = log_base(value)``.
"""
def _non_decade_format(self, sign_string, base, fx, usetex):
'Return string for non-decade locations'
if usetex:
return (r'$%s%s^{%.2f}$') % (sign_string, base, fx)
else:
return ('$%s$' % _mathdefault('%s%s^{%.2f}' %
(sign_string, base, fx)))
def __call__(self, x, pos=None):
"""
Return the format for tick value *x*.
The position *pos* is ignored.
"""
usetex = rcParams['text.usetex']
min_exp = rcParams['axes.formatter.min_exponent']
if x == 0: # Symlog
if usetex:
return '$0$'
else:
return '$%s$' % _mathdefault('0')
sign_string = '-' if x < 0 else ''
x = abs(x)
b = self._base
# only label the decades
fx = math.log(x) / math.log(b)
is_x_decade = is_close_to_int(fx)
exponent = np.round(fx) if is_x_decade else np.floor(fx)
coeff = np.round(x / b ** exponent)
if is_x_decade:
fx = round(fx)
if self.labelOnlyBase and not is_x_decade:
return ''
if self._sublabels is not None and coeff not in self._sublabels:
return ''
# use string formatting of the base if it is not an integer
if b % 1 == 0.0:
base = '%d' % b
else:
base = '%s' % b
if np.abs(fx) < min_exp:
if usetex:
return r'${0}{1:g}$'.format(sign_string, x)
else:
return '${0}$'.format(_mathdefault(
'{0}{1:g}'.format(sign_string, x)))
elif not is_x_decade:
return self._non_decade_format(sign_string, base, fx, usetex)
elif usetex:
return r'$%s%s^{%d}$' % (sign_string, base, fx)
else:
return '$%s$' % _mathdefault('%s%s^{%d}' % (sign_string, base, fx))
class LogFormatterSciNotation(LogFormatterMathtext):
"""
Format values following scientific notation in a logarithmic axis.
"""
def _non_decade_format(self, sign_string, base, fx, usetex):
'Return string for non-decade locations'
b = float(base)
exponent = math.floor(fx)
coeff = b ** fx / b ** exponent
if is_close_to_int(coeff):
coeff = round(coeff)
if usetex:
return (r'$%s%g\times%s^{%d}$') % \
(sign_string, coeff, base, exponent)
else:
return ('$%s$' % _mathdefault(r'%s%g\times%s^{%d}' %
(sign_string, coeff, base, exponent)))
class LogitFormatter(Formatter):
"""
Probability formatter (using Math text).
"""
def __call__(self, x, pos=None):
s = ''
if 0.01 <= x <= 0.99:
s = '{:.2f}'.format(x)
elif x < 0.01:
if is_decade(x):
s = '$10^{{{:.0f}}}$'.format(np.log10(x))
else:
s = '${:.5f}$'.format(x)
else: # x > 0.99
if is_decade(1-x):
s = '$1-10^{{{:.0f}}}$'.format(np.log10(1-x))
else:
s = '$1-{:.5f}$'.format(1-x)
return s
def format_data_short(self, value):
'return a short formatted string representation of a number'
return '%-12g' % value
class EngFormatter(Formatter):
"""
Formats axis values using engineering prefixes to represent powers
of 1000, plus a specified unit, e.g., 10 MHz instead of 1e7.
"""
# The SI engineering prefixes
ENG_PREFIXES = {
-24: "y",
-21: "z",
-18: "a",
-15: "f",
-12: "p",
-9: "n",
-6: "\N{MICRO SIGN}",
-3: "m",
0: "",
3: "k",
6: "M",
9: "G",
12: "T",
15: "P",
18: "E",
21: "Z",
24: "Y"
}
def __init__(self, unit="", places=None, sep=" ", *, usetex=None,
useMathText=None):
"""
Parameters
----------
unit : str (default: "")
Unit symbol to use, suitable for use with single-letter
representations of powers of 1000. For example, 'Hz' or 'm'.
places : int (default: None)
Precision with which to display the number, specified in
digits after the decimal point (there will be between one
and three digits before the decimal point). If it is None,
the formatting falls back to the floating point format '%g',
which displays up to 6 *significant* digits, i.e. the equivalent
value for *places* varies between 0 and 5 (inclusive).
sep : str (default: " ")
Separator used between the value and the prefix/unit. For
example, one get '3.14 mV' if ``sep`` is " " (default) and
'3.14mV' if ``sep`` is "". Besides the default behavior, some
other useful options may be:
* ``sep=""`` to append directly the prefix/unit to the value;
* ``sep="\\N{THIN SPACE}"`` (``U+2009``);
* ``sep="\\N{NARROW NO-BREAK SPACE}"`` (``U+202F``);
* ``sep="\\N{NO-BREAK SPACE}"`` (``U+00A0``).
usetex : bool (default: None)
To enable/disable the use of TeX's math mode for rendering the
numbers in the formatter.
useMathText : bool (default: None)
To enable/disable the use mathtext for rendering the numbers in
the formatter.
"""
self.unit = unit
self.places = places
self.sep = sep
self.set_usetex(usetex)
self.set_useMathText(useMathText)
def get_usetex(self):
return self._usetex
def set_usetex(self, val):
if val is None:
self._usetex = rcParams['text.usetex']
else:
self._usetex = val
usetex = property(fget=get_usetex, fset=set_usetex)
def get_useMathText(self):
return self._useMathText
def set_useMathText(self, val):
if val is None:
self._useMathText = rcParams['axes.formatter.use_mathtext']
else:
self._useMathText = val
useMathText = property(fget=get_useMathText, fset=set_useMathText)
def fix_minus(self, s):
"""
Replace hyphens with a unicode minus.
"""
return ScalarFormatter.fix_minus(self, s)
def __call__(self, x, pos=None):
s = "%s%s" % (self.format_eng(x), self.unit)
# Remove the trailing separator when there is neither prefix nor unit
if self.sep and s.endswith(self.sep):
s = s[:-len(self.sep)]
return self.fix_minus(s)
def format_eng(self, num):
"""
Formats a number in engineering notation, appending a letter
representing the power of 1000 of the original number.
Some examples:
>>> format_eng(0) # for self.places = 0
'0'
>>> format_eng(1000000) # for self.places = 1
'1.0 M'
>>> format_eng("-1e-6") # for self.places = 2
'-1.00 \N{MICRO SIGN}'
"""
sign = 1
fmt = "g" if self.places is None else ".{:d}f".format(self.places)
if num < 0:
sign = -1
num = -num
if num != 0:
pow10 = int(math.floor(math.log10(num) / 3) * 3)
else:
pow10 = 0
# Force num to zero, to avoid inconsistencies like
# format_eng(-0) = "0" and format_eng(0.0) = "0"
# but format_eng(-0.0) = "-0.0"
num = 0.0
pow10 = np.clip(pow10, min(self.ENG_PREFIXES), max(self.ENG_PREFIXES))
mant = sign * num / (10.0 ** pow10)
# Taking care of the cases like 999.9..., which may be rounded to 1000
# instead of 1 k. Beware of the corner case of values that are beyond
# the range of SI prefixes (i.e. > 'Y').
if (abs(float(format(mant, fmt))) >= 1000
and pow10 < max(self.ENG_PREFIXES)):
mant /= 1000
pow10 += 3
prefix = self.ENG_PREFIXES[int(pow10)]
if self._usetex or self._useMathText:
formatted = "${mant:{fmt}}${sep}{prefix}".format(
mant=mant, sep=self.sep, prefix=prefix, fmt=fmt)
else:
formatted = "{mant:{fmt}}{sep}{prefix}".format(
mant=mant, sep=self.sep, prefix=prefix, fmt=fmt)
return formatted
class PercentFormatter(Formatter):
"""
Format numbers as a percentage.
Parameters
----------
xmax : float
Determines how the number is converted into a percentage.
*xmax* is the data value that corresponds to 100%.
Percentages are computed as ``x / xmax * 100``. So if the data is
already scaled to be percentages, *xmax* will be 100. Another common
situation is where `xmax` is 1.0.
decimals : None or int
The number of decimal places to place after the point.
If *None* (the default), the number will be computed automatically.
symbol : string or None
A string that will be appended to the label. It may be
*None* or empty to indicate that no symbol should be used. LaTeX
special characters are escaped in *symbol* whenever latex mode is
enabled, unless *is_latex* is *True*.
is_latex : bool
If *False*, reserved LaTeX characters in *symbol* will be escaped.
"""
def __init__(self, xmax=100, decimals=None, symbol='%', is_latex=False):
self.xmax = xmax + 0.0
self.decimals = decimals
self._symbol = symbol
self._is_latex = is_latex
def __call__(self, x, pos=None):
"""
Formats the tick as a percentage with the appropriate scaling.
"""
ax_min, ax_max = self.axis.get_view_interval()
display_range = abs(ax_max - ax_min)
return self.fix_minus(self.format_pct(x, display_range))
def format_pct(self, x, display_range):
"""
Formats the number as a percentage number with the correct
number of decimals and adds the percent symbol, if any.
If `self.decimals` is `None`, the number of digits after the
decimal point is set based on the `display_range` of the axis
as follows:
+---------------+----------+------------------------+
| display_range | decimals | sample |
+---------------+----------+------------------------+
| >50 | 0 | ``x = 34.5`` => 35% |
+---------------+----------+------------------------+
| >5 | 1 | ``x = 34.5`` => 34.5% |
+---------------+----------+------------------------+
| >0.5 | 2 | ``x = 34.5`` => 34.50% |
+---------------+----------+------------------------+
| ... | ... | ... |
+---------------+----------+------------------------+
This method will not be very good for tiny axis ranges or
extremely large ones. It assumes that the values on the chart
are percentages displayed on a reasonable scale.
"""
x = self.convert_to_pct(x)
if self.decimals is None:
# conversion works because display_range is a difference
scaled_range = self.convert_to_pct(display_range)
if scaled_range <= 0:
decimals = 0
else:
# Luckily Python's built-in ceil rounds to +inf, not away from
# zero. This is very important since the equation for decimals
# starts out as `scaled_range > 0.5 * 10**(2 - decimals)`
# and ends up with `decimals > 2 - log10(2 * scaled_range)`.
decimals = math.ceil(2.0 - math.log10(2.0 * scaled_range))
if decimals > 5:
decimals = 5
elif decimals < 0:
decimals = 0
else:
decimals = self.decimals
s = '{x:0.{decimals}f}'.format(x=x, decimals=int(decimals))
return s + self.symbol
def convert_to_pct(self, x):
return 100.0 * (x / self.xmax)
@property
def symbol(self):
"""
The configured percent symbol as a string.
If LaTeX is enabled via :rc:`text.usetex`, the special characters
``{'#', '$', '%', '&', '~', '_', '^', '\\', '{', '}'}`` are
automatically escaped in the string.
"""
symbol = self._symbol
if not symbol:
symbol = ''
elif rcParams['text.usetex'] and not self._is_latex:
# Source: http://www.personal.ceu.hu/tex/specchar.htm
# Backslash must be first for this to work correctly since
# it keeps getting added in
for spec in r'\#$%&~_^{}':
symbol = symbol.replace(spec, '\\' + spec)
return symbol
@symbol.setter
def symbol(self, symbol):
self._symbol = symbol
class Locator(TickHelper):
"""
Determine the tick locations;
Note that the same locator should not be used across multiple
`~matplotlib.axis.Axis` because the locator stores references to the Axis
data and view limits.
"""
# Some automatic tick locators can generate so many ticks they
# kill the machine when you try and render them.
# This parameter is set to cause locators to raise an error if too
# many ticks are generated.
MAXTICKS = 1000
def tick_values(self, vmin, vmax):
"""
Return the values of the located ticks given **vmin** and **vmax**.
.. note::
To get tick locations with the vmin and vmax values defined
automatically for the associated :attr:`axis` simply call
the Locator instance::
>>> print(type(loc))
<type 'Locator'>
>>> print(loc())
[1, 2, 3, 4]
"""
raise NotImplementedError('Derived must override')
def set_params(self, **kwargs):
"""
Do nothing, and raise a warning. Any locator class not supporting the
set_params() function will call this.
"""
cbook._warn_external(
"'set_params()' not defined for locator of type " +
str(type(self)))
def __call__(self):
"""Return the locations of the ticks"""
# note: some locators return data limits, other return view limits,
# hence there is no *one* interface to call self.tick_values.
raise NotImplementedError('Derived must override')
def raise_if_exceeds(self, locs):
"""raise a RuntimeError if Locator attempts to create more than
MAXTICKS locs"""
if len(locs) >= self.MAXTICKS:
raise RuntimeError("Locator attempting to generate {} ticks from "
"{} to {}: exceeds Locator.MAXTICKS".format(
len(locs), locs[0], locs[-1]))
return locs
def nonsingular(self, v0, v1):
"""Modify the endpoints of a range as needed to avoid singularities."""
return mtransforms.nonsingular(v0, v1, increasing=False, expander=.05)
def view_limits(self, vmin, vmax):
"""
Select a scale for the range from vmin to vmax.
Subclasses should override this method to change locator behaviour.
"""
return mtransforms.nonsingular(vmin, vmax)
def autoscale(self):
"""autoscale the view limits"""
return self.view_limits(*self.axis.get_view_interval())
def pan(self, numsteps):
"""Pan numticks (can be positive or negative)"""
ticks = self()
numticks = len(ticks)
vmin, vmax = self.axis.get_view_interval()
vmin, vmax = mtransforms.nonsingular(vmin, vmax, expander=0.05)
if numticks > 2:
step = numsteps * abs(ticks[0] - ticks[1])
else:
d = abs(vmax - vmin)
step = numsteps * d / 6.
vmin += step
vmax += step
self.axis.set_view_interval(vmin, vmax, ignore=True)
def zoom(self, direction):
"Zoom in/out on axis; if direction is >0 zoom in, else zoom out"
vmin, vmax = self.axis.get_view_interval()
vmin, vmax = mtransforms.nonsingular(vmin, vmax, expander=0.05)
interval = abs(vmax - vmin)
step = 0.1 * interval * direction
self.axis.set_view_interval(vmin + step, vmax - step, ignore=True)
def refresh(self):
"""refresh internal information based on current lim"""
pass
class IndexLocator(Locator):
"""
Place a tick on every multiple of some base number of points
plotted, e.g., on every 5th point. It is assumed that you are doing
index plotting; i.e., the axis is 0, len(data). This is mainly
useful for x ticks.
"""
def __init__(self, base, offset):
'place ticks on the i-th data points where (i-offset)%base==0'
self._base = base
self.offset = offset
def set_params(self, base=None, offset=None):
"""Set parameters within this locator"""
if base is not None:
self._base = base
if offset is not None:
self.offset = offset
def __call__(self):
"""Return the locations of the ticks"""
dmin, dmax = self.axis.get_data_interval()
return self.tick_values(dmin, dmax)
def tick_values(self, vmin, vmax):
return self.raise_if_exceeds(
np.arange(vmin + self.offset, vmax + 1, self._base))
class FixedLocator(Locator):
"""
Tick locations are fixed. If nbins is not None,
the array of possible positions will be subsampled to
keep the number of ticks <= nbins +1.
The subsampling will be done so as to include the smallest
absolute value; for example, if zero is included in the
array of possibilities, then it is guaranteed to be one of
the chosen ticks.
"""
def __init__(self, locs, nbins=None):
self.locs = np.asarray(locs)
self.nbins = max(nbins, 2) if nbins is not None else None
def set_params(self, nbins=None):
"""Set parameters within this locator."""
if nbins is not None:
self.nbins = nbins
def __call__(self):
return self.tick_values(None, None)
def tick_values(self, vmin, vmax):
""""
Return the locations of the ticks.
.. note::
Because the values are fixed, vmin and vmax are not used in this
method.
"""
if self.nbins is None:
return self.locs
step = max(int(np.ceil(len(self.locs) / self.nbins)), 1)
ticks = self.locs[::step]
for i in range(1, step):
ticks1 = self.locs[i::step]
if np.abs(ticks1).min() < np.abs(ticks).min():
ticks = ticks1
return self.raise_if_exceeds(ticks)
class NullLocator(Locator):
"""
No ticks
"""
def __call__(self):
return self.tick_values(None, None)
def tick_values(self, vmin, vmax):
""""
Return the locations of the ticks.
.. note::
Because the values are Null, vmin and vmax are not used in this
method.
"""
return []
class LinearLocator(Locator):
"""
Determine the tick locations
The first time this function is called it will try to set the
number of ticks to make a nice tick partitioning. Thereafter the
number of ticks will be fixed so that interactive navigation will
be nice
"""
def __init__(self, numticks=None, presets=None):
"""
Use presets to set locs based on lom. A dict mapping vmin, vmax->locs
"""
self.numticks = numticks
if presets is None:
self.presets = {}
else:
self.presets = presets
def set_params(self, numticks=None, presets=None):
"""Set parameters within this locator."""
if presets is not None:
self.presets = presets
if numticks is not None:
self.numticks = numticks
def __call__(self):
'Return the locations of the ticks'
vmin, vmax = self.axis.get_view_interval()
return self.tick_values(vmin, vmax)
def tick_values(self, vmin, vmax):
vmin, vmax = mtransforms.nonsingular(vmin, vmax, expander=0.05)
if vmax < vmin:
vmin, vmax = vmax, vmin
if (vmin, vmax) in self.presets:
return self.presets[(vmin, vmax)]
if self.numticks is None:
self._set_numticks()
if self.numticks == 0:
return []
ticklocs = np.linspace(vmin, vmax, self.numticks)
return self.raise_if_exceeds(ticklocs)
def _set_numticks(self):
self.numticks = 11 # todo; be smart here; this is just for dev
def view_limits(self, vmin, vmax):
'Try to choose the view limits intelligently'
if vmax < vmin:
vmin, vmax = vmax, vmin
if vmin == vmax:
vmin -= 1
vmax += 1
if rcParams['axes.autolimit_mode'] == 'round_numbers':
exponent, remainder = divmod(
math.log10(vmax - vmin), math.log10(max(self.numticks - 1, 1)))
exponent -= (remainder < .5)
scale = max(self.numticks - 1, 1) ** (-exponent)
vmin = math.floor(scale * vmin) / scale
vmax = math.ceil(scale * vmax) / scale
return mtransforms.nonsingular(vmin, vmax)
@cbook.deprecated("3.0")
def closeto(x, y):
return abs(x - y) < 1e-10
@cbook.deprecated("3.0")
class Base(object):
'this solution has some hacks to deal with floating point inaccuracies'
def __init__(self, base):
if base <= 0:
raise ValueError("'base' must be positive")
self._base = base
def lt(self, x):
'return the largest multiple of base < x'
d, m = divmod(x, self._base)
if closeto(m, 0) and not closeto(m / self._base, 1):
return (d - 1) * self._base
return d * self._base
def le(self, x):
'return the largest multiple of base <= x'
d, m = divmod(x, self._base)
if closeto(m / self._base, 1): # was closeto(m, self._base)
#looks like floating point error
return (d + 1) * self._base
return d * self._base
def gt(self, x):
'return the smallest multiple of base > x'
d, m = divmod(x, self._base)
if closeto(m / self._base, 1):
#looks like floating point error
return (d + 2) * self._base
return (d + 1) * self._base
def ge(self, x):
'return the smallest multiple of base >= x'
d, m = divmod(x, self._base)
if closeto(m, 0) and not closeto(m / self._base, 1):
return d * self._base
return (d + 1) * self._base
def get_base(self):
return self._base
class MultipleLocator(Locator):
"""
Set a tick on each integer multiple of a base within the view interval.
"""
def __init__(self, base=1.0):
self._edge = _Edge_integer(base, 0)
def set_params(self, base):
"""Set parameters within this locator."""
if base is not None:
self._edge = _Edge_integer(base, 0)
def __call__(self):
'Return the locations of the ticks'
vmin, vmax = self.axis.get_view_interval()
return self.tick_values(vmin, vmax)
def tick_values(self, vmin, vmax):
if vmax < vmin:
vmin, vmax = vmax, vmin
step = self._edge.step
vmin = self._edge.ge(vmin) * step
n = (vmax - vmin + 0.001 * step) // step
locs = vmin - step + np.arange(n + 3) * step
return self.raise_if_exceeds(locs)
def view_limits(self, dmin, dmax):
"""
Set the view limits to the nearest multiples of base that
contain the data.
"""
if rcParams['axes.autolimit_mode'] == 'round_numbers':
vmin = self._edge.le(dmin) * self._edge.step
vmax = self._edge.ge(dmax) * self._edge.step
if vmin == vmax:
vmin -= 1
vmax += 1
else:
vmin = dmin
vmax = dmax
return mtransforms.nonsingular(vmin, vmax)
def scale_range(vmin, vmax, n=1, threshold=100):
dv = abs(vmax - vmin) # > 0 as nonsingular is called before.
meanv = (vmax + vmin) / 2
if abs(meanv) / dv < threshold:
offset = 0
else:
offset = math.copysign(10 ** (math.log10(abs(meanv)) // 1), meanv)
scale = 10 ** (math.log10(dv / n) // 1)
return scale, offset
class _Edge_integer:
"""
Helper for MaxNLocator, MultipleLocator, etc.
Take floating point precision limitations into account when calculating
tick locations as integer multiples of a step.
"""
def __init__(self, step, offset):
"""
*step* is a positive floating-point interval between ticks.
*offset* is the offset subtracted from the data limits
prior to calculating tick locations.
"""
if step <= 0:
raise ValueError("'step' must be positive")
self.step = step
self._offset = abs(offset)
def closeto(self, ms, edge):
# Allow more slop when the offset is large compared to the step.
if self._offset > 0:
digits = np.log10(self._offset / self.step)
tol = max(1e-10, 10 ** (digits - 12))
tol = min(0.4999, tol)
else:
tol = 1e-10
return abs(ms - edge) < tol
def le(self, x):
'Return the largest n: n*step <= x.'
d, m = divmod(x, self.step)
if self.closeto(m / self.step, 1):
return (d + 1)
return d
def ge(self, x):
'Return the smallest n: n*step >= x.'
d, m = divmod(x, self.step)
if self.closeto(m / self.step, 0):
return d
return (d + 1)
class MaxNLocator(Locator):
"""
Select no more than N intervals at nice locations.
"""
_default_params = dict(nbins=10,
steps=None,
integer=False,
symmetric=False,
prune=None,
min_n_ticks=2)
def __init__(self, *args, **kwargs):
"""
Parameters
----------
nbins : int or 'auto', optional, default: 10
Maximum number of intervals; one less than max number of
ticks. If the string `'auto'`, the number of bins will be
automatically determined based on the length of the axis.
steps : array-like, optional
Sequence of nice numbers starting with 1 and ending with 10;
e.g., [1, 2, 4, 5, 10], where the values are acceptable
tick multiples. i.e. for the example, 20, 40, 60 would be
an acceptable set of ticks, as would 0.4, 0.6, 0.8, because
they are multiples of 2. However, 30, 60, 90 would not
be allowed because 3 does not appear in the list of steps.
integer : bool, optional, default: False
If True, ticks will take only integer values, provided
at least `min_n_ticks` integers are found within the
view limits.
symmetric : bool, optional, default: False
If True, autoscaling will result in a range symmetric about zero.
prune : {'lower', 'upper', 'both', None}, optional, default: None
Remove edge ticks -- useful for stacked or ganged plots where
the upper tick of one axes overlaps with the lower tick of the
axes above it, primarily when :rc:`axes.autolimit_mode` is
``'round_numbers'``. If ``prune=='lower'``, the smallest tick will
be removed. If ``prune == 'upper'``, the largest tick will be
removed. If ``prune == 'both'``, the largest and smallest ticks
will be removed. If ``prune == None``, no ticks will be removed.
min_n_ticks : int, optional, default: 2
Relax *nbins* and *integer* constraints if necessary to obtain
this minimum number of ticks.
"""
if args:
if 'nbins' in kwargs:
cbook.deprecated("3.1",
message='Calling MaxNLocator with positional '
'and keyword parameter *nbins* is '
'considered an error and will fail '
'in future versions of matplotlib.')
kwargs['nbins'] = args[0]
if len(args) > 1:
raise ValueError(
"Keywords are required for all arguments except 'nbins'")
self.set_params(**{**self._default_params, **kwargs})
@staticmethod
def _validate_steps(steps):
if not np.iterable(steps):
raise ValueError('steps argument must be an increasing sequence '
'of numbers between 1 and 10 inclusive')
steps = np.asarray(steps)
if np.any(np.diff(steps) <= 0) or steps[-1] > 10 or steps[0] < 1:
raise ValueError('steps argument must be an increasing sequence '
'of numbers between 1 and 10 inclusive')
if steps[0] != 1:
steps = np.hstack((1, steps))
if steps[-1] != 10:
steps = np.hstack((steps, 10))
return steps
@cbook.deprecated("3.1")
@property
def default_params(self):
return self._default_params
@cbook.deprecated("3.1")
@default_params.setter
def default_params(self, params):
self._default_params = params
@staticmethod
def _staircase(steps):
# Make an extended staircase within which the needed
# step will be found. This is probably much larger
# than necessary.
flights = (0.1 * steps[:-1], steps, 10 * steps[1])
return np.hstack(flights)
def set_params(self, **kwargs):
"""
Set parameters for this locator.
Parameters
----------
nbins : int or 'auto', optional
see `.MaxNLocator`
steps : array-like, optional
see `.MaxNLocator`
integer : bool, optional
see `.MaxNLocator`
symmetric : bool, optional
see `.MaxNLocator`
prune : {'lower', 'upper', 'both', None}, optional
see `.MaxNLocator`
min_n_ticks : int, optional
see `.MaxNLocator`
"""
if 'nbins' in kwargs:
self._nbins = kwargs.pop('nbins')
if self._nbins != 'auto':
self._nbins = int(self._nbins)
if 'symmetric' in kwargs:
self._symmetric = kwargs.pop('symmetric')
if 'prune' in kwargs:
prune = kwargs.pop('prune')
if prune is not None and prune not in ['upper', 'lower', 'both']:
raise ValueError(
"prune must be 'upper', 'lower', 'both', or None")
self._prune = prune
if 'min_n_ticks' in kwargs:
self._min_n_ticks = max(1, kwargs.pop('min_n_ticks'))
if 'steps' in kwargs:
steps = kwargs.pop('steps')
if steps is None:
self._steps = np.array([1, 1.5, 2, 2.5, 3, 4, 5, 6, 8, 10])
else:
self._steps = self._validate_steps(steps)
self._extended_steps = self._staircase(self._steps)
if 'integer' in kwargs:
self._integer = kwargs.pop('integer')
if kwargs:
key, _ = kwargs.popitem()
cbook.warn_deprecated("3.1",
message="MaxNLocator.set_params got an "
f"unexpected parameter: {key}")
def _raw_ticks(self, vmin, vmax):
"""
Generate a list of tick locations including the range *vmin* to
*vmax*. In some applications, one or both of the end locations
will not be needed, in which case they are trimmed off
elsewhere.
"""
if self._nbins == 'auto':
if self.axis is not None:
nbins = np.clip(self.axis.get_tick_space(),
max(1, self._min_n_ticks - 1), 9)
else:
nbins = 9
else:
nbins = self._nbins
scale, offset = scale_range(vmin, vmax, nbins)
_vmin = vmin - offset
_vmax = vmax - offset
raw_step = (_vmax - _vmin) / nbins
steps = self._extended_steps * scale
if self._integer:
# For steps > 1, keep only integer values.
igood = (steps < 1) | (np.abs(steps - np.round(steps)) < 0.001)
steps = steps[igood]
istep = np.nonzero(steps >= raw_step)[0][0]
# Classic round_numbers mode may require a larger step.
if rcParams['axes.autolimit_mode'] == 'round_numbers':
for istep in range(istep, len(steps)):
step = steps[istep]
best_vmin = (_vmin // step) * step
best_vmax = best_vmin + step * nbins
if best_vmax >= _vmax:
break
# This is an upper limit; move to smaller steps if necessary.
for istep in reversed(range(istep + 1)):
step = steps[istep]
if (self._integer and
np.floor(_vmax) - np.ceil(_vmin) >= self._min_n_ticks - 1):
step = max(1, step)
best_vmin = (_vmin // step) * step
# Find tick locations spanning the vmin-vmax range, taking into
# account degradation of precision when there is a large offset.
# The edge ticks beyond vmin and/or vmax are needed for the
# "round_numbers" autolimit mode.
edge = _Edge_integer(step, offset)
low = edge.le(_vmin - best_vmin)
high = edge.ge(_vmax - best_vmin)
ticks = np.arange(low, high + 1) * step + best_vmin
# Count only the ticks that will be displayed.
nticks = ((ticks <= _vmax) & (ticks >= _vmin)).sum()
if nticks >= self._min_n_ticks:
break
return ticks + offset
def __call__(self):
vmin, vmax = self.axis.get_view_interval()
return self.tick_values(vmin, vmax)
def tick_values(self, vmin, vmax):
if self._symmetric:
vmax = max(abs(vmin), abs(vmax))
vmin = -vmax
vmin, vmax = mtransforms.nonsingular(
vmin, vmax, expander=1e-13, tiny=1e-14)
locs = self._raw_ticks(vmin, vmax)
prune = self._prune
if prune == 'lower':
locs = locs[1:]
elif prune == 'upper':
locs = locs[:-1]
elif prune == 'both':
locs = locs[1:-1]
return self.raise_if_exceeds(locs)
def view_limits(self, dmin, dmax):
if self._symmetric:
dmax = max(abs(dmin), abs(dmax))
dmin = -dmax
dmin, dmax = mtransforms.nonsingular(
dmin, dmax, expander=1e-12, tiny=1e-13)
if rcParams['axes.autolimit_mode'] == 'round_numbers':
return self._raw_ticks(dmin, dmax)[[0, -1]]
else:
return dmin, dmax
@cbook.deprecated("3.1")
def decade_down(x, base=10):
'floor x to the nearest lower decade'
if x == 0.0:
return -base
lx = np.floor(np.log(x) / np.log(base))
return base ** lx
@cbook.deprecated("3.1")
def decade_up(x, base=10):
'ceil x to the nearest higher decade'
if x == 0.0:
return base
lx = np.ceil(np.log(x) / np.log(base))
return base ** lx
def nearest_long(x):
cbook.warn_deprecated('3.0', removal='3.1', name='`nearest_long`',
obj_type='function', alternative='`round`')
if x >= 0:
return int(x + 0.5)
return int(x - 0.5)
def is_decade(x, base=10):
if not np.isfinite(x):
return False
if x == 0.0:
return True
lx = np.log(np.abs(x)) / np.log(base)
return is_close_to_int(lx)
def _decade_less_equal(x, base):
"""
Return the largest integer power of *base* that's less or equal to *x*.
If *x* is negative, the exponent will be *greater*.
"""
return (x if x == 0 else
-_decade_greater_equal(-x, base) if x < 0 else
base ** np.floor(np.log(x) / np.log(base)))
def _decade_greater_equal(x, base):
"""
Return the smallest integer power of *base* that's greater or equal to *x*.
If *x* is negative, the exponent will be *smaller*.
"""
return (x if x == 0 else
-_decade_less_equal(-x, base) if x < 0 else
base ** np.ceil(np.log(x) / np.log(base)))
def _decade_less(x, base):
"""
Return the largest integer power of *base* that's less than *x*.
If *x* is negative, the exponent will be *greater*.
"""
if x < 0:
return -_decade_greater(-x, base)
less = _decade_less_equal(x, base)
if less == x:
less /= base
return less
def _decade_greater(x, base):
"""
Return the smallest integer power of *base* that's greater than *x*.
If *x* is negative, the exponent will be *smaller*.
"""
if x < 0:
return -_decade_less(-x, base)
greater = _decade_greater_equal(x, base)
if greater == x:
greater *= base
return greater
def is_close_to_int(x):
return abs(x - np.round(x)) < 1e-10
class LogLocator(Locator):
"""
Determine the tick locations for log axes
"""
def __init__(self, base=10.0, subs=(1.0,), numdecs=4, numticks=None):
"""
Place ticks on the locations : subs[j] * base**i
Parameters
----------
subs : None, string, or sequence of float, optional, default (1.0,)
Gives the multiples of integer powers of the base at which
to place ticks. The default places ticks only at
integer powers of the base.
The permitted string values are ``'auto'`` and ``'all'``,
both of which use an algorithm based on the axis view
limits to determine whether and how to put ticks between
integer powers of the base. With ``'auto'``, ticks are
placed only between integer powers; with ``'all'``, the
integer powers are included. A value of None is
equivalent to ``'auto'``.
"""
if numticks is None:
if rcParams['_internal.classic_mode']:
numticks = 15
else:
numticks = 'auto'
self.base(base)
self.subs(subs)
self.numdecs = numdecs
self.numticks = numticks
def set_params(self, base=None, subs=None, numdecs=None, numticks=None):
"""Set parameters within this locator."""
if base is not None:
self.base(base)
if subs is not None:
self.subs(subs)
if numdecs is not None:
self.numdecs = numdecs
if numticks is not None:
self.numticks = numticks
# FIXME: these base and subs functions are contrary to our
# usual and desired API.
def base(self, base):
"""
set the base of the log scaling (major tick every base**i, i integer)
"""
self._base = float(base)
def subs(self, subs):
"""
set the minor ticks for the log scaling every base**i*subs[j]
"""
if subs is None: # consistency with previous bad API
self._subs = 'auto'
elif isinstance(subs, str):
if subs not in ('all', 'auto'):
raise ValueError("A subs string must be 'all' or 'auto'; "
"found '%s'." % subs)
self._subs = subs
else:
self._subs = np.asarray(subs, dtype=float)
def __call__(self):
'Return the locations of the ticks'
vmin, vmax = self.axis.get_view_interval()
return self.tick_values(vmin, vmax)
def tick_values(self, vmin, vmax):
if self.numticks == 'auto':
if self.axis is not None:
numticks = np.clip(self.axis.get_tick_space(), 2, 9)
else:
numticks = 9
else:
numticks = self.numticks
b = self._base
# dummy axis has no axes attribute
if hasattr(self.axis, 'axes') and self.axis.axes.name == 'polar':
vmax = math.ceil(math.log(vmax) / math.log(b))
decades = np.arange(vmax - self.numdecs, vmax)
ticklocs = b ** decades
return ticklocs
if vmin <= 0.0:
if self.axis is not None:
vmin = self.axis.get_minpos()
if vmin <= 0.0 or not np.isfinite(vmin):
raise ValueError(
"Data has no positive values, and therefore can not be "
"log-scaled.")
_log.debug('vmin %s vmax %s', vmin, vmax)
if vmax < vmin:
vmin, vmax = vmax, vmin
log_vmin = math.log(vmin) / math.log(b)
log_vmax = math.log(vmax) / math.log(b)
numdec = math.floor(log_vmax) - math.ceil(log_vmin)
if isinstance(self._subs, str):
_first = 2.0 if self._subs == 'auto' else 1.0
if numdec > 10 or b < 3:
if self._subs == 'auto':
return np.array([]) # no minor or major ticks
else:
subs = np.array([1.0]) # major ticks
else:
subs = np.arange(_first, b)
else:
subs = self._subs
# Get decades between major ticks.
stride = (max(math.ceil(numdec / (numticks - 1)), 1)
if rcParams['_internal.classic_mode'] else
(numdec + 1) // numticks + 1)
# Does subs include anything other than 1? Essentially a hack to know
# whether we're a major or a minor locator.
have_subs = len(subs) > 1 or (len(subs) == 1 and subs[0] != 1.0)
decades = np.arange(math.floor(log_vmin) - stride,
math.ceil(log_vmax) + 2 * stride, stride)
if hasattr(self, '_transform'):
ticklocs = self._transform.inverted().transform(decades)
if have_subs:
if stride == 1:
ticklocs = np.ravel(np.outer(subs, ticklocs))
else:
# No ticklocs if we have >1 decade between major ticks.
ticklocs = np.array([])
else:
if have_subs:
if stride == 1:
ticklocs = np.concatenate(
[subs * decade_start for decade_start in b ** decades])
else:
ticklocs = np.array([])
else:
ticklocs = b ** decades
_log.debug('ticklocs %r', ticklocs)
if (len(subs) > 1
and stride == 1
and ((vmin <= ticklocs) & (ticklocs <= vmax)).sum() <= 1):
# If we're a minor locator *that expects at least two ticks per
# decade* and the major locator stride is 1 and there's no more
# than one minor tick, switch to AutoLocator.
return AutoLocator().tick_values(vmin, vmax)
else:
return self.raise_if_exceeds(ticklocs)
def view_limits(self, vmin, vmax):
'Try to choose the view limits intelligently'
b = self._base
vmin, vmax = self.nonsingular(vmin, vmax)
if self.axis.axes.name == 'polar':
vmax = math.ceil(math.log(vmax) / math.log(b))
vmin = b ** (vmax - self.numdecs)
if rcParams['axes.autolimit_mode'] == 'round_numbers':
vmin = _decade_less_equal(vmin, self._base)
vmax = _decade_greater_equal(vmax, self._base)
return vmin, vmax
def nonsingular(self, vmin, vmax):
if not np.isfinite(vmin) or not np.isfinite(vmax):
return 1, 10 # initial range, no data plotted yet
if vmin > vmax:
vmin, vmax = vmax, vmin
if vmax <= 0:
cbook._warn_external(
"Data has no positive values, and therefore cannot be "
"log-scaled.")
return 1, 10
minpos = self.axis.get_minpos()
if not np.isfinite(minpos):
minpos = 1e-300 # This should never take effect.
if vmin <= 0:
vmin = minpos
if vmin == vmax:
vmin = _decade_less(vmin, self._base)
vmax = _decade_greater(vmax, self._base)
return vmin, vmax
class SymmetricalLogLocator(Locator):
"""
Determine the tick locations for symmetric log axes
"""
def __init__(self, transform=None, subs=None, linthresh=None, base=None):
"""
place ticks on the location= base**i*subs[j]
"""
if transform is not None:
self._base = transform.base
self._linthresh = transform.linthresh
elif linthresh is not None and base is not None:
self._base = base
self._linthresh = linthresh
else:
raise ValueError("Either transform, or both linthresh "
"and base, must be provided.")
if subs is None:
self._subs = [1.0]
else:
self._subs = subs
self.numticks = 15
def set_params(self, subs=None, numticks=None):
"""Set parameters within this locator."""
if numticks is not None:
self.numticks = numticks
if subs is not None:
self._subs = subs
def __call__(self):
'Return the locations of the ticks'
# Note, these are untransformed coordinates
vmin, vmax = self.axis.get_view_interval()
return self.tick_values(vmin, vmax)
def tick_values(self, vmin, vmax):
b = self._base
t = self._linthresh
if vmax < vmin:
vmin, vmax = vmax, vmin
# The domain is divided into three sections, only some of
# which may actually be present.
#
# <======== -t ==0== t ========>
# aaaaaaaaa bbbbb ccccccccc
#
# a) and c) will have ticks at integral log positions. The
# number of ticks needs to be reduced if there are more
# than self.numticks of them.
#
# b) has a tick at 0 and only 0 (we assume t is a small
# number, and the linear segment is just an implementation
# detail and not interesting.)
#
# We could also add ticks at t, but that seems to usually be
# uninteresting.
#
# "simple" mode is when the range falls entirely within (-t,
# t) -- it should just display (vmin, 0, vmax)
has_a = has_b = has_c = False
if vmin < -t:
has_a = True
if vmax > -t:
has_b = True
if vmax > t:
has_c = True
elif vmin < 0:
if vmax > 0:
has_b = True
if vmax > t:
has_c = True
else:
return [vmin, vmax]
elif vmin < t:
if vmax > t:
has_b = True
has_c = True
else:
return [vmin, vmax]
else:
has_c = True
def get_log_range(lo, hi):
lo = np.floor(np.log(lo) / np.log(b))
hi = np.ceil(np.log(hi) / np.log(b))
return lo, hi
# First, calculate all the ranges, so we can determine striding
if has_a:
if has_b:
a_range = get_log_range(t, -vmin + 1)
else:
a_range = get_log_range(-vmax, -vmin + 1)
else:
a_range = (0, 0)
if has_c:
if has_b:
c_range = get_log_range(t, vmax + 1)
else:
c_range = get_log_range(vmin, vmax + 1)
else:
c_range = (0, 0)
total_ticks = (a_range[1] - a_range[0]) + (c_range[1] - c_range[0])
if has_b:
total_ticks += 1
stride = max(total_ticks // (self.numticks - 1), 1)
decades = []
if has_a:
decades.extend(-1 * (b ** (np.arange(a_range[0], a_range[1],
stride)[::-1])))
if has_b:
decades.append(0.0)
if has_c:
decades.extend(b ** (np.arange(c_range[0], c_range[1], stride)))
# Add the subticks if requested
if self._subs is None:
subs = np.arange(2.0, b)
else:
subs = np.asarray(self._subs)
if len(subs) > 1 or subs[0] != 1.0:
ticklocs = []
for decade in decades:
if decade == 0:
ticklocs.append(decade)
else:
ticklocs.extend(subs * decade)
else:
ticklocs = decades
return self.raise_if_exceeds(np.array(ticklocs))
def view_limits(self, vmin, vmax):
'Try to choose the view limits intelligently'
b = self._base
if vmax < vmin:
vmin, vmax = vmax, vmin
if rcParams['axes.autolimit_mode'] == 'round_numbers':
vmin = _decade_less_equal(vmin, b)
vmax = _decade_greater_equal(vmax, b)
if vmin == vmax:
vmin = _decade_less(vmin, b)
vmax = _decade_greater(vmax, b)
result = mtransforms.nonsingular(vmin, vmax)
return result
class LogitLocator(Locator):
"""
Determine the tick locations for logit axes
"""
def __init__(self, minor=False):
"""
place ticks on the logit locations
"""
self.minor = minor
def set_params(self, minor=None):
"""Set parameters within this locator."""
if minor is not None:
self.minor = minor
def __call__(self):
'Return the locations of the ticks'
vmin, vmax = self.axis.get_view_interval()
return self.tick_values(vmin, vmax)
def tick_values(self, vmin, vmax):
# dummy axis has no axes attribute
if hasattr(self.axis, 'axes') and self.axis.axes.name == 'polar':
raise NotImplementedError('Polar axis cannot be logit scaled yet')
vmin, vmax = self.nonsingular(vmin, vmax)
vmin = np.log10(vmin / (1 - vmin))
vmax = np.log10(vmax / (1 - vmax))
decade_min = np.floor(vmin)
decade_max = np.ceil(vmax)
# major ticks
if not self.minor:
ticklocs = []
if decade_min <= -1:
expo = np.arange(decade_min, min(0, decade_max + 1))
ticklocs.extend(10**expo)
if decade_min <= 0 <= decade_max:
ticklocs.append(0.5)
if decade_max >= 1:
expo = -np.arange(max(1, decade_min), decade_max + 1)
ticklocs.extend(1 - 10**expo)
# minor ticks
else:
ticklocs = []
if decade_min <= -2:
expo = np.arange(decade_min, min(-1, decade_max))
newticks = np.outer(np.arange(2, 10), 10**expo).ravel()
ticklocs.extend(newticks)
if decade_min <= 0 <= decade_max:
ticklocs.extend([0.2, 0.3, 0.4, 0.6, 0.7, 0.8])
if decade_max >= 2:
expo = -np.arange(max(2, decade_min), decade_max + 1)
newticks = 1 - np.outer(np.arange(2, 10), 10**expo).ravel()
ticklocs.extend(newticks)
return self.raise_if_exceeds(np.array(ticklocs))
def nonsingular(self, vmin, vmax):
initial_range = (1e-7, 1 - 1e-7)
if not np.isfinite(vmin) or not np.isfinite(vmax):
return initial_range # no data plotted yet
if vmin > vmax:
vmin, vmax = vmax, vmin
# what to do if a window beyond ]0, 1[ is chosen
if self.axis is not None:
minpos = self.axis.get_minpos()
if not np.isfinite(minpos):
return initial_range # again, no data plotted
else:
minpos = 1e-7 # should not occur in normal use
# NOTE: for vmax, we should query a property similar to get_minpos, but
# related to the maximal, less-than-one data point. Unfortunately,
# Bbox._minpos is defined very deep in the BBox and updated with data,
# so for now we use 1 - minpos as a substitute.
if vmin <= 0:
vmin = minpos
if vmax >= 1:
vmax = 1 - minpos
if vmin == vmax:
return 0.1 * vmin, 1 - 0.1 * vmin
return vmin, vmax
class AutoLocator(MaxNLocator):
"""
Dynamically find major tick positions. This is actually a subclass
of `~matplotlib.ticker.MaxNLocator`, with parameters *nbins = 'auto'*
and *steps = [1, 2, 2.5, 5, 10]*.
"""
def __init__(self):
"""
To know the values of the non-public parameters, please have a
look to the defaults of `~matplotlib.ticker.MaxNLocator`.
"""
if rcParams['_internal.classic_mode']:
nbins = 9
steps = [1, 2, 5, 10]
else:
nbins = 'auto'
steps = [1, 2, 2.5, 5, 10]
MaxNLocator.__init__(self, nbins=nbins, steps=steps)
class AutoMinorLocator(Locator):
"""
Dynamically find minor tick positions based on the positions of
major ticks. The scale must be linear with major ticks evenly spaced.
"""
def __init__(self, n=None):
"""
*n* is the number of subdivisions of the interval between
major ticks; e.g., n=2 will place a single minor tick midway
between major ticks.
If *n* is omitted or None, it will be set to 5 or 4.
"""
self.ndivs = n
def __call__(self):
'Return the locations of the ticks'
if self.axis.get_scale() == 'log':
cbook._warn_external('AutoMinorLocator does not work with '
'logarithmic scale')
return []
majorlocs = self.axis.get_majorticklocs()
try:
majorstep = majorlocs[1] - majorlocs[0]
except IndexError:
# Need at least two major ticks to find minor tick locations
# TODO: Figure out a way to still be able to display minor
# ticks without two major ticks visible. For now, just display
# no ticks at all.
return []
if self.ndivs is None:
majorstep_no_exponent = 10 ** (np.log10(majorstep) % 1)
if np.isclose(majorstep_no_exponent, [1.0, 2.5, 5.0, 10.0]).any():
ndivs = 5
else:
ndivs = 4
else:
ndivs = self.ndivs
minorstep = majorstep / ndivs
vmin, vmax = self.axis.get_view_interval()
if vmin > vmax:
vmin, vmax = vmax, vmin
t0 = majorlocs[0]
tmin = ((vmin - t0) // minorstep + 1) * minorstep
tmax = ((vmax - t0) // minorstep + 1) * minorstep
locs = np.arange(tmin, tmax, minorstep) + t0
return self.raise_if_exceeds(locs)
def tick_values(self, vmin, vmax):
raise NotImplementedError('Cannot get tick locations for a '
'%s type.' % type(self))
class OldAutoLocator(Locator):
"""
On autoscale this class picks the best MultipleLocator to set the
view limits and the tick locs.
"""
def __init__(self):
self._locator = LinearLocator()
def __call__(self):
'Return the locations of the ticks'
self.refresh()
return self.raise_if_exceeds(self._locator())
def tick_values(self, vmin, vmax):
raise NotImplementedError('Cannot get tick locations for a '
'%s type.' % type(self))
def refresh(self):
'refresh internal information based on current lim'
vmin, vmax = self.axis.get_view_interval()
vmin, vmax = mtransforms.nonsingular(vmin, vmax, expander=0.05)
d = abs(vmax - vmin)
self._locator = self.get_locator(d)
def view_limits(self, vmin, vmax):
'Try to choose the view limits intelligently'
d = abs(vmax - vmin)
self._locator = self.get_locator(d)
return self._locator.view_limits(vmin, vmax)
def get_locator(self, d):
'pick the best locator based on a distance'
d = abs(d)
if d <= 0:
locator = MultipleLocator(0.2)
else:
try:
ld = math.log10(d)
except OverflowError:
raise RuntimeError('AutoLocator illegal data interval range')
fld = math.floor(ld)
base = 10 ** fld
#if ld==fld: base = 10**(fld-1)
#else: base = 10**fld
if d >= 5 * base:
ticksize = base
elif d >= 2 * base:
ticksize = base / 2.0
else:
ticksize = base / 5.0
locator = MultipleLocator(ticksize)
return locator
|
e20478c4a94cbeb36a568bf2d310d84370734f2e4e9203cd40b4d5a689b688d7
|
import inspect
from matplotlib import cbook
class Substitution(object):
"""
A decorator that performs %-substitution on an object's docstring.
This decorator should be robust even if ``obj.__doc__`` is None (for
example, if -OO was passed to the interpreter).
Usage: construct a docstring.Substitution with a sequence or dictionary
suitable for performing substitution; then decorate a suitable function
with the constructed object, e.g.::
sub_author_name = Substitution(author='Jason')
@sub_author_name
def some_function(x):
"%(author)s wrote this function"
# note that some_function.__doc__ is now "Jason wrote this function"
One can also use positional arguments::
sub_first_last_names = Substitution('Edgar Allen', 'Poe')
@sub_first_last_names
def some_function(x):
"%s %s wrote the Raven"
"""
def __init__(self, *args, **kwargs):
if args and kwargs:
raise TypeError("Only positional or keyword args are allowed")
self.params = args or kwargs
def __call__(self, func):
if func.__doc__:
func.__doc__ %= self.params
return func
def update(self, *args, **kwargs):
"""
Update ``self.params`` (which must be a dict) with the supplied args.
"""
self.params.update(*args, **kwargs)
@classmethod
def from_params(cls, params):
"""
In the case where the params is a mutable sequence (list or
dictionary) and it may change before this class is called, one may
explicitly use a reference to the params rather than using *args or
**kwargs which will copy the values and not reference them.
"""
result = cls()
result.params = params
return result
@cbook.deprecated("3.1")
class Appender(object):
"""
A function decorator that will append an addendum to the docstring
of the target function.
This decorator should be robust even if func.__doc__ is None
(for example, if -OO was passed to the interpreter).
Usage: construct a docstring.Appender with a string to be joined to
the original docstring. An optional 'join' parameter may be supplied
which will be used to join the docstring and addendum. e.g.
add_copyright = Appender("Copyright (c) 2009", join='\n')
@add_copyright
def my_dog(has='fleas'):
"This docstring will have a copyright below"
pass
"""
def __init__(self, addendum, join=''):
self.addendum = addendum
self.join = join
def __call__(self, func):
docitems = [func.__doc__, self.addendum]
func.__doc__ = func.__doc__ and self.join.join(docitems)
return func
@cbook.deprecated("3.1", alternative="inspect.getdoc()")
def dedent(func):
"Dedent a docstring (if present)"
func.__doc__ = func.__doc__ and cbook.dedent(func.__doc__)
return func
def copy(source):
"Copy a docstring from another source function (if present)"
def do_copy(target):
if source.__doc__:
target.__doc__ = source.__doc__
return target
return do_copy
# Create a decorator that will house the various docstring snippets reused
# throughout Matplotlib.
interpd = Substitution()
def dedent_interpd(func):
"""Dedent *func*'s docstring, then interpolate it with ``interpd``."""
func.__doc__ = inspect.getdoc(func)
return interpd(func)
@cbook.deprecated("3.1", alternative="docstring.copy() and cbook.dedent()")
def copy_dedent(source):
"""A decorator that will copy the docstring from the source and
then dedent it"""
# note the following is ugly because "Python is not a functional
# language" - GVR. Perhaps one day, functools.compose will exist.
# or perhaps not.
# http://mail.python.org/pipermail/patches/2007-February/021687.html
return lambda target: dedent(copy(source)(target))
|
1fc6e1db0d70ee404d267cf001642f5a8f4027b79e02a82bd8ea419a77e48ca7
|
"""
The image module supports basic image loading, rescaling and display
operations.
"""
from io import BytesIO
from math import ceil
import os
import logging
from pathlib import Path
import urllib.parse
import numpy as np
from matplotlib import rcParams
import matplotlib.artist as martist
from matplotlib.backend_bases import FigureCanvasBase
import matplotlib.colors as mcolors
import matplotlib.cm as cm
import matplotlib.cbook as cbook
# For clarity, names from _image are given explicitly in this module:
import matplotlib._image as _image
# For user convenience, the names from _image are also imported into
# the image namespace:
from matplotlib._image import *
from matplotlib.transforms import (Affine2D, BboxBase, Bbox, BboxTransform,
IdentityTransform, TransformedBbox)
_log = logging.getLogger(__name__)
# map interpolation strings to module constants
_interpd_ = {
'none': _image.NEAREST, # fall back to nearest when not supported
'nearest': _image.NEAREST,
'bilinear': _image.BILINEAR,
'bicubic': _image.BICUBIC,
'spline16': _image.SPLINE16,
'spline36': _image.SPLINE36,
'hanning': _image.HANNING,
'hamming': _image.HAMMING,
'hermite': _image.HERMITE,
'kaiser': _image.KAISER,
'quadric': _image.QUADRIC,
'catrom': _image.CATROM,
'gaussian': _image.GAUSSIAN,
'bessel': _image.BESSEL,
'mitchell': _image.MITCHELL,
'sinc': _image.SINC,
'lanczos': _image.LANCZOS,
'blackman': _image.BLACKMAN,
}
interpolations_names = set(_interpd_)
def composite_images(images, renderer, magnification=1.0):
"""
Composite a number of RGBA images into one. The images are
composited in the order in which they appear in the `images` list.
Parameters
----------
images : list of Images
Each must have a `make_image` method. For each image,
`can_composite` should return `True`, though this is not
enforced by this function. Each image must have a purely
affine transformation with no shear.
renderer : RendererBase instance
magnification : float
The additional magnification to apply for the renderer in use.
Returns
-------
tuple : image, offset_x, offset_y
Returns the tuple:
- image: A numpy array of the same type as the input images.
- offset_x, offset_y: The offset of the image (left, bottom)
in the output figure.
"""
if len(images) == 0:
return np.empty((0, 0, 4), dtype=np.uint8), 0, 0
parts = []
bboxes = []
for image in images:
data, x, y, trans = image.make_image(renderer, magnification)
if data is not None:
x *= magnification
y *= magnification
parts.append((data, x, y, image.get_alpha() or 1.0))
bboxes.append(
Bbox([[x, y], [x + data.shape[1], y + data.shape[0]]]))
if len(parts) == 0:
return np.empty((0, 0, 4), dtype=np.uint8), 0, 0
bbox = Bbox.union(bboxes)
output = np.zeros(
(int(bbox.height), int(bbox.width), 4), dtype=np.uint8)
for data, x, y, alpha in parts:
trans = Affine2D().translate(x - bbox.x0, y - bbox.y0)
_image.resample(data, output, trans, _image.NEAREST,
resample=False, alpha=alpha)
return output, bbox.x0 / magnification, bbox.y0 / magnification
def _draw_list_compositing_images(
renderer, parent, artists, suppress_composite=None):
"""
Draw a sorted list of artists, compositing images into a single
image where possible.
For internal matplotlib use only: It is here to reduce duplication
between `Figure.draw` and `Axes.draw`, but otherwise should not be
generally useful.
"""
has_images = any(isinstance(x, _ImageBase) for x in artists)
# override the renderer default if suppressComposite is not None
not_composite = (suppress_composite if suppress_composite is not None
else renderer.option_image_nocomposite())
if not_composite or not has_images:
for a in artists:
a.draw(renderer)
else:
# Composite any adjacent images together
image_group = []
mag = renderer.get_image_magnification()
def flush_images():
if len(image_group) == 1:
image_group[0].draw(renderer)
elif len(image_group) > 1:
data, l, b = composite_images(image_group, renderer, mag)
if data.size != 0:
gc = renderer.new_gc()
gc.set_clip_rectangle(parent.bbox)
gc.set_clip_path(parent.get_clip_path())
renderer.draw_image(gc, np.round(l), np.round(b), data)
gc.restore()
del image_group[:]
for a in artists:
if isinstance(a, _ImageBase) and a.can_composite():
image_group.append(a)
else:
flush_images()
a.draw(renderer)
flush_images()
def _rgb_to_rgba(A):
"""
Convert an RGB image to RGBA, as required by the image resample C++
extension.
"""
rgba = np.zeros((A.shape[0], A.shape[1], 4), dtype=A.dtype)
rgba[:, :, :3] = A
if rgba.dtype == np.uint8:
rgba[:, :, 3] = 255
else:
rgba[:, :, 3] = 1.0
return rgba
class _ImageBase(martist.Artist, cm.ScalarMappable):
zorder = 0
def __init__(self, ax,
cmap=None,
norm=None,
interpolation=None,
origin=None,
filternorm=True,
filterrad=4.0,
resample=False,
**kwargs
):
"""
interpolation and cmap default to their rc settings
cmap is a colors.Colormap instance
norm is a colors.Normalize instance to map luminance to 0-1
extent is data axes (left, right, bottom, top) for making image plots
registered with data plots. Default is to label the pixel
centers with the zero-based row and column indices.
Additional kwargs are matplotlib.artist properties
"""
martist.Artist.__init__(self)
cm.ScalarMappable.__init__(self, norm, cmap)
self._mouseover = True
if origin is None:
origin = rcParams['image.origin']
self.origin = origin
self.set_filternorm(filternorm)
self.set_filterrad(filterrad)
self.set_interpolation(interpolation)
self.set_resample(resample)
self.axes = ax
self._imcache = None
self.update(kwargs)
def __getstate__(self):
state = super().__getstate__()
# We can't pickle the C Image cached object.
state['_imcache'] = None
return state
def get_size(self):
"""Get the numrows, numcols of the input image"""
if self._A is None:
raise RuntimeError('You must first set the image array')
return self._A.shape[:2]
def set_alpha(self, alpha):
"""
Set the alpha value used for blending - not supported on all backends.
Parameters
----------
alpha : float
"""
martist.Artist.set_alpha(self, alpha)
self._imcache = None
def changed(self):
"""
Call this whenever the mappable is changed so observers can
update state
"""
self._imcache = None
self._rgbacache = None
cm.ScalarMappable.changed(self)
def _make_image(self, A, in_bbox, out_bbox, clip_bbox, magnification=1.0,
unsampled=False, round_to_pixel_border=True):
"""
Normalize, rescale, and colormap the image *A* from the given *in_bbox*
(in data space), to the given *out_bbox* (in pixel space) clipped to
the given *clip_bbox* (also in pixel space), and magnified by the
*magnification* factor.
*A* may be a greyscale image (M, N) with a dtype of float32, float64,
float128, uint16 or uint8, or an (M, N, 4) RGBA image with a dtype of
float32, float64, float128, or uint8.
If *unsampled* is True, the image will not be scaled, but an
appropriate affine transformation will be returned instead.
If *round_to_pixel_border* is True, the output image size will be
rounded to the nearest pixel boundary. This makes the images align
correctly with the axes. It should not be used if exact scaling is
needed, such as for `FigureImage`.
Returns
-------
image : (M, N, 4) uint8 array
The RGBA image, resampled unless *unsampled* is True.
x, y : float
The upper left corner where the image should be drawn, in pixel
space.
trans : Affine2D
The affine transformation from image to pixel space.
"""
if A is None:
raise RuntimeError('You must first set the image '
'array or the image attribute')
if A.size == 0:
raise RuntimeError("_make_image must get a non-empty image. "
"Your Artist's draw method must filter before "
"this method is called.")
clipped_bbox = Bbox.intersection(out_bbox, clip_bbox)
if clipped_bbox is None:
return None, 0, 0, None
out_width_base = clipped_bbox.width * magnification
out_height_base = clipped_bbox.height * magnification
if out_width_base == 0 or out_height_base == 0:
return None, 0, 0, None
if self.origin == 'upper':
# Flip the input image using a transform. This avoids the
# problem with flipping the array, which results in a copy
# when it is converted to contiguous in the C wrapper
t0 = Affine2D().translate(0, -A.shape[0]).scale(1, -1)
else:
t0 = IdentityTransform()
t0 += (
Affine2D()
.scale(
in_bbox.width / A.shape[1],
in_bbox.height / A.shape[0])
.translate(in_bbox.x0, in_bbox.y0)
+ self.get_transform())
t = (t0
+ Affine2D().translate(
-clipped_bbox.x0,
-clipped_bbox.y0)
.scale(magnification, magnification))
# So that the image is aligned with the edge of the axes, we want
# to round up the output width to the next integer. This also
# means scaling the transform just slightly to account for the
# extra subpixel.
if (t.is_affine and round_to_pixel_border and
(out_width_base % 1.0 != 0.0 or out_height_base % 1.0 != 0.0)):
out_width = int(ceil(out_width_base))
out_height = int(ceil(out_height_base))
extra_width = (out_width - out_width_base) / out_width_base
extra_height = (out_height - out_height_base) / out_height_base
t += Affine2D().scale(1.0 + extra_width, 1.0 + extra_height)
else:
out_width = int(out_width_base)
out_height = int(out_height_base)
if not unsampled:
if A.ndim not in (2, 3):
raise ValueError("Invalid shape {} for image data"
.format(A.shape))
if A.ndim == 2:
# if we are a 2D array, then we are running through the
# norm + colormap transformation. However, in general the
# input data is not going to match the size on the screen so we
# have to resample to the correct number of pixels
# need to
# TODO slice input array first
inp_dtype = A.dtype
a_min = A.min()
a_max = A.max()
# figure out the type we should scale to. For floats,
# leave as is. For integers cast to an appropriate-sized
# float. Small integers get smaller floats in an attempt
# to keep the memory footprint reasonable.
if a_min is np.ma.masked:
# all masked, so values don't matter
a_min, a_max = np.int32(0), np.int32(1)
if inp_dtype.kind == 'f':
scaled_dtype = A.dtype
# Cast to float64
if A.dtype not in (np.float32, np.float16):
if A.dtype != np.float64:
cbook._warn_external("Casting input data from "
"'{0}' to 'float64' for "
"imshow".format(A.dtype))
scaled_dtype = np.float64
else:
# probably an integer of some type.
da = a_max.astype(np.float64) - a_min.astype(np.float64)
if da > 1e8:
# give more breathing room if a big dynamic range
scaled_dtype = np.float64
else:
scaled_dtype = np.float32
# scale the input data to [.1, .9]. The Agg
# interpolators clip to [0, 1] internally, use a
# smaller input scale to identify which of the
# interpolated points need to be should be flagged as
# over / under.
# This may introduce numeric instabilities in very broadly
# scaled data
A_scaled = np.empty(A.shape, dtype=scaled_dtype)
A_scaled[:] = A
# clip scaled data around norm if necessary.
# This is necessary for big numbers at the edge of
# float64's ability to represent changes. Applying
# a norm first would be good, but ruins the interpolation
# of over numbers.
self.norm.autoscale_None(A)
dv = (np.float64(self.norm.vmax) -
np.float64(self.norm.vmin))
vmid = self.norm.vmin + dv / 2
fact = 1e7 if scaled_dtype == np.float64 else 1e4
newmin = vmid - dv * fact
if newmin < a_min:
newmin = None
else:
a_min = np.float64(newmin)
newmax = vmid + dv * fact
if newmax > a_max:
newmax = None
else:
a_max = np.float64(newmax)
if newmax is not None or newmin is not None:
A_scaled = np.clip(A_scaled, newmin, newmax)
A_scaled -= a_min
# a_min and a_max might be ndarray subclasses so use
# item to avoid errors
a_min = a_min.astype(scaled_dtype).item()
a_max = a_max.astype(scaled_dtype).item()
if a_min != a_max:
A_scaled /= ((a_max - a_min) / 0.8)
A_scaled += 0.1
A_resampled = np.zeros((out_height, out_width),
dtype=A_scaled.dtype)
# resample the input data to the correct resolution and shape
_image.resample(A_scaled, A_resampled,
t,
_interpd_[self.get_interpolation()],
self.get_resample(), 1.0,
self.get_filternorm(),
self.get_filterrad())
# we are done with A_scaled now, remove from namespace
# to be sure!
del A_scaled
# un-scale the resampled data to approximately the
# original range things that interpolated to above /
# below the original min/max will still be above /
# below, but possibly clipped in the case of higher order
# interpolation + drastically changing data.
A_resampled -= 0.1
if a_min != a_max:
A_resampled *= ((a_max - a_min) / 0.8)
A_resampled += a_min
# if using NoNorm, cast back to the original datatype
if isinstance(self.norm, mcolors.NoNorm):
A_resampled = A_resampled.astype(A.dtype)
mask = np.empty(A.shape, dtype=np.float32)
if A.mask.shape == A.shape:
# this is the case of a nontrivial mask
mask[:] = np.where(A.mask, np.float32(np.nan),
np.float32(1))
else:
mask[:] = 1
# we always have to interpolate the mask to account for
# non-affine transformations
out_mask = np.zeros((out_height, out_width),
dtype=mask.dtype)
_image.resample(mask, out_mask,
t,
_interpd_[self.get_interpolation()],
True, 1,
self.get_filternorm(),
self.get_filterrad())
# we are done with the mask, delete from namespace to be sure!
del mask
# Agg updates the out_mask in place. If the pixel has
# no image data it will not be updated (and still be 0
# as we initialized it), if input data that would go
# into that output pixel than it will be `nan`, if all
# the input data for a pixel is good it will be 1, and
# if there is _some_ good data in that output pixel it
# will be between [0, 1] (such as a rotated image).
out_alpha = np.array(out_mask)
out_mask = np.isnan(out_mask)
out_alpha[out_mask] = 1
# mask and run through the norm
output = self.norm(np.ma.masked_array(A_resampled, out_mask))
else:
# Always convert to RGBA, even if only RGB input
if A.shape[2] == 3:
A = _rgb_to_rgba(A)
elif A.shape[2] != 4:
raise ValueError("Invalid shape {} for image data"
.format(A.shape))
output = np.zeros((out_height, out_width, 4), dtype=A.dtype)
output_a = np.zeros((out_height, out_width), dtype=A.dtype)
alpha = self.get_alpha()
if alpha is None:
alpha = 1
#resample alpha channel
alpha_channel = A[..., 3]
_image.resample(
alpha_channel, output_a, t,
_interpd_[self.get_interpolation()],
self.get_resample(), alpha,
self.get_filternorm(), self.get_filterrad())
#resample rgb channels
A = _rgb_to_rgba(A[..., :3])
_image.resample(
A, output, t,
_interpd_[self.get_interpolation()],
self.get_resample(), alpha,
self.get_filternorm(), self.get_filterrad())
#recombine rgb and alpha channels
output[..., 3] = output_a
# at this point output is either a 2D array of normed data
# (of int or float)
# or an RGBA array of re-sampled input
output = self.to_rgba(output, bytes=True, norm=False)
# output is now a correctly sized RGBA array of uint8
# Apply alpha *after* if the input was greyscale without a mask
if A.ndim == 2:
alpha = self.get_alpha()
if alpha is None:
alpha = 1
alpha_channel = output[:, :, 3]
alpha_channel[:] = np.asarray(
np.asarray(alpha_channel, np.float32) * out_alpha * alpha,
np.uint8)
else:
if self._imcache is None:
self._imcache = self.to_rgba(A, bytes=True, norm=(A.ndim == 2))
output = self._imcache
# Subset the input image to only the part that will be
# displayed
subset = TransformedBbox(
clip_bbox, t0.frozen().inverted()).frozen()
output = output[
int(max(subset.ymin, 0)):
int(min(subset.ymax + 1, output.shape[0])),
int(max(subset.xmin, 0)):
int(min(subset.xmax + 1, output.shape[1]))]
t = Affine2D().translate(
int(max(subset.xmin, 0)), int(max(subset.ymin, 0))) + t
return output, clipped_bbox.x0, clipped_bbox.y0, t
def make_image(self, renderer, magnification=1.0, unsampled=False):
"""
Normalize, rescale, and colormap this image's data for rendering using
*renderer*, with the given *magnification*.
If *unsampled* is True, the image will not be scaled, but an
appropriate affine transformation will be returned instead.
Returns
-------
image : (M, N, 4) uint8 array
The RGBA image, resampled unless *unsampled* is True.
x, y : float
The upper left corner where the image should be drawn, in pixel
space.
trans : Affine2D
The affine transformation from image to pixel space.
"""
raise NotImplementedError('The make_image method must be overridden')
def _draw_unsampled_image(self, renderer, gc):
"""
draw unsampled image. The renderer should support a draw_image method
with scale parameter.
"""
im, l, b, trans = self.make_image(renderer, unsampled=True)
if im is None:
return
trans = Affine2D().scale(im.shape[1], im.shape[0]) + trans
renderer.draw_image(gc, l, b, im, trans)
def _check_unsampled_image(self, renderer):
"""
return True if the image is better to be drawn unsampled.
The derived class needs to override it.
"""
return False
@martist.allow_rasterization
def draw(self, renderer, *args, **kwargs):
# if not visible, declare victory and return
if not self.get_visible():
self.stale = False
return
# for empty images, there is nothing to draw!
if self.get_array().size == 0:
self.stale = False
return
# actually render the image.
gc = renderer.new_gc()
self._set_gc_clip(gc)
gc.set_alpha(self.get_alpha())
gc.set_url(self.get_url())
gc.set_gid(self.get_gid())
if (self._check_unsampled_image(renderer) and
self.get_transform().is_affine):
self._draw_unsampled_image(renderer, gc)
else:
im, l, b, trans = self.make_image(
renderer, renderer.get_image_magnification())
if im is not None:
renderer.draw_image(gc, l, b, im)
gc.restore()
self.stale = False
def contains(self, mouseevent):
"""
Test whether the mouse event occurred within the image.
"""
if self._contains is not None:
return self._contains(self, mouseevent)
# TODO: make sure this is consistent with patch and patch
# collection on nonlinear transformed coordinates.
# TODO: consider returning image coordinates (shouldn't
# be too difficult given that the image is rectilinear
x, y = mouseevent.xdata, mouseevent.ydata
xmin, xmax, ymin, ymax = self.get_extent()
if xmin > xmax:
xmin, xmax = xmax, xmin
if ymin > ymax:
ymin, ymax = ymax, ymin
if x is not None and y is not None:
inside = (xmin <= x <= xmax) and (ymin <= y <= ymax)
else:
inside = False
return inside, {}
def write_png(self, fname):
"""Write the image to png file with fname"""
from matplotlib import _png
im = self.to_rgba(self._A[::-1] if self.origin == 'lower' else self._A,
bytes=True, norm=True)
_png.write_png(im, fname)
def set_data(self, A):
"""
Set the image array.
Note that this function does *not* update the normalization used.
Parameters
----------
A : array-like
"""
self._A = cbook.safe_masked_invalid(A, copy=True)
if (self._A.dtype != np.uint8 and
not np.can_cast(self._A.dtype, float, "same_kind")):
raise TypeError("Image data of dtype {} cannot be converted to "
"float".format(self._A.dtype))
if not (self._A.ndim == 2
or self._A.ndim == 3 and self._A.shape[-1] in [3, 4]):
raise TypeError("Invalid shape {} for image data"
.format(self._A.shape))
if self._A.ndim == 3:
# If the input data has values outside the valid range (after
# normalisation), we issue a warning and then clip X to the bounds
# - otherwise casting wraps extreme values, hiding outliers and
# making reliable interpretation impossible.
high = 255 if np.issubdtype(self._A.dtype, np.integer) else 1
if self._A.min() < 0 or high < self._A.max():
_log.warning(
'Clipping input data to the valid range for imshow with '
'RGB data ([0..1] for floats or [0..255] for integers).'
)
self._A = np.clip(self._A, 0, high)
# Cast unsupported integer types to uint8
if self._A.dtype != np.uint8 and np.issubdtype(self._A.dtype,
np.integer):
self._A = self._A.astype(np.uint8)
self._imcache = None
self._rgbacache = None
self.stale = True
def set_array(self, A):
"""
Retained for backwards compatibility - use set_data instead.
Parameters
----------
A : array-like
"""
# This also needs to be here to override the inherited
# cm.ScalarMappable.set_array method so it is not invoked by mistake.
self.set_data(A)
def get_interpolation(self):
"""
Return the interpolation method the image uses when resizing.
One of 'nearest', 'bilinear', 'bicubic', 'spline16', 'spline36',
'hanning', 'hamming', 'hermite', 'kaiser', 'quadric', 'catrom',
'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos', or 'none'.
"""
return self._interpolation
def set_interpolation(self, s):
"""
Set the interpolation method the image uses when resizing.
if None, use a value from rc setting. If 'none', the image is
shown as is without interpolating. 'none' is only supported in
agg, ps and pdf backends and will fall back to 'nearest' mode
for other backends.
Parameters
----------
s : {'nearest', 'bilinear', 'bicubic', 'spline16', 'spline36', \
'hanning', 'hamming', 'hermite', 'kaiser', 'quadric', 'catrom', 'gaussian', \
'bessel', 'mitchell', 'sinc', 'lanczos', 'none'}
"""
if s is None:
s = rcParams['image.interpolation']
s = s.lower()
if s not in _interpd_:
raise ValueError('Illegal interpolation string')
self._interpolation = s
self.stale = True
def can_composite(self):
"""Return whether the image can be composited with its neighbors."""
trans = self.get_transform()
return (
self._interpolation != 'none' and
trans.is_affine and
trans.is_separable)
def set_resample(self, v):
"""
Set whether image resampling is used.
Parameters
----------
v : bool or None
If None, use :rc:`image.resample` = True.
"""
if v is None:
v = rcParams['image.resample']
self._resample = v
self.stale = True
def get_resample(self):
"""Return whether image resampling is used."""
return self._resample
def set_filternorm(self, filternorm):
"""
Set whether the resize filter normalizes the weights.
See help for `~.Axes.imshow`.
Parameters
----------
filternorm : bool
"""
self._filternorm = bool(filternorm)
self.stale = True
def get_filternorm(self):
"""Return whether the resize filter normalizes the weights."""
return self._filternorm
def set_filterrad(self, filterrad):
"""
Set the resize filter radius only applicable to some
interpolation schemes -- see help for imshow
Parameters
----------
filterrad : positive float
"""
r = float(filterrad)
if r <= 0:
raise ValueError("The filter radius must be a positive number")
self._filterrad = r
self.stale = True
def get_filterrad(self):
"""Return the filterrad setting."""
return self._filterrad
class AxesImage(_ImageBase):
def __str__(self):
return "AxesImage(%g,%g;%gx%g)" % tuple(self.axes.bbox.bounds)
def __init__(self, ax,
cmap=None,
norm=None,
interpolation=None,
origin=None,
extent=None,
filternorm=1,
filterrad=4.0,
resample=False,
**kwargs
):
"""
interpolation and cmap default to their rc settings
cmap is a colors.Colormap instance
norm is a colors.Normalize instance to map luminance to 0-1
extent is data axes (left, right, bottom, top) for making image plots
registered with data plots. Default is to label the pixel
centers with the zero-based row and column indices.
Additional kwargs are matplotlib.artist properties
"""
self._extent = extent
super().__init__(
ax,
cmap=cmap,
norm=norm,
interpolation=interpolation,
origin=origin,
filternorm=filternorm,
filterrad=filterrad,
resample=resample,
**kwargs
)
def get_window_extent(self, renderer=None):
x0, x1, y0, y1 = self._extent
bbox = Bbox.from_extents([x0, y0, x1, y1])
return bbox.transformed(self.axes.transData)
def make_image(self, renderer, magnification=1.0, unsampled=False):
# docstring inherited
trans = self.get_transform()
# image is created in the canvas coordinate.
x1, x2, y1, y2 = self.get_extent()
bbox = Bbox(np.array([[x1, y1], [x2, y2]]))
transformed_bbox = TransformedBbox(bbox, trans)
return self._make_image(
self._A, bbox, transformed_bbox, self.axes.bbox, magnification,
unsampled=unsampled)
def _check_unsampled_image(self, renderer):
"""
Return whether the image would be better drawn unsampled.
"""
return (self.get_interpolation() == "none"
and renderer.option_scale_image())
def set_extent(self, extent):
"""
extent is data axes (left, right, bottom, top) for making image plots
This updates ax.dataLim, and, if autoscaling, sets viewLim
to tightly fit the image, regardless of dataLim. Autoscaling
state is not changed, so following this with ax.autoscale_view
will redo the autoscaling in accord with dataLim.
"""
self._extent = xmin, xmax, ymin, ymax = extent
corners = (xmin, ymin), (xmax, ymax)
self.axes.update_datalim(corners)
self.sticky_edges.x[:] = [xmin, xmax]
self.sticky_edges.y[:] = [ymin, ymax]
if self.axes._autoscaleXon:
self.axes.set_xlim((xmin, xmax), auto=None)
if self.axes._autoscaleYon:
self.axes.set_ylim((ymin, ymax), auto=None)
self.stale = True
def get_extent(self):
"""Get the image extent: left, right, bottom, top"""
if self._extent is not None:
return self._extent
else:
sz = self.get_size()
numrows, numcols = sz
if self.origin == 'upper':
return (-0.5, numcols-0.5, numrows-0.5, -0.5)
else:
return (-0.5, numcols-0.5, -0.5, numrows-0.5)
def get_cursor_data(self, event):
"""
Return the image value at the event position or *None* if the event is
outside the image.
See Also
--------
matplotlib.artist.Artist.get_cursor_data
"""
xmin, xmax, ymin, ymax = self.get_extent()
if self.origin == 'upper':
ymin, ymax = ymax, ymin
arr = self.get_array()
data_extent = Bbox([[ymin, xmin], [ymax, xmax]])
array_extent = Bbox([[0, 0], arr.shape[:2]])
trans = BboxTransform(boxin=data_extent, boxout=array_extent)
y, x = event.ydata, event.xdata
point = trans.transform_point([y, x])
if any(np.isnan(point)):
return None
i, j = point.astype(int)
# Clip the coordinates at array bounds
if not (0 <= i < arr.shape[0]) or not (0 <= j < arr.shape[1]):
return None
else:
return arr[i, j]
def format_cursor_data(self, data):
if self.colorbar:
return (
"["
+ cbook.strip_math(
self.colorbar.formatter.format_data_short(data)).strip()
+ "]")
else:
return super().format_cursor_data(data)
class NonUniformImage(AxesImage):
def __init__(self, ax, *, interpolation='nearest', **kwargs):
"""
kwargs are identical to those for AxesImage, except
that 'nearest' and 'bilinear' are the only supported 'interpolation'
options.
"""
super().__init__(ax, **kwargs)
self.set_interpolation(interpolation)
def _check_unsampled_image(self, renderer):
"""
return False. Do not use unsampled image.
"""
return False
def make_image(self, renderer, magnification=1.0, unsampled=False):
# docstring inherited
if self._A is None:
raise RuntimeError('You must first set the image array')
if unsampled:
raise ValueError('unsampled not supported on NonUniformImage')
A = self._A
if A.ndim == 2:
if A.dtype != np.uint8:
A = self.to_rgba(A, bytes=True)
self.is_grayscale = self.cmap.is_gray()
else:
A = np.repeat(A[:, :, np.newaxis], 4, 2)
A[:, :, 3] = 255
self.is_grayscale = True
else:
if A.dtype != np.uint8:
A = (255*A).astype(np.uint8)
if A.shape[2] == 3:
B = np.zeros(tuple([*A.shape[0:2], 4]), np.uint8)
B[:, :, 0:3] = A
B[:, :, 3] = 255
A = B
self.is_grayscale = False
x0, y0, v_width, v_height = self.axes.viewLim.bounds
l, b, r, t = self.axes.bbox.extents
width = (np.round(r) + 0.5) - (np.round(l) - 0.5)
height = (np.round(t) + 0.5) - (np.round(b) - 0.5)
width *= magnification
height *= magnification
im = _image.pcolor(self._Ax, self._Ay, A,
int(height), int(width),
(x0, x0+v_width, y0, y0+v_height),
_interpd_[self._interpolation])
return im, l, b, IdentityTransform()
def set_data(self, x, y, A):
"""
Set the grid for the pixel centers, and the pixel values.
*x* and *y* are monotonic 1-D ndarrays of lengths N and M,
respectively, specifying pixel centers
*A* is an (M,N) ndarray or masked array of values to be
colormapped, or a (M,N,3) RGB array, or a (M,N,4) RGBA
array.
"""
x = np.array(x, np.float32)
y = np.array(y, np.float32)
A = cbook.safe_masked_invalid(A, copy=True)
if not (x.ndim == y.ndim == 1 and A.shape[0:2] == y.shape + x.shape):
raise TypeError("Axes don't match array shape")
if A.ndim not in [2, 3]:
raise TypeError("Can only plot 2D or 3D data")
if A.ndim == 3 and A.shape[2] not in [1, 3, 4]:
raise TypeError("3D arrays must have three (RGB) "
"or four (RGBA) color components")
if A.ndim == 3 and A.shape[2] == 1:
A.shape = A.shape[0:2]
self._A = A
self._Ax = x
self._Ay = y
self._imcache = None
self.stale = True
def set_array(self, *args):
raise NotImplementedError('Method not supported')
def set_interpolation(self, s):
"""
Parameters
----------
s : str, None
Either 'nearest', 'bilinear', or ``None``.
"""
if s is not None and s not in ('nearest', 'bilinear'):
raise NotImplementedError('Only nearest neighbor and '
'bilinear interpolations are supported')
AxesImage.set_interpolation(self, s)
def get_extent(self):
if self._A is None:
raise RuntimeError('Must set data first')
return self._Ax[0], self._Ax[-1], self._Ay[0], self._Ay[-1]
def set_filternorm(self, s):
pass
def set_filterrad(self, s):
pass
def set_norm(self, norm):
if self._A is not None:
raise RuntimeError('Cannot change colors after loading data')
super().set_norm(norm)
def set_cmap(self, cmap):
if self._A is not None:
raise RuntimeError('Cannot change colors after loading data')
super().set_cmap(cmap)
class PcolorImage(AxesImage):
"""
Make a pcolor-style plot with an irregular rectangular grid.
This uses a variation of the original irregular image code,
and it is used by pcolorfast for the corresponding grid type.
"""
def __init__(self, ax,
x=None,
y=None,
A=None,
cmap=None,
norm=None,
**kwargs
):
"""
cmap defaults to its rc setting
cmap is a colors.Colormap instance
norm is a colors.Normalize instance to map luminance to 0-1
Additional kwargs are matplotlib.artist properties
"""
super().__init__(ax, norm=norm, cmap=cmap)
self.update(kwargs)
if A is not None:
self.set_data(x, y, A)
def make_image(self, renderer, magnification=1.0, unsampled=False):
# docstring inherited
if self._A is None:
raise RuntimeError('You must first set the image array')
if unsampled:
raise ValueError('unsampled not supported on PColorImage')
fc = self.axes.patch.get_facecolor()
bg = mcolors.to_rgba(fc, 0)
bg = (np.array(bg)*255).astype(np.uint8)
l, b, r, t = self.axes.bbox.extents
width = (np.round(r) + 0.5) - (np.round(l) - 0.5)
height = (np.round(t) + 0.5) - (np.round(b) - 0.5)
# The extra cast-to-int is only needed for python2
width = int(np.round(width * magnification))
height = int(np.round(height * magnification))
if self._rgbacache is None:
A = self.to_rgba(self._A, bytes=True)
self._rgbacache = A
if self._A.ndim == 2:
self.is_grayscale = self.cmap.is_gray()
else:
A = self._rgbacache
vl = self.axes.viewLim
im = _image.pcolor2(self._Ax, self._Ay, A,
height,
width,
(vl.x0, vl.x1, vl.y0, vl.y1),
bg)
return im, l, b, IdentityTransform()
def _check_unsampled_image(self, renderer):
return False
def set_data(self, x, y, A):
"""
Set the grid for the rectangle boundaries, and the data values.
*x* and *y* are monotonic 1-D ndarrays of lengths N+1 and M+1,
respectively, specifying rectangle boundaries. If None,
they will be created as uniform arrays from 0 through N
and 0 through M, respectively.
*A* is an (M,N) ndarray or masked array of values to be
colormapped, or a (M,N,3) RGB array, or a (M,N,4) RGBA
array.
"""
A = cbook.safe_masked_invalid(A, copy=True)
if x is None:
x = np.arange(0, A.shape[1]+1, dtype=np.float64)
else:
x = np.array(x, np.float64).ravel()
if y is None:
y = np.arange(0, A.shape[0]+1, dtype=np.float64)
else:
y = np.array(y, np.float64).ravel()
if A.shape[:2] != (y.size-1, x.size-1):
raise ValueError(
"Axes don't match array shape. Got %s, expected %s." %
(A.shape[:2], (y.size - 1, x.size - 1)))
if A.ndim not in [2, 3]:
raise ValueError("A must be 2D or 3D")
if A.ndim == 3 and A.shape[2] == 1:
A.shape = A.shape[:2]
self.is_grayscale = False
if A.ndim == 3:
if A.shape[2] in [3, 4]:
if ((A[:, :, 0] == A[:, :, 1]).all() and
(A[:, :, 0] == A[:, :, 2]).all()):
self.is_grayscale = True
else:
raise ValueError("3D arrays must have RGB or RGBA as last dim")
# For efficient cursor readout, ensure x and y are increasing.
if x[-1] < x[0]:
x = x[::-1]
A = A[:, ::-1]
if y[-1] < y[0]:
y = y[::-1]
A = A[::-1]
self._A = A
self._Ax = x
self._Ay = y
self._rgbacache = None
self.stale = True
def set_array(self, *args):
raise NotImplementedError('Method not supported')
def get_cursor_data(self, event):
# docstring inherited
x, y = event.xdata, event.ydata
if (x < self._Ax[0] or x > self._Ax[-1] or
y < self._Ay[0] or y > self._Ay[-1]):
return None
j = np.searchsorted(self._Ax, x) - 1
i = np.searchsorted(self._Ay, y) - 1
try:
return self._A[i, j]
except IndexError:
return None
class FigureImage(_ImageBase):
zorder = 0
_interpolation = 'nearest'
def __init__(self, fig,
cmap=None,
norm=None,
offsetx=0,
offsety=0,
origin=None,
**kwargs
):
"""
cmap is a colors.Colormap instance
norm is a colors.Normalize instance to map luminance to 0-1
kwargs are an optional list of Artist keyword args
"""
super().__init__(
None,
norm=norm,
cmap=cmap,
origin=origin
)
self.figure = fig
self.ox = offsetx
self.oy = offsety
self.update(kwargs)
self.magnification = 1.0
def get_extent(self):
"""Get the image extent: left, right, bottom, top"""
numrows, numcols = self.get_size()
return (-0.5 + self.ox, numcols-0.5 + self.ox,
-0.5 + self.oy, numrows-0.5 + self.oy)
def make_image(self, renderer, magnification=1.0, unsampled=False):
# docstring inherited
fac = renderer.dpi/self.figure.dpi
# fac here is to account for pdf, eps, svg backends where
# figure.dpi is set to 72. This means we need to scale the
# image (using magnification) and offset it appropriately.
bbox = Bbox([[self.ox/fac, self.oy/fac],
[(self.ox/fac + self._A.shape[1]),
(self.oy/fac + self._A.shape[0])]])
width, height = self.figure.get_size_inches()
width *= renderer.dpi
height *= renderer.dpi
clip = Bbox([[0, 0], [width, height]])
return self._make_image(
self._A, bbox, bbox, clip, magnification=magnification / fac,
unsampled=unsampled, round_to_pixel_border=False)
def set_data(self, A):
"""Set the image array."""
cm.ScalarMappable.set_array(self,
cbook.safe_masked_invalid(A, copy=True))
self.stale = True
class BboxImage(_ImageBase):
"""The Image class whose size is determined by the given bbox."""
@cbook._delete_parameter("3.1", "interp_at_native")
def __init__(self, bbox,
cmap=None,
norm=None,
interpolation=None,
origin=None,
filternorm=1,
filterrad=4.0,
resample=False,
interp_at_native=True,
**kwargs
):
"""
cmap is a colors.Colormap instance
norm is a colors.Normalize instance to map luminance to 0-1
kwargs are an optional list of Artist keyword args
"""
super().__init__(
None,
cmap=cmap,
norm=norm,
interpolation=interpolation,
origin=origin,
filternorm=filternorm,
filterrad=filterrad,
resample=resample,
**kwargs
)
self.bbox = bbox
self._interp_at_native = interp_at_native
self._transform = IdentityTransform()
@cbook.deprecated("3.1")
@property
def interp_at_native(self):
return self._interp_at_native
def get_transform(self):
return self._transform
def get_window_extent(self, renderer=None):
if renderer is None:
renderer = self.get_figure()._cachedRenderer
if isinstance(self.bbox, BboxBase):
return self.bbox
elif callable(self.bbox):
return self.bbox(renderer)
else:
raise ValueError("unknown type of bbox")
def contains(self, mouseevent):
"""Test whether the mouse event occurred within the image."""
if self._contains is not None:
return self._contains(self, mouseevent)
if not self.get_visible(): # or self.get_figure()._renderer is None:
return False, {}
x, y = mouseevent.x, mouseevent.y
inside = self.get_window_extent().contains(x, y)
return inside, {}
def make_image(self, renderer, magnification=1.0, unsampled=False):
# docstring inherited
width, height = renderer.get_canvas_width_height()
bbox_in = self.get_window_extent(renderer).frozen()
bbox_in._points /= [width, height]
bbox_out = self.get_window_extent(renderer)
clip = Bbox([[0, 0], [width, height]])
self._transform = BboxTransform(Bbox([[0, 0], [1, 1]]), clip)
return self._make_image(
self._A,
bbox_in, bbox_out, clip, magnification, unsampled=unsampled)
def imread(fname, format=None):
"""
Read an image from a file into an array.
Parameters
----------
fname : str or file-like
The image file to read. This can be a filename, a URL or a Python
file-like object opened in read-binary mode.
format : str, optional
The image file format assumed for reading the data. If not
given, the format is deduced from the filename. If nothing can
be deduced, PNG is tried.
Returns
-------
imagedata : :class:`numpy.array`
The image data. The returned array has shape
- (M, N) for grayscale images.
- (M, N, 3) for RGB images.
- (M, N, 4) for RGBA images.
Notes
-----
Matplotlib can only read PNGs natively. Further image formats are
supported via the optional dependency on Pillow. Note, URL strings
are not compatible with Pillow. Check the `Pillow documentation`_
for more information.
.. _Pillow documentation: http://pillow.readthedocs.io/en/latest/
"""
def read_png(*args, **kwargs):
from matplotlib import _png
return _png.read_png(*args, **kwargs)
handlers = {'png': read_png, }
if format is None:
if isinstance(fname, str):
parsed = urllib.parse.urlparse(fname)
# If the string is a URL (Windows paths appear as if they have a
# length-1 scheme), assume png.
if len(parsed.scheme) > 1:
ext = 'png'
else:
basename, ext = os.path.splitext(fname)
ext = ext.lower()[1:]
elif hasattr(fname, 'geturl'): # Returned by urlopen().
# We could try to parse the url's path and use the extension, but
# returning png is consistent with the block above. Note that this
# if clause has to come before checking for fname.name as
# urlopen("file:///...") also has a name attribute (with the fixed
# value "<urllib response>").
ext = 'png'
elif hasattr(fname, 'name'):
basename, ext = os.path.splitext(fname.name)
ext = ext.lower()[1:]
else:
ext = 'png'
else:
ext = format
if ext not in handlers: # Try to load the image with PIL.
try:
from PIL import Image
except ImportError:
raise ValueError('Only know how to handle extensions: %s; '
'with Pillow installed matplotlib can handle '
'more images' % list(handlers))
with Image.open(fname) as image:
return pil_to_array(image)
handler = handlers[ext]
# To handle Unicode filenames, we pass a file object to the PNG
# reader extension, since Python handles them quite well, but it's
# tricky in C.
if isinstance(fname, str):
parsed = urllib.parse.urlparse(fname)
# If fname is a URL, download the data
if len(parsed.scheme) > 1:
from urllib import request
fd = BytesIO(request.urlopen(fname).read())
return handler(fd)
else:
with open(fname, 'rb') as fd:
return handler(fd)
else:
return handler(fname)
def imsave(fname, arr, vmin=None, vmax=None, cmap=None, format=None,
origin=None, dpi=100):
"""
Save an array as an image file.
Parameters
----------
fname : str or PathLike file-like
A path or a Python file-like object to store the image in.
If *format* is not set, then the output format is inferred from the
extension of *fname*, if any, and from :rc:`savefig.format` otherwise.
If *format* is set, it determines the output format.
arr : array-like
The image data. The shape can be one of
MxN (luminance), MxNx3 (RGB) or MxNx4 (RGBA).
vmin, vmax : scalar, optional
*vmin* and *vmax* set the color scaling for the image by fixing the
values that map to the colormap color limits. If either *vmin*
or *vmax* is None, that limit is determined from the *arr*
min/max value.
cmap : str or `~matplotlib.colors.Colormap`, optional
A Colormap instance or registered colormap name. The colormap
maps scalar data to colors. It is ignored for RGB(A) data.
Defaults to :rc:`image.cmap` ('viridis').
format : str, optional
The file format, e.g. 'png', 'pdf', 'svg', ... The behavior when this
is unset is documented under *fname*.
origin : {'upper', 'lower'}, optional
Indicates whether the ``(0, 0)`` index of the array is in the upper
left or lower left corner of the axes. Defaults to :rc:`image.origin`
('upper').
dpi : int
The DPI to store in the metadata of the file. This does not affect the
resolution of the output image.
"""
from matplotlib.figure import Figure
from matplotlib import _png
if isinstance(fname, os.PathLike):
fname = os.fspath(fname)
if format is None:
format = (Path(fname).suffix[1:] if isinstance(fname, str)
else rcParams["savefig.format"]).lower()
if format in ["pdf", "ps", "eps", "svg"]:
# Vector formats that are not handled by PIL.
fig = Figure(dpi=dpi, frameon=False)
fig.figimage(arr, cmap=cmap, vmin=vmin, vmax=vmax, origin=origin,
resize=True)
fig.savefig(fname, dpi=dpi, format=format, transparent=True)
else:
# Don't bother creating an image; this avoids rounding errors on the
# size when dividing and then multiplying by dpi.
sm = cm.ScalarMappable(cmap=cmap)
sm.set_clim(vmin, vmax)
if origin is None:
origin = rcParams["image.origin"]
if origin == "lower":
arr = arr[::-1]
rgba = sm.to_rgba(arr, bytes=True)
if format == "png":
_png.write_png(rgba, fname, dpi=dpi)
else:
try:
from PIL import Image
except ImportError as exc:
raise ImportError(
f"Saving to {format} requires Pillow") from exc
pil_shape = (rgba.shape[1], rgba.shape[0])
image = Image.frombuffer(
"RGBA", pil_shape, rgba, "raw", "RGBA", 0, 1)
if format in ["jpg", "jpeg"]:
format = "jpeg" # Pillow doesn't recognize "jpg".
color = tuple(
int(x * 255)
for x in mcolors.to_rgb(rcParams["savefig.facecolor"]))
background = Image.new("RGB", pil_shape, color)
background.paste(image, image)
image = background
image.save(fname, format=format, dpi=(dpi, dpi))
def pil_to_array(pilImage):
"""Load a `PIL image`_ and return it as a numpy array.
.. _PIL image: https://pillow.readthedocs.io/en/latest/reference/Image.html
Returns
-------
numpy.array
The array shape depends on the image type:
- (M, N) for grayscale images.
- (M, N, 3) for RGB images.
- (M, N, 4) for RGBA images.
"""
if pilImage.mode in ['RGBA', 'RGBX', 'RGB', 'L']:
# return MxNx4 RGBA, MxNx3 RBA, or MxN luminance array
return np.asarray(pilImage)
elif pilImage.mode.startswith('I;16'):
# return MxN luminance array of uint16
raw = pilImage.tobytes('raw', pilImage.mode)
if pilImage.mode.endswith('B'):
x = np.frombuffer(raw, '>u2')
else:
x = np.frombuffer(raw, '<u2')
return x.reshape(pilImage.size[::-1]).astype('=u2')
else: # try to convert to an rgba image
try:
pilImage = pilImage.convert('RGBA')
except ValueError:
raise RuntimeError('Unknown image mode')
return np.asarray(pilImage) # return MxNx4 RGBA array
def thumbnail(infile, thumbfile, scale=0.1, interpolation='bilinear',
preview=False):
"""
Make a thumbnail of image in *infile* with output filename *thumbfile*.
See :doc:`/gallery/misc/image_thumbnail_sgskip`.
Parameters
----------
infile : str or file-like
The image file -- must be PNG, or Pillow-readable if you have Pillow_
installed.
.. _Pillow: http://python-pillow.org/
thumbfile : str or file-like
The thumbnail filename.
scale : float, optional
The scale factor for the thumbnail.
interpolation : str, optional
The interpolation scheme used in the resampling. See the
*interpolation* parameter of `~.Axes.imshow` for possible values.
preview : bool, optional
If True, the default backend (presumably a user interface
backend) will be used which will cause a figure to be raised if
`~matplotlib.pyplot.show` is called. If it is False, the figure is
created using `FigureCanvasBase` and the drawing backend is selected
as `~matplotlib.figure.savefig` would normally do.
Returns
-------
figure : `~.figure.Figure`
The figure instance containing the thumbnail.
"""
im = imread(infile)
rows, cols, depth = im.shape
# This doesn't really matter (it cancels in the end) but the API needs it.
dpi = 100
height = rows / dpi * scale
width = cols / dpi * scale
if preview:
# Let the UI backend do everything.
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(width, height), dpi=dpi)
else:
from matplotlib.figure import Figure
fig = Figure(figsize=(width, height), dpi=dpi)
FigureCanvasBase(fig)
ax = fig.add_axes([0, 0, 1, 1], aspect='auto',
frameon=False, xticks=[], yticks=[])
ax.imshow(im, aspect='auto', resample=True, interpolation=interpolation)
fig.savefig(thumbfile, dpi=dpi)
return fig
|
994741b01bae5925c5914a0bc551e094be1cb653d0ac383eec904e5406bc27c3
|
"""
Abstract base classes define the primitives that renderers and
graphics contexts must implement to serve as a matplotlib backend
:class:`RendererBase`
An abstract base class to handle drawing/rendering operations.
:class:`FigureCanvasBase`
The abstraction layer that separates the
:class:`matplotlib.figure.Figure` from the backend specific
details like a user interface drawing area
:class:`GraphicsContextBase`
An abstract base class that provides color, line styles, etc...
:class:`Event`
The base class for all of the matplotlib event
handling. Derived classes such as :class:`KeyEvent` and
:class:`MouseEvent` store the meta data like keys and buttons
pressed, x and y locations in pixel and
:class:`~matplotlib.axes.Axes` coordinates.
:class:`ShowBase`
The base class for the Show class of each interactive backend;
the 'show' callable is then set to Show.__call__, inherited from
ShowBase.
:class:`ToolContainerBase`
The base class for the Toolbar class of each interactive backend.
:class:`StatusbarBase`
The base class for the messaging area.
"""
from contextlib import contextmanager
from enum import IntEnum
import functools
import importlib
import io
import logging
import os
import sys
import time
from weakref import WeakKeyDictionary
import numpy as np
import matplotlib as mpl
from matplotlib import (
backend_tools as tools, cbook, colors, textpath, tight_bbox, transforms,
widgets, get_backend, is_interactive, rcParams)
from matplotlib._pylab_helpers import Gcf
from matplotlib.transforms import Affine2D
from matplotlib.path import Path
try:
from PIL import PILLOW_VERSION
from distutils.version import LooseVersion
if LooseVersion(PILLOW_VERSION) >= "3.4":
_has_pil = True
else:
_has_pil = False
del PILLOW_VERSION
except ImportError:
_has_pil = False
_log = logging.getLogger(__name__)
_default_filetypes = {
'ps': 'Postscript',
'eps': 'Encapsulated Postscript',
'pdf': 'Portable Document Format',
'pgf': 'PGF code for LaTeX',
'png': 'Portable Network Graphics',
'raw': 'Raw RGBA bitmap',
'rgba': 'Raw RGBA bitmap',
'svg': 'Scalable Vector Graphics',
'svgz': 'Scalable Vector Graphics'
}
_default_backends = {
'ps': 'matplotlib.backends.backend_ps',
'eps': 'matplotlib.backends.backend_ps',
'pdf': 'matplotlib.backends.backend_pdf',
'pgf': 'matplotlib.backends.backend_pgf',
'png': 'matplotlib.backends.backend_agg',
'raw': 'matplotlib.backends.backend_agg',
'rgba': 'matplotlib.backends.backend_agg',
'svg': 'matplotlib.backends.backend_svg',
'svgz': 'matplotlib.backends.backend_svg',
}
def register_backend(format, backend, description=None):
"""
Register a backend for saving to a given file format.
Parameters
----------
format : str
File extension
backend : module string or canvas class
Backend for handling file output
description : str, optional
Description of the file type. Defaults to an empty string
"""
if description is None:
description = ''
_default_backends[format] = backend
_default_filetypes[format] = description
def get_registered_canvas_class(format):
"""
Return the registered default canvas for given file format.
Handles deferred import of required backend.
"""
if format not in _default_backends:
return None
backend_class = _default_backends[format]
if isinstance(backend_class, str):
backend_class = importlib.import_module(backend_class).FigureCanvas
_default_backends[format] = backend_class
return backend_class
class RendererBase(object):
"""An abstract base class to handle drawing/rendering operations.
The following methods must be implemented in the backend for full
functionality (though just implementing :meth:`draw_path` alone would
give a highly capable backend):
* :meth:`draw_path`
* :meth:`draw_image`
* :meth:`draw_gouraud_triangle`
The following methods *should* be implemented in the backend for
optimization reasons:
* :meth:`draw_text`
* :meth:`draw_markers`
* :meth:`draw_path_collection`
* :meth:`draw_quad_mesh`
"""
def __init__(self):
self._texmanager = None
self._text2path = textpath.TextToPath()
def open_group(self, s, gid=None):
"""
Open a grouping element with label *s* and *gid* (if set) as id.
Only used by the SVG renderer.
"""
def close_group(self, s):
"""
Close a grouping element with label *s*
Only used by the SVG renderer.
"""
def draw_path(self, gc, path, transform, rgbFace=None):
"""
Draws a :class:`~matplotlib.path.Path` instance using the
given affine transform.
"""
raise NotImplementedError
def draw_markers(self, gc, marker_path, marker_trans, path,
trans, rgbFace=None):
"""
Draws a marker at each of the vertices in path. This includes
all vertices, including control points on curves. To avoid
that behavior, those vertices should be removed before calling
this function.
This provides a fallback implementation of draw_markers that
makes multiple calls to :meth:`draw_path`. Some backends may
want to override this method in order to draw the marker only
once and reuse it multiple times.
Parameters
----------
gc : `GraphicsContextBase`
The graphics context
marker_trans : `matplotlib.transforms.Transform`
An affine transform applied to the marker.
trans : `matplotlib.transforms.Transform`
An affine transform applied to the path.
"""
for vertices, codes in path.iter_segments(trans, simplify=False):
if len(vertices):
x, y = vertices[-2:]
self.draw_path(gc, marker_path,
marker_trans +
transforms.Affine2D().translate(x, y),
rgbFace)
def draw_path_collection(self, gc, master_transform, paths, all_transforms,
offsets, offsetTrans, facecolors, edgecolors,
linewidths, linestyles, antialiaseds, urls,
offset_position):
"""
Draws a collection of paths selecting drawing properties from
the lists *facecolors*, *edgecolors*, *linewidths*,
*linestyles* and *antialiaseds*. *offsets* is a list of
offsets to apply to each of the paths. The offsets in
*offsets* are first transformed by *offsetTrans* before being
applied. *offset_position* may be either "screen" or "data"
depending on the space that the offsets are in.
This provides a fallback implementation of
:meth:`draw_path_collection` that makes multiple calls to
:meth:`draw_path`. Some backends may want to override this in
order to render each set of path data only once, and then
reference that path multiple times with the different offsets,
colors, styles etc. The generator methods
:meth:`_iter_collection_raw_paths` and
:meth:`_iter_collection` are provided to help with (and
standardize) the implementation across backends. It is highly
recommended to use those generators, so that changes to the
behavior of :meth:`draw_path_collection` can be made globally.
"""
path_ids = [
(path, transforms.Affine2D(transform))
for path, transform in self._iter_collection_raw_paths(
master_transform, paths, all_transforms)]
for xo, yo, path_id, gc0, rgbFace in self._iter_collection(
gc, master_transform, all_transforms, path_ids, offsets,
offsetTrans, facecolors, edgecolors, linewidths, linestyles,
antialiaseds, urls, offset_position):
path, transform = path_id
transform = transforms.Affine2D(
transform.get_matrix()).translate(xo, yo)
self.draw_path(gc0, path, transform, rgbFace)
def draw_quad_mesh(self, gc, master_transform, meshWidth, meshHeight,
coordinates, offsets, offsetTrans, facecolors,
antialiased, edgecolors):
"""
This provides a fallback implementation of
:meth:`draw_quad_mesh` that generates paths and then calls
:meth:`draw_path_collection`.
"""
from matplotlib.collections import QuadMesh
paths = QuadMesh.convert_mesh_to_paths(
meshWidth, meshHeight, coordinates)
if edgecolors is None:
edgecolors = facecolors
linewidths = np.array([gc.get_linewidth()], float)
return self.draw_path_collection(
gc, master_transform, paths, [], offsets, offsetTrans, facecolors,
edgecolors, linewidths, [], [antialiased], [None], 'screen')
def draw_gouraud_triangle(self, gc, points, colors, transform):
"""
Draw a Gouraud-shaded triangle.
Parameters
----------
points : array_like, shape=(3, 2)
Array of (x, y) points for the triangle.
colors : array_like, shape=(3, 4)
RGBA colors for each point of the triangle.
transform : `matplotlib.transforms.Transform`
An affine transform to apply to the points.
"""
raise NotImplementedError
def draw_gouraud_triangles(self, gc, triangles_array, colors_array,
transform):
"""
Draws a series of Gouraud triangles.
Parameters
----------
points : array_like, shape=(N, 3, 2)
Array of *N* (x, y) points for the triangles.
colors : array_like, shape=(N, 3, 4)
Array of *N* RGBA colors for each point of the triangles.
transform : `matplotlib.transforms.Transform`
An affine transform to apply to the points.
"""
transform = transform.frozen()
for tri, col in zip(triangles_array, colors_array):
self.draw_gouraud_triangle(gc, tri, col, transform)
def _iter_collection_raw_paths(self, master_transform, paths,
all_transforms):
"""
This is a helper method (along with :meth:`_iter_collection`) to make
it easier to write a space-efficient :meth:`draw_path_collection`
implementation in a backend.
This method yields all of the base path/transform
combinations, given a master transform, a list of paths and
list of transforms.
The arguments should be exactly what is passed in to
:meth:`draw_path_collection`.
The backend should take each yielded path and transform and
create an object that can be referenced (reused) later.
"""
Npaths = len(paths)
Ntransforms = len(all_transforms)
N = max(Npaths, Ntransforms)
if Npaths == 0:
return
transform = transforms.IdentityTransform()
for i in range(N):
path = paths[i % Npaths]
if Ntransforms:
transform = Affine2D(all_transforms[i % Ntransforms])
yield path, transform + master_transform
def _iter_collection_uses_per_path(self, paths, all_transforms,
offsets, facecolors, edgecolors):
"""
Compute how many times each raw path object returned by
_iter_collection_raw_paths would be used when calling
_iter_collection. This is intended for the backend to decide
on the tradeoff between using the paths in-line and storing
them once and reusing. Rounds up in case the number of uses
is not the same for every path.
"""
Npaths = len(paths)
if Npaths == 0 or len(facecolors) == len(edgecolors) == 0:
return 0
Npath_ids = max(Npaths, len(all_transforms))
N = max(Npath_ids, len(offsets))
return (N + Npath_ids - 1) // Npath_ids
def _iter_collection(self, gc, master_transform, all_transforms,
path_ids, offsets, offsetTrans, facecolors,
edgecolors, linewidths, linestyles,
antialiaseds, urls, offset_position):
"""
This is a helper method (along with
:meth:`_iter_collection_raw_paths`) to make it easier to write
a space-efficient :meth:`draw_path_collection` implementation in a
backend.
This method yields all of the path, offset and graphics
context combinations to draw the path collection. The caller
should already have looped over the results of
:meth:`_iter_collection_raw_paths` to draw this collection.
The arguments should be the same as that passed into
:meth:`draw_path_collection`, with the exception of
*path_ids*, which is a list of arbitrary objects that the
backend will use to reference one of the paths created in the
:meth:`_iter_collection_raw_paths` stage.
Each yielded result is of the form::
xo, yo, path_id, gc, rgbFace
where *xo*, *yo* is an offset; *path_id* is one of the elements of
*path_ids*; *gc* is a graphics context and *rgbFace* is a color to
use for filling the path.
"""
Ntransforms = len(all_transforms)
Npaths = len(path_ids)
Noffsets = len(offsets)
N = max(Npaths, Noffsets)
Nfacecolors = len(facecolors)
Nedgecolors = len(edgecolors)
Nlinewidths = len(linewidths)
Nlinestyles = len(linestyles)
Naa = len(antialiaseds)
Nurls = len(urls)
if (Nfacecolors == 0 and Nedgecolors == 0) or Npaths == 0:
return
if Noffsets:
toffsets = offsetTrans.transform(offsets)
gc0 = self.new_gc()
gc0.copy_properties(gc)
if Nfacecolors == 0:
rgbFace = None
if Nedgecolors == 0:
gc0.set_linewidth(0.0)
xo, yo = 0, 0
for i in range(N):
path_id = path_ids[i % Npaths]
if Noffsets:
xo, yo = toffsets[i % Noffsets]
if offset_position == 'data':
if Ntransforms:
transform = (
Affine2D(all_transforms[i % Ntransforms]) +
master_transform)
else:
transform = master_transform
xo, yo = transform.transform_point((xo, yo))
xp, yp = transform.transform_point((0, 0))
xo = -(xp - xo)
yo = -(yp - yo)
if not (np.isfinite(xo) and np.isfinite(yo)):
continue
if Nfacecolors:
rgbFace = facecolors[i % Nfacecolors]
if Nedgecolors:
if Nlinewidths:
gc0.set_linewidth(linewidths[i % Nlinewidths])
if Nlinestyles:
gc0.set_dashes(*linestyles[i % Nlinestyles])
fg = edgecolors[i % Nedgecolors]
if len(fg) == 4:
if fg[3] == 0.0:
gc0.set_linewidth(0)
else:
gc0.set_foreground(fg)
else:
gc0.set_foreground(fg)
if rgbFace is not None and len(rgbFace) == 4:
if rgbFace[3] == 0:
rgbFace = None
gc0.set_antialiased(antialiaseds[i % Naa])
if Nurls:
gc0.set_url(urls[i % Nurls])
yield xo, yo, path_id, gc0, rgbFace
gc0.restore()
def get_image_magnification(self):
"""
Get the factor by which to magnify images passed to :meth:`draw_image`.
Allows a backend to have images at a different resolution to other
artists.
"""
return 1.0
def draw_image(self, gc, x, y, im, transform=None):
"""
Draw an RGBA image.
Parameters
----------
gc : `GraphicsContextBase`
a graphics context with clipping information.
x : scalar
the distance in physical units (i.e., dots or pixels) from the left
hand side of the canvas.
y : scalar
the distance in physical units (i.e., dots or pixels) from the
bottom side of the canvas.
im : array_like, shape=(N, M, 4), dtype=np.uint8
An array of RGBA pixels.
transform : `matplotlib.transforms.Affine2DBase`
If and only if the concrete backend is written such that
:meth:`option_scale_image` returns ``True``, an affine
transformation *may* be passed to :meth:`draw_image`. It takes the
form of a :class:`~matplotlib.transforms.Affine2DBase` instance.
The translation vector of the transformation is given in physical
units (i.e., dots or pixels). Note that the transformation does not
override `x` and `y`, and has to be applied *before* translating
the result by `x` and `y` (this can be accomplished by adding `x`
and `y` to the translation vector defined by `transform`).
"""
raise NotImplementedError
def option_image_nocomposite(self):
"""
Return whether image composition by Matplotlib should be skipped.
Raster backends should usually return False (letting the C-level
rasterizer take care of image composition); vector backends should
usually return ``not rcParams["image.composite_image"]``.
"""
return False
def option_scale_image(self):
"""
Return whether arbitrary affine transformations in :meth:`draw_image`
are supported (True for most vector backends).
"""
return False
def draw_tex(self, gc, x, y, s, prop, angle, ismath='TeX!', mtext=None):
"""
"""
self._draw_text_as_path(gc, x, y, s, prop, angle, ismath="TeX")
def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
"""
Draw the text instance.
Parameters
----------
gc : `GraphicsContextBase`
The graphics context.
x : scalar
The x location of the text in display coords.
y : scalar
The y location of the text baseline in display coords.
s : str
The text string.
prop : `matplotlib.font_manager.FontProperties`
The font properties.
angle : scalar
The rotation angle in degrees.
mtext : `matplotlib.text.Text`
The original text object to be rendered.
Notes
-----
**backend implementers note**
When you are trying to determine if you have gotten your bounding box
right (which is what enables the text layout/alignment to work
properly), it helps to change the line in text.py::
if 0: bbox_artist(self, renderer)
to if 1, and then the actual bounding box will be plotted along with
your text.
"""
self._draw_text_as_path(gc, x, y, s, prop, angle, ismath)
def _get_text_path_transform(self, x, y, s, prop, angle, ismath):
"""
Return the text path and transform.
Parameters
----------
prop : `matplotlib.font_manager.FontProperties`
The font property.
s : str
The text to be converted.
ismath : bool or "TeX"
If True, use mathtext parser. If "TeX", use *usetex* mode.
"""
text2path = self._text2path
fontsize = self.points_to_pixels(prop.get_size_in_points())
verts, codes = text2path.get_text_path(prop, s, ismath=ismath)
path = Path(verts, codes)
angle = np.deg2rad(angle)
if self.flipy():
transform = Affine2D().scale(fontsize / text2path.FONT_SCALE,
fontsize / text2path.FONT_SCALE)
transform = transform.rotate(angle).translate(x, self.height - y)
else:
transform = Affine2D().scale(fontsize / text2path.FONT_SCALE,
fontsize / text2path.FONT_SCALE)
transform = transform.rotate(angle).translate(x, y)
return path, transform
def _draw_text_as_path(self, gc, x, y, s, prop, angle, ismath):
"""
Draw the text by converting them to paths using textpath module.
Parameters
----------
prop : `matplotlib.font_manager.FontProperties`
The font property.
s : str
The text to be converted.
usetex : bool
Whether to use matplotlib usetex mode.
ismath : bool or "TeX"
If True, use mathtext parser. If "TeX", use *usetex* mode.
"""
path, transform = self._get_text_path_transform(
x, y, s, prop, angle, ismath)
color = gc.get_rgb()
gc.set_linewidth(0.0)
self.draw_path(gc, path, transform, rgbFace=color)
def get_text_width_height_descent(self, s, prop, ismath):
"""
Get the width, height, and descent (offset from the bottom
to the baseline), in display coords, of the string *s* with
:class:`~matplotlib.font_manager.FontProperties` *prop*
"""
if ismath == 'TeX':
# todo: handle props
texmanager = self._text2path.get_texmanager()
fontsize = prop.get_size_in_points()
w, h, d = texmanager.get_text_width_height_descent(
s, fontsize, renderer=self)
return w, h, d
dpi = self.points_to_pixels(72)
if ismath:
dims = self._text2path.mathtext_parser.parse(s, dpi, prop)
return dims[0:3] # return width, height, descent
flags = self._text2path._get_hinting_flag()
font = self._text2path._get_font(prop)
size = prop.get_size_in_points()
font.set_size(size, dpi)
# the width and height of unrotated string
font.set_text(s, 0.0, flags=flags)
w, h = font.get_width_height()
d = font.get_descent()
w /= 64.0 # convert from subpixels
h /= 64.0
d /= 64.0
return w, h, d
def flipy(self):
"""
Return whether y values increase from top to bottom.
Note that this only affects drawing of texts and images.
"""
return True
def get_canvas_width_height(self):
"""Return the canvas width and height in display coords."""
return 1, 1
def get_texmanager(self):
"""Return the `.TexManager` instance."""
if self._texmanager is None:
from matplotlib.texmanager import TexManager
self._texmanager = TexManager()
return self._texmanager
def new_gc(self):
"""Return an instance of a `GraphicsContextBase`."""
return GraphicsContextBase()
def points_to_pixels(self, points):
"""
Convert points to display units.
You need to override this function (unless your backend
doesn't have a dpi, e.g., postscript or svg). Some imaging
systems assume some value for pixels per inch::
points to pixels = points * pixels_per_inch/72.0 * dpi/72.0
Parameters
----------
points : scalar or array_like
a float or a numpy array of float
Returns
-------
Points converted to pixels
"""
return points
@cbook.deprecated("3.1", alternative="cbook.strip_math")
def strip_math(self, s):
return cbook.strip_math(s)
def start_rasterizing(self):
"""
Switch to the raster renderer.
Used by `MixedModeRenderer`.
"""
def stop_rasterizing(self):
"""
Switch back to the vector renderer and draw the contents of the raster
renderer as an image on the vector renderer.
Used by `MixedModeRenderer`.
"""
def start_filter(self):
"""
Switch to a temporary renderer for image filtering effects.
Currently only supported by the agg renderer.
"""
def stop_filter(self, filter_func):
"""
Switch back to the original renderer. The contents of the temporary
renderer is processed with the *filter_func* and is drawn on the
original renderer as an image.
Currently only supported by the agg renderer.
"""
class GraphicsContextBase(object):
"""An abstract base class that provides color, line styles, etc."""
def __init__(self):
self._alpha = 1.0
self._forced_alpha = False # if True, _alpha overrides A from RGBA
self._antialiased = 1 # use 0,1 not True, False for extension code
self._capstyle = 'butt'
self._cliprect = None
self._clippath = None
self._dashes = None, None
self._joinstyle = 'round'
self._linestyle = 'solid'
self._linewidth = 1
self._rgb = (0.0, 0.0, 0.0, 1.0)
self._hatch = None
self._hatch_color = colors.to_rgba(rcParams['hatch.color'])
self._hatch_linewidth = rcParams['hatch.linewidth']
self._url = None
self._gid = None
self._snap = None
self._sketch = None
def copy_properties(self, gc):
'Copy properties from gc to self'
self._alpha = gc._alpha
self._forced_alpha = gc._forced_alpha
self._antialiased = gc._antialiased
self._capstyle = gc._capstyle
self._cliprect = gc._cliprect
self._clippath = gc._clippath
self._dashes = gc._dashes
self._joinstyle = gc._joinstyle
self._linestyle = gc._linestyle
self._linewidth = gc._linewidth
self._rgb = gc._rgb
self._hatch = gc._hatch
self._hatch_color = gc._hatch_color
self._hatch_linewidth = gc._hatch_linewidth
self._url = gc._url
self._gid = gc._gid
self._snap = gc._snap
self._sketch = gc._sketch
def restore(self):
"""
Restore the graphics context from the stack - needed only
for backends that save graphics contexts on a stack.
"""
def get_alpha(self):
"""
Return the alpha value used for blending - not supported on
all backends.
"""
return self._alpha
def get_antialiased(self):
"Return whether the object should try to do antialiased rendering."
return self._antialiased
def get_capstyle(self):
"""
Return the capstyle as a string in ('butt', 'round', 'projecting').
"""
return self._capstyle
def get_clip_rectangle(self):
"""
Return the clip rectangle as a `~matplotlib.transforms.Bbox` instance.
"""
return self._cliprect
def get_clip_path(self):
"""
Return the clip path in the form (path, transform), where path
is a :class:`~matplotlib.path.Path` instance, and transform is
an affine transform to apply to the path before clipping.
"""
if self._clippath is not None:
return self._clippath.get_transformed_path_and_affine()
return None, None
def get_dashes(self):
"""
Return the dash style as an (offset, dash-list) pair.
The dash list is a even-length list that gives the ink on, ink off in
points. See p. 107 of to PostScript `blue book`_ for more info.
Default value is (None, None).
.. _blue book: https://www-cdf.fnal.gov/offline/PostScript/BLUEBOOK.PDF
"""
return self._dashes
def get_forced_alpha(self):
"""
Return whether the value given by get_alpha() should be used to
override any other alpha-channel values.
"""
return self._forced_alpha
def get_joinstyle(self):
"""Return the line join style as one of ('miter', 'round', 'bevel')."""
return self._joinstyle
def get_linewidth(self):
"""Return the line width in points."""
return self._linewidth
def get_rgb(self):
"""Return a tuple of three or four floats from 0-1."""
return self._rgb
def get_url(self):
"""Return a url if one is set, None otherwise."""
return self._url
def get_gid(self):
"""Return the object identifier if one is set, None otherwise."""
return self._gid
def get_snap(self):
"""
Returns the snap setting, which can be:
* True: snap vertices to the nearest pixel center
* False: leave vertices as-is
* None: (auto) If the path contains only rectilinear line segments,
round to the nearest pixel center
"""
return self._snap
def set_alpha(self, alpha):
"""
Set the alpha value used for blending - not supported on all backends.
If ``alpha=None`` (the default), the alpha components of the
foreground and fill colors will be used to set their respective
transparencies (where applicable); otherwise, ``alpha`` will override
them.
"""
if alpha is not None:
self._alpha = alpha
self._forced_alpha = True
else:
self._alpha = 1.0
self._forced_alpha = False
self.set_foreground(self._rgb, isRGBA=True)
def set_antialiased(self, b):
"""Set whether object should be drawn with antialiased rendering."""
# Use ints to make life easier on extension code trying to read the gc.
self._antialiased = int(bool(b))
def set_capstyle(self, cs):
"""Set the capstyle to be one of ('butt', 'round', 'projecting')."""
cbook._check_in_list(['butt', 'round', 'projecting'], cs=cs)
self._capstyle = cs
def set_clip_rectangle(self, rectangle):
"""
Set the clip rectangle with sequence (left, bottom, width, height)
"""
self._cliprect = rectangle
def set_clip_path(self, path):
"""
Set the clip path and transformation. Path should be a
:class:`~matplotlib.transforms.TransformedPath` instance.
"""
if (path is not None
and not isinstance(path, transforms.TransformedPath)):
raise ValueError("Path should be a "
"matplotlib.transforms.TransformedPath instance")
self._clippath = path
def set_dashes(self, dash_offset, dash_list):
"""
Set the dash style for the gc.
Parameters
----------
dash_offset : float or None
The offset (usually 0).
dash_list : array_like or None
The on-off sequence as points.
Notes
-----
``(None, None)`` specifies a solid line.
See p. 107 of to PostScript `blue book`_ for more info.
.. _blue book: https://www-cdf.fnal.gov/offline/PostScript/BLUEBOOK.PDF
"""
if dash_list is not None:
dl = np.asarray(dash_list)
if np.any(dl < 0.0):
raise ValueError(
"All values in the dash list must be positive")
self._dashes = dash_offset, dash_list
def set_foreground(self, fg, isRGBA=False):
"""
Set the foreground color.
Parameters
----------
fg : color
isRGBA : bool
If *fg* is known to be an ``(r, g, b, a)`` tuple, *isRGBA* can be
set to True to improve performance.
"""
if self._forced_alpha and isRGBA:
self._rgb = fg[:3] + (self._alpha,)
elif self._forced_alpha:
self._rgb = colors.to_rgba(fg, self._alpha)
elif isRGBA:
self._rgb = fg
else:
self._rgb = colors.to_rgba(fg)
def set_joinstyle(self, js):
"""Set the join style to be one of ('miter', 'round', 'bevel')."""
cbook._check_in_list(['miter', 'round', 'bevel'], js=js)
self._joinstyle = js
def set_linewidth(self, w):
"""Set the linewidth in points."""
self._linewidth = float(w)
def set_url(self, url):
"""Set the url for links in compatible backends."""
self._url = url
def set_gid(self, id):
"""Set the id."""
self._gid = id
def set_snap(self, snap):
"""
Set the snap setting which may be:
* True: snap vertices to the nearest pixel center
* False: leave vertices as-is
* None: (auto) If the path contains only rectilinear line segments,
round to the nearest pixel center
"""
self._snap = snap
def set_hatch(self, hatch):
"""Set the hatch style (for fills)."""
self._hatch = hatch
def get_hatch(self):
"""Get the current hatch style."""
return self._hatch
def get_hatch_path(self, density=6.0):
"""Return a `Path` for the current hatch."""
hatch = self.get_hatch()
if hatch is None:
return None
return Path.hatch(hatch, density)
def get_hatch_color(self):
"""Get the hatch color."""
return self._hatch_color
def set_hatch_color(self, hatch_color):
"""Set the hatch color."""
self._hatch_color = hatch_color
def get_hatch_linewidth(self):
"""Get the hatch linewidth."""
return self._hatch_linewidth
def get_sketch_params(self):
"""
Return the sketch parameters for the artist.
Returns
-------
sketch_params : tuple or `None`
A 3-tuple with the following elements:
* `scale`: The amplitude of the wiggle perpendicular to the
source line.
* `length`: The length of the wiggle along the line.
* `randomness`: The scale factor by which the length is
shrunken or expanded.
May return `None` if no sketch parameters were set.
"""
return self._sketch
def set_sketch_params(self, scale=None, length=None, randomness=None):
"""
Set the sketch parameters.
Parameters
----------
scale : float, optional
The amplitude of the wiggle perpendicular to the source line, in
pixels. If scale is `None`, or not provided, no sketch filter will
be provided.
length : float, optional
The length of the wiggle along the line, in pixels (default 128).
randomness : float, optional
The scale factor by which the length is shrunken or expanded
(default 16).
"""
self._sketch = (
None if scale is None
else (scale, length or 128., randomness or 16.))
class TimerBase(object):
"""
A base class for providing timer events, useful for things animations.
Backends need to implement a few specific methods in order to use their
own timing mechanisms so that the timer events are integrated into their
event loops.
Mandatory functions that must be implemented:
* `_timer_start`: Contains backend-specific code for starting
the timer
* `_timer_stop`: Contains backend-specific code for stopping
the timer
Optional overrides:
* `_timer_set_single_shot`: Code for setting the timer to
single shot operating mode, if supported by the timer
object. If not, the `Timer` class itself will store the flag
and the `_on_timer` method should be overridden to support
such behavior.
* `_timer_set_interval`: Code for setting the interval on the
timer, if there is a method for doing so on the timer
object.
* `_on_timer`: This is the internal function that any timer
object should call, which will handle the task of running
all callbacks that have been set.
Attributes
----------
interval : scalar
The time between timer events in milliseconds. Default is 1000 ms.
single_shot : bool
Boolean flag indicating whether this timer should operate as single
shot (run once and then stop). Defaults to `False`.
callbacks : List[Tuple[callable, Tuple, Dict]]
Stores list of (func, args, kwargs) tuples that will be called upon
timer events. This list can be manipulated directly, or the
functions `add_callback` and `remove_callback` can be used.
"""
def __init__(self, interval=None, callbacks=None):
#Initialize empty callbacks list and setup default settings if necssary
if callbacks is None:
self.callbacks = []
else:
self.callbacks = callbacks[:] # Create a copy
if interval is None:
self._interval = 1000
else:
self._interval = interval
self._single = False
# Default attribute for holding the GUI-specific timer object
self._timer = None
def __del__(self):
"""Need to stop timer and possibly disconnect timer."""
self._timer_stop()
def start(self, interval=None):
"""
Start the timer object.
Parameters
----------
interval : int, optional
Timer interval in milliseconds; overrides a previously set interval
if provided.
"""
if interval is not None:
self._set_interval(interval)
self._timer_start()
def stop(self):
"""Stop the timer."""
self._timer_stop()
def _timer_start(self):
pass
def _timer_stop(self):
pass
@property
def interval(self):
return self._interval
@interval.setter
def interval(self, interval):
# Force to int since none of the backends actually support fractional
# milliseconds, and some error or give warnings.
interval = int(interval)
self._interval = interval
self._timer_set_interval()
@property
def single_shot(self):
return self._single
@single_shot.setter
def single_shot(self, ss):
self._single = ss
self._timer_set_single_shot()
def add_callback(self, func, *args, **kwargs):
"""
Register *func* to be called by timer when the event fires. Any
additional arguments provided will be passed to *func*.
This function returns *func*, which makes it possible to use it as a
decorator.
"""
self.callbacks.append((func, args, kwargs))
return func
def remove_callback(self, func, *args, **kwargs):
"""
Remove *func* from list of callbacks.
*args* and *kwargs* are optional and used to distinguish between copies
of the same function registered to be called with different arguments.
This behavior is deprecated. In the future, `*args, **kwargs` won't be
considered anymore; to keep a specific callback removable by itself,
pass it to `add_callback` as a `functools.partial` object.
"""
if args or kwargs:
cbook.warn_deprecated(
"3.1", "In a future version, Timer.remove_callback will not "
"take *args, **kwargs anymore, but remove all callbacks where "
"the callable matches; to keep a specific callback removable "
"by itself, pass it to add_callback as a functools.partial "
"object.")
self.callbacks.remove((func, args, kwargs))
else:
funcs = [c[0] for c in self.callbacks]
if func in funcs:
self.callbacks.pop(funcs.index(func))
def _timer_set_interval(self):
"""Used to set interval on underlying timer object."""
def _timer_set_single_shot(self):
"""Used to set single shot on underlying timer object."""
def _on_timer(self):
"""
Runs all function that have been registered as callbacks. Functions
can return False (or 0) if they should not be called any more. If there
are no callbacks, the timer is automatically stopped.
"""
for func, args, kwargs in self.callbacks:
ret = func(*args, **kwargs)
# docstring above explains why we use `if ret == 0` here,
# instead of `if not ret`.
# This will also catch `ret == False` as `False == 0`
# but does not annoy the linters
# https://docs.python.org/3/library/stdtypes.html#boolean-values
if ret == 0:
self.callbacks.remove((func, args, kwargs))
if len(self.callbacks) == 0:
self.stop()
class Event(object):
"""
A matplotlib event. Attach additional attributes as defined in
:meth:`FigureCanvasBase.mpl_connect`. The following attributes
are defined and shown with their default values
Attributes
----------
name : str
the event name
canvas : `FigureCanvasBase`
the backend-specific canvas instance generating the event
guiEvent
the GUI event that triggered the matplotlib event
"""
def __init__(self, name, canvas, guiEvent=None):
self.name = name
self.canvas = canvas
self.guiEvent = guiEvent
class DrawEvent(Event):
"""
An event triggered by a draw operation on the canvas
In most backends callbacks subscribed to this callback will be
fired after the rendering is complete but before the screen is
updated. Any extra artists drawn to the canvas's renderer will
be reflected without an explicit call to ``blit``.
.. warning ::
Calling ``canvas.draw`` and ``canvas.blit`` in these callbacks may
not be safe with all backends and may cause infinite recursion.
In addition to the :class:`Event` attributes, the following event
attributes are defined:
Attributes
----------
renderer : `RendererBase`
the renderer for the draw event
"""
def __init__(self, name, canvas, renderer):
Event.__init__(self, name, canvas)
self.renderer = renderer
class ResizeEvent(Event):
"""
An event triggered by a canvas resize
In addition to the :class:`Event` attributes, the following event
attributes are defined:
Attributes
----------
width : scalar
width of the canvas in pixels
height : scalar
height of the canvas in pixels
"""
def __init__(self, name, canvas):
Event.__init__(self, name, canvas)
self.width, self.height = canvas.get_width_height()
class CloseEvent(Event):
"""An event triggered by a figure being closed."""
class LocationEvent(Event):
"""
An event that has a screen location.
The following additional attributes are defined and shown with
their default values.
In addition to the :class:`Event` attributes, the following
event attributes are defined:
Attributes
----------
x : scalar
x position - pixels from left of canvas
y : scalar
y position - pixels from bottom of canvas
inaxes : bool
the :class:`~matplotlib.axes.Axes` instance if mouse is over axes
xdata : scalar
x coord of mouse in data coords
ydata : scalar
y coord of mouse in data coords
"""
lastevent = None # the last event that was triggered before this one
def __init__(self, name, canvas, x, y, guiEvent=None):
"""
*x*, *y* in figure coords, 0,0 = bottom, left
"""
Event.__init__(self, name, canvas, guiEvent=guiEvent)
# x position - pixels from left of canvas
self.x = int(x) if x is not None else x
# y position - pixels from right of canvas
self.y = int(y) if y is not None else y
self.inaxes = None # the Axes instance if mouse us over axes
self.xdata = None # x coord of mouse in data coords
self.ydata = None # y coord of mouse in data coords
if x is None or y is None:
# cannot check if event was in axes if no x,y info
self._update_enter_leave()
return
if self.canvas.mouse_grabber is None:
self.inaxes = self.canvas.inaxes((x, y))
else:
self.inaxes = self.canvas.mouse_grabber
if self.inaxes is not None:
try:
trans = self.inaxes.transData.inverted()
xdata, ydata = trans.transform_point((x, y))
except ValueError:
pass
else:
self.xdata = xdata
self.ydata = ydata
self._update_enter_leave()
def _update_enter_leave(self):
'process the figure/axes enter leave events'
if LocationEvent.lastevent is not None:
last = LocationEvent.lastevent
if last.inaxes != self.inaxes:
# process axes enter/leave events
try:
if last.inaxes is not None:
last.canvas.callbacks.process('axes_leave_event', last)
except Exception:
pass
# See ticket 2901582.
# I think this is a valid exception to the rule
# against catching all exceptions; if anything goes
# wrong, we simply want to move on and process the
# current event.
if self.inaxes is not None:
self.canvas.callbacks.process('axes_enter_event', self)
else:
# process a figure enter event
if self.inaxes is not None:
self.canvas.callbacks.process('axes_enter_event', self)
LocationEvent.lastevent = self
class MouseButton(IntEnum):
LEFT = 1
MIDDLE = 2
RIGHT = 3
BACK = 8
FORWARD = 9
class MouseEvent(LocationEvent):
"""
A mouse event ('button_press_event',
'button_release_event',
'scroll_event',
'motion_notify_event').
In addition to the :class:`Event` and :class:`LocationEvent`
attributes, the following attributes are defined:
Attributes
----------
button : {None, MouseButton.LEFT, MouseButton.MIDDLE, MouseButton.RIGHT, \
'up', 'down'}
The button pressed. 'up' and 'down' are used for scroll events.
Note that in the nbagg backend, both the middle and right clicks
return RIGHT since right clicking will bring up the context menu in
some browsers.
Note that LEFT and RIGHT actually refer to the "primary" and
"secondary" buttons, i.e. if the user inverts their left and right
buttons ("left-handed setting") then the LEFT button will be the one
physically on the right.
key : None or str
The key pressed when the mouse event triggered, e.g. 'shift'.
See `KeyEvent`.
step : scalar
The number of scroll steps (positive for 'up', negative for 'down').
dblclick : bool
Whether the event is a double-click.
Examples
--------
Usage::
def on_press(event):
print('you pressed', event.button, event.xdata, event.ydata)
cid = fig.canvas.mpl_connect('button_press_event', on_press)
"""
def __init__(self, name, canvas, x, y, button=None, key=None,
step=0, dblclick=False, guiEvent=None):
"""
x, y in figure coords, 0,0 = bottom, left
button pressed None, 1, 2, 3, 'up', 'down'
"""
LocationEvent.__init__(self, name, canvas, x, y, guiEvent=guiEvent)
if button in MouseButton.__members__.values():
button = MouseButton(button)
self.button = button
self.key = key
self.step = step
self.dblclick = dblclick
def __str__(self):
return (f"{self.name}: "
f"xy=({self.x}, {self.y}) xydata=({self.xdata}, {self.ydata}) "
f"button={self.button} dblclick={self.dblclick} "
f"inaxes={self.inaxes}")
class PickEvent(Event):
"""
a pick event, fired when the user picks a location on the canvas
sufficiently close to an artist.
Attrs: all the :class:`Event` attributes plus
Attributes
----------
mouseevent : `MouseEvent`
the mouse event that generated the pick
artist : `matplotlib.artist.Artist`
the picked artist
other
extra class dependent attrs -- e.g., a
:class:`~matplotlib.lines.Line2D` pick may define different
extra attributes than a
:class:`~matplotlib.collections.PatchCollection` pick event
Examples
--------
Usage::
ax.plot(np.rand(100), 'o', picker=5) # 5 points tolerance
def on_pick(event):
line = event.artist
xdata, ydata = line.get_data()
ind = event.ind
print('on pick line:', np.array([xdata[ind], ydata[ind]]).T)
cid = fig.canvas.mpl_connect('pick_event', on_pick)
"""
def __init__(self, name, canvas, mouseevent, artist,
guiEvent=None, **kwargs):
Event.__init__(self, name, canvas, guiEvent)
self.mouseevent = mouseevent
self.artist = artist
self.__dict__.update(kwargs)
class KeyEvent(LocationEvent):
"""
A key event (key press, key release).
Attach additional attributes as defined in
:meth:`FigureCanvasBase.mpl_connect`.
In addition to the :class:`Event` and :class:`LocationEvent`
attributes, the following attributes are defined:
Attributes
----------
key : None or str
the key(s) pressed. Could be **None**, a single case sensitive ascii
character ("g", "G", "#", etc.), a special key
("control", "shift", "f1", "up", etc.) or a
combination of the above (e.g., "ctrl+alt+g", "ctrl+alt+G").
Notes
-----
Modifier keys will be prefixed to the pressed key and will be in the order
"ctrl", "alt", "super". The exception to this rule is when the pressed key
is itself a modifier key, therefore "ctrl+alt" and "alt+control" can both
be valid key values.
Examples
--------
Usage::
def on_key(event):
print('you pressed', event.key, event.xdata, event.ydata)
cid = fig.canvas.mpl_connect('key_press_event', on_key)
"""
def __init__(self, name, canvas, key, x=0, y=0, guiEvent=None):
LocationEvent.__init__(self, name, canvas, x, y, guiEvent=guiEvent)
self.key = key
class FigureCanvasBase(object):
"""
The canvas the figure renders into.
Public attributes
Attributes
----------
figure : `matplotlib.figure.Figure`
A high-level figure instance
"""
events = [
'resize_event',
'draw_event',
'key_press_event',
'key_release_event',
'button_press_event',
'button_release_event',
'scroll_event',
'motion_notify_event',
'pick_event',
'idle_event',
'figure_enter_event',
'figure_leave_event',
'axes_enter_event',
'axes_leave_event',
'close_event'
]
supports_blit = True
fixed_dpi = None
filetypes = _default_filetypes
if _has_pil:
# JPEG support
register_backend('jpg', 'matplotlib.backends.backend_agg',
'Joint Photographic Experts Group')
register_backend('jpeg', 'matplotlib.backends.backend_agg',
'Joint Photographic Experts Group')
# TIFF support
register_backend('tif', 'matplotlib.backends.backend_agg',
'Tagged Image File Format')
register_backend('tiff', 'matplotlib.backends.backend_agg',
'Tagged Image File Format')
def __init__(self, figure):
self._fix_ipython_backend2gui()
self._is_idle_drawing = True
self._is_saving = False
figure.set_canvas(self)
self.figure = figure
# a dictionary from event name to a dictionary that maps cid->func
self.callbacks = cbook.CallbackRegistry()
self.widgetlock = widgets.LockDraw()
self._button = None # the button pressed
self._key = None # the key pressed
self._lastx, self._lasty = None, None
self.button_pick_id = self.mpl_connect('button_press_event', self.pick)
self.scroll_pick_id = self.mpl_connect('scroll_event', self.pick)
self.mouse_grabber = None # the axes currently grabbing mouse
self.toolbar = None # NavigationToolbar2 will set me
self._is_idle_drawing = False
@classmethod
@functools.lru_cache()
def _fix_ipython_backend2gui(cls):
# Fix hard-coded module -> toolkit mapping in IPython (used for
# `ipython --auto`). This cannot be done at import time due to
# ordering issues, so we do it when creating a canvas, and should only
# be done once per class (hence the `lru_cache(1)`).
if "IPython" not in sys.modules:
return
import IPython
ip = IPython.get_ipython()
if not ip:
return
from IPython.core import pylabtools as pt
if (not hasattr(pt, "backend2gui")
or not hasattr(ip, "enable_matplotlib")):
# In case we ever move the patch to IPython and remove these APIs,
# don't break on our side.
return
backend_mod = sys.modules[cls.__module__]
rif = getattr(backend_mod, "required_interactive_framework", None)
backend2gui_rif = {"qt5": "qt", "qt4": "qt", "gtk3": "gtk3",
"wx": "wx", "macosx": "osx"}.get(rif)
if backend2gui_rif:
pt.backend2gui[get_backend()] = backend2gui_rif
# Work around pylabtools.find_gui_and_backend always reading from
# rcParamsOrig.
orig_origbackend = mpl.rcParamsOrig["backend"]
try:
mpl.rcParamsOrig["backend"] = mpl.rcParams["backend"]
ip.enable_matplotlib()
finally:
mpl.rcParamsOrig["backend"] = orig_origbackend
@contextmanager
def _idle_draw_cntx(self):
self._is_idle_drawing = True
yield
self._is_idle_drawing = False
def is_saving(self):
"""
Returns whether the renderer is in the process of saving
to a file, rather than rendering for an on-screen buffer.
"""
return self._is_saving
def pick(self, mouseevent):
if not self.widgetlock.locked():
self.figure.pick(mouseevent)
def blit(self, bbox=None):
"""Blit the canvas in bbox (default entire canvas)."""
def resize(self, w, h):
"""Set the canvas size in pixels."""
def draw_event(self, renderer):
"""Pass a `DrawEvent` to all functions connected to ``draw_event``."""
s = 'draw_event'
event = DrawEvent(s, self, renderer)
self.callbacks.process(s, event)
def resize_event(self):
"""Pass a `ResizeEvent` to all functions connected to ``resize_event``.
"""
s = 'resize_event'
event = ResizeEvent(s, self)
self.callbacks.process(s, event)
self.draw_idle()
def close_event(self, guiEvent=None):
"""Pass a `CloseEvent` to all functions connected to ``close_event``.
"""
s = 'close_event'
try:
event = CloseEvent(s, self, guiEvent=guiEvent)
self.callbacks.process(s, event)
except (TypeError, AttributeError):
pass
# Suppress the TypeError when the python session is being killed.
# It may be that a better solution would be a mechanism to
# disconnect all callbacks upon shutdown.
# AttributeError occurs on OSX with qt4agg upon exiting
# with an open window; 'callbacks' attribute no longer exists.
def key_press_event(self, key, guiEvent=None):
"""Pass a `KeyEvent` to all functions connected to ``key_press_event``.
"""
self._key = key
s = 'key_press_event'
event = KeyEvent(
s, self, key, self._lastx, self._lasty, guiEvent=guiEvent)
self.callbacks.process(s, event)
def key_release_event(self, key, guiEvent=None):
"""
Pass a `KeyEvent` to all functions connected to ``key_release_event``.
"""
s = 'key_release_event'
event = KeyEvent(
s, self, key, self._lastx, self._lasty, guiEvent=guiEvent)
self.callbacks.process(s, event)
self._key = None
def pick_event(self, mouseevent, artist, **kwargs):
"""
This method will be called by artists who are picked and will
fire off :class:`PickEvent` callbacks registered listeners
"""
s = 'pick_event'
event = PickEvent(s, self, mouseevent, artist,
guiEvent=mouseevent.guiEvent,
**kwargs)
self.callbacks.process(s, event)
def scroll_event(self, x, y, step, guiEvent=None):
"""
Backend derived classes should call this function on any
scroll wheel event. x,y are the canvas coords: 0,0 is lower,
left. button and key are as defined in MouseEvent.
This method will be call all functions connected to the
'scroll_event' with a :class:`MouseEvent` instance.
"""
if step >= 0:
self._button = 'up'
else:
self._button = 'down'
s = 'scroll_event'
mouseevent = MouseEvent(s, self, x, y, self._button, self._key,
step=step, guiEvent=guiEvent)
self.callbacks.process(s, mouseevent)
def button_press_event(self, x, y, button, dblclick=False, guiEvent=None):
"""
Backend derived classes should call this function on any mouse
button press. x,y are the canvas coords: 0,0 is lower, left.
button and key are as defined in :class:`MouseEvent`.
This method will be call all functions connected to the
'button_press_event' with a :class:`MouseEvent` instance.
"""
self._button = button
s = 'button_press_event'
mouseevent = MouseEvent(s, self, x, y, button, self._key,
dblclick=dblclick, guiEvent=guiEvent)
self.callbacks.process(s, mouseevent)
def button_release_event(self, x, y, button, guiEvent=None):
"""
Backend derived classes should call this function on any mouse
button release.
This method will call all functions connected to the
'button_release_event' with a :class:`MouseEvent` instance.
Parameters
----------
x : scalar
the canvas coordinates where 0=left
y : scalar
the canvas coordinates where 0=bottom
guiEvent
the native UI event that generated the mpl event
"""
s = 'button_release_event'
event = MouseEvent(s, self, x, y, button, self._key, guiEvent=guiEvent)
self.callbacks.process(s, event)
self._button = None
def motion_notify_event(self, x, y, guiEvent=None):
"""
Backend derived classes should call this function on any
motion-notify-event.
This method will call all functions connected to the
'motion_notify_event' with a :class:`MouseEvent` instance.
Parameters
----------
x : scalar
the canvas coordinates where 0=left
y : scalar
the canvas coordinates where 0=bottom
guiEvent
the native UI event that generated the mpl event
"""
self._lastx, self._lasty = x, y
s = 'motion_notify_event'
event = MouseEvent(s, self, x, y, self._button, self._key,
guiEvent=guiEvent)
self.callbacks.process(s, event)
def leave_notify_event(self, guiEvent=None):
"""
Backend derived classes should call this function when leaving
canvas
Parameters
----------
guiEvent
the native UI event that generated the mpl event
"""
self.callbacks.process('figure_leave_event', LocationEvent.lastevent)
LocationEvent.lastevent = None
self._lastx, self._lasty = None, None
def enter_notify_event(self, guiEvent=None, xy=None):
"""
Backend derived classes should call this function when entering
canvas
Parameters
----------
guiEvent
the native UI event that generated the mpl event
xy : (float, float)
the coordinate location of the pointer when the canvas is
entered
"""
if xy is not None:
x, y = xy
self._lastx, self._lasty = x, y
else:
x = None
y = None
cbook.warn_deprecated(
'3.0', message='enter_notify_event expects a location but '
'your backend did not pass one.')
event = LocationEvent('figure_enter_event', self, x, y, guiEvent)
self.callbacks.process('figure_enter_event', event)
def inaxes(self, xy):
"""
Check if a point is in an axes.
Parameters
----------
xy : tuple or list
(x,y) coordinates.
x position - pixels from left of canvas.
y position - pixels from bottom of canvas.
Returns
-------
axes: topmost axes containing the point, or None if no axes.
"""
axes_list = [a for a in self.figure.get_axes()
if a.patch.contains_point(xy)]
if axes_list:
axes = cbook._topmost_artist(axes_list)
else:
axes = None
return axes
def grab_mouse(self, ax):
"""
Set the child axes which are currently grabbing the mouse events.
Usually called by the widgets themselves.
It is an error to call this if the mouse is already grabbed by
another axes.
"""
if self.mouse_grabber not in (None, ax):
raise RuntimeError("Another Axes already grabs mouse input")
self.mouse_grabber = ax
def release_mouse(self, ax):
"""
Release the mouse grab held by the axes, ax.
Usually called by the widgets.
It is ok to call this even if you ax doesn't have the mouse
grab currently.
"""
if self.mouse_grabber is ax:
self.mouse_grabber = None
def draw(self, *args, **kwargs):
"""Render the :class:`~matplotlib.figure.Figure`."""
def draw_idle(self, *args, **kwargs):
"""
Request a widget redraw once control returns to the GUI event loop.
Even if multiple calls to `draw_idle` occur before control returns
to the GUI event loop, the figure will only be rendered once.
Notes
-----
Backends may choose to override the method and implement their own
strategy to prevent multiple renderings.
"""
if not self._is_idle_drawing:
with self._idle_draw_cntx():
self.draw(*args, **kwargs)
def draw_cursor(self, event):
"""
Draw a cursor in the event.axes if inaxes is not None. Use
native GUI drawing for efficiency if possible
"""
def get_width_height(self):
"""
Return the figure width and height in points or pixels
(depending on the backend), truncated to integers
"""
return int(self.figure.bbox.width), int(self.figure.bbox.height)
@classmethod
def get_supported_filetypes(cls):
"""Return dict of savefig file formats supported by this backend"""
return cls.filetypes
@classmethod
def get_supported_filetypes_grouped(cls):
"""Return a dict of savefig file formats supported by this backend,
where the keys are a file type name, such as 'Joint Photographic
Experts Group', and the values are a list of filename extensions used
for that filetype, such as ['jpg', 'jpeg']."""
groupings = {}
for ext, name in cls.filetypes.items():
groupings.setdefault(name, []).append(ext)
groupings[name].sort()
return groupings
def _get_output_canvas(self, fmt):
"""
Return a canvas suitable for saving figures to a specified file format.
If necessary, this function will switch to a registered backend that
supports the format.
"""
# Return the current canvas if it supports the requested format.
if hasattr(self, 'print_{}'.format(fmt)):
return self
# Return a default canvas for the requested format, if it exists.
canvas_class = get_registered_canvas_class(fmt)
if canvas_class:
return self.switch_backends(canvas_class)
# Else report error for unsupported format.
raise ValueError(
"Format {!r} is not supported (supported formats: {})"
.format(fmt, ", ".join(sorted(self.get_supported_filetypes()))))
def print_figure(self, filename, dpi=None, facecolor=None, edgecolor=None,
orientation='portrait', format=None,
*, bbox_inches=None, **kwargs):
"""
Render the figure to hardcopy. Set the figure patch face and edge
colors. This is useful because some of the GUIs have a gray figure
face color background and you'll probably want to override this on
hardcopy.
Parameters
----------
filename
can also be a file object on image backends
orientation : {'landscape', 'portrait'}, optional
only currently applies to PostScript printing.
dpi : scalar, optional
the dots per inch to save the figure in; if None, use savefig.dpi
facecolor : color or None, optional
the facecolor of the figure; if None, defaults to savefig.facecolor
edgecolor : color or None, optional
the edgecolor of the figure; if None, defaults to savefig.edgecolor
format : str, optional
when set, forcibly set the file format to save to
bbox_inches : str or `~matplotlib.transforms.Bbox`, optional
Bbox in inches. Only the given portion of the figure is
saved. If 'tight', try to figure out the tight bbox of
the figure. If None, use savefig.bbox
pad_inches : scalar, optional
Amount of padding around the figure when bbox_inches is
'tight'. If None, use savefig.pad_inches
bbox_extra_artists : list of `~matplotlib.artist.Artist`, optional
A list of extra artists that will be considered when the
tight bbox is calculated.
"""
if format is None:
# get format from filename, or from backend's default filetype
if isinstance(filename, os.PathLike):
filename = os.fspath(filename)
if isinstance(filename, str):
format = os.path.splitext(filename)[1][1:]
if format is None or format == '':
format = self.get_default_filetype()
if isinstance(filename, str):
filename = filename.rstrip('.') + '.' + format
format = format.lower()
# get canvas object and print method for format
canvas = self._get_output_canvas(format)
print_method = getattr(canvas, 'print_%s' % format)
if dpi is None:
dpi = rcParams['savefig.dpi']
if dpi == 'figure':
dpi = getattr(self.figure, '_original_dpi', self.figure.dpi)
# Remove the figure manager, if any, to avoid resizing the GUI widget.
# Some code (e.g. Figure.show) differentiates between having *no*
# manager and a *None* manager, which should be fixed at some point,
# but this should be fine.
with cbook._setattr_cm(self, _is_saving=True, manager=None), \
cbook._setattr_cm(self.figure, dpi=dpi):
if facecolor is None:
facecolor = rcParams['savefig.facecolor']
if edgecolor is None:
edgecolor = rcParams['savefig.edgecolor']
origfacecolor = self.figure.get_facecolor()
origedgecolor = self.figure.get_edgecolor()
self.figure.set_facecolor(facecolor)
self.figure.set_edgecolor(edgecolor)
if bbox_inches is None:
bbox_inches = rcParams['savefig.bbox']
if bbox_inches:
# call adjust_bbox to save only the given area
if bbox_inches == "tight":
# When bbox_inches == "tight", it saves the figure twice.
# The first save command (to a BytesIO) is just to estimate
# the bounding box of the figure.
result = print_method(
io.BytesIO(),
dpi=dpi,
facecolor=facecolor,
edgecolor=edgecolor,
orientation=orientation,
dryrun=True,
**kwargs)
renderer = self.figure._cachedRenderer
bbox_artists = kwargs.pop("bbox_extra_artists", None)
bbox_inches = self.figure.get_tightbbox(renderer,
bbox_extra_artists=bbox_artists)
pad = kwargs.pop("pad_inches", None)
if pad is None:
pad = rcParams['savefig.pad_inches']
bbox_inches = bbox_inches.padded(pad)
restore_bbox = tight_bbox.adjust_bbox(self.figure, bbox_inches,
canvas.fixed_dpi)
_bbox_inches_restore = (bbox_inches, restore_bbox)
else:
_bbox_inches_restore = None
try:
result = print_method(
filename,
dpi=dpi,
facecolor=facecolor,
edgecolor=edgecolor,
orientation=orientation,
bbox_inches_restore=_bbox_inches_restore,
**kwargs)
finally:
if bbox_inches and restore_bbox:
restore_bbox()
self.figure.set_facecolor(origfacecolor)
self.figure.set_edgecolor(origedgecolor)
self.figure.set_canvas(self)
return result
@classmethod
def get_default_filetype(cls):
"""
Get the default savefig file format as specified in rcParam
``savefig.format``. Returned string excludes period. Overridden
in backends that only support a single file type.
"""
return rcParams['savefig.format']
def get_window_title(self):
"""
Get the title text of the window containing the figure.
Return None if there is no window (e.g., a PS backend).
"""
if hasattr(self, "manager"):
return self.manager.get_window_title()
def set_window_title(self, title):
"""
Set the title text of the window containing the figure. Note that
this has no effect if there is no window (e.g., a PS backend).
"""
if hasattr(self, "manager"):
self.manager.set_window_title(title)
def get_default_filename(self):
"""
Return a string, which includes extension, suitable for use as
a default filename.
"""
default_basename = self.get_window_title() or 'image'
default_basename = default_basename.replace(' ', '_')
default_filetype = self.get_default_filetype()
default_filename = default_basename + '.' + default_filetype
return default_filename
def switch_backends(self, FigureCanvasClass):
"""
Instantiate an instance of FigureCanvasClass
This is used for backend switching, e.g., to instantiate a
FigureCanvasPS from a FigureCanvasGTK. Note, deep copying is
not done, so any changes to one of the instances (e.g., setting
figure size or line props), will be reflected in the other
"""
newCanvas = FigureCanvasClass(self.figure)
newCanvas._is_saving = self._is_saving
return newCanvas
def mpl_connect(self, s, func):
"""
Connect event with string *s* to *func*. The signature of *func* is::
def func(event)
where event is a :class:`matplotlib.backend_bases.Event`. The
following events are recognized
- 'button_press_event'
- 'button_release_event'
- 'draw_event'
- 'key_press_event'
- 'key_release_event'
- 'motion_notify_event'
- 'pick_event'
- 'resize_event'
- 'scroll_event'
- 'figure_enter_event',
- 'figure_leave_event',
- 'axes_enter_event',
- 'axes_leave_event'
- 'close_event'
For the location events (button and key press/release), if the
mouse is over the axes, the variable ``event.inaxes`` will be
set to the :class:`~matplotlib.axes.Axes` the event occurs is
over, and additionally, the variables ``event.xdata`` and
``event.ydata`` will be defined. This is the mouse location
in data coords. See
:class:`~matplotlib.backend_bases.KeyEvent` and
:class:`~matplotlib.backend_bases.MouseEvent` for more info.
Return value is a connection id that can be used with
:meth:`~matplotlib.backend_bases.Event.mpl_disconnect`.
Examples
--------
Usage::
def on_press(event):
print('you pressed', event.button, event.xdata, event.ydata)
cid = canvas.mpl_connect('button_press_event', on_press)
"""
return self.callbacks.connect(s, func)
def mpl_disconnect(self, cid):
"""
Disconnect callback id cid
Examples
--------
Usage::
cid = canvas.mpl_connect('button_press_event', on_press)
#...later
canvas.mpl_disconnect(cid)
"""
return self.callbacks.disconnect(cid)
def new_timer(self, *args, **kwargs):
"""
Creates a new backend-specific subclass of
:class:`backend_bases.Timer`. This is useful for getting periodic
events through the backend's native event loop. Implemented only for
backends with GUIs.
Other Parameters
----------------
interval : scalar
Timer interval in milliseconds
callbacks : List[Tuple[callable, Tuple, Dict]]
Sequence of (func, args, kwargs) where ``func(*args, **kwargs)``
will be executed by the timer every *interval*.
callbacks which return ``False`` or ``0`` will be removed from the
timer.
Examples
--------
>>> timer = fig.canvas.new_timer(callbacks=[(f1, (1, ), {'a': 3}),])
"""
return TimerBase(*args, **kwargs)
def flush_events(self):
"""
Flush the GUI events for the figure.
Interactive backends need to reimplement this method.
"""
def start_event_loop(self, timeout=0):
"""Start a blocking event loop.
Such an event loop is used by interactive functions, such as `ginput`
and `waitforbuttonpress`, to wait for events.
The event loop blocks until a callback function triggers
`stop_event_loop`, or *timeout* is reached.
If *timeout* is negative, never timeout.
Only interactive backends need to reimplement this method and it relies
on `flush_events` being properly implemented.
Interactive backends should implement this in a more native way.
"""
if timeout <= 0:
timeout = np.inf
timestep = 0.01
counter = 0
self._looping = True
while self._looping and counter * timestep < timeout:
self.flush_events()
time.sleep(timestep)
counter += 1
def stop_event_loop(self):
"""Stop the current blocking event loop.
Interactive backends need to reimplement this to match
`start_event_loop`
"""
self._looping = False
def key_press_handler(event, canvas, toolbar=None):
"""
Implement the default mpl key bindings for the canvas and toolbar
described at :ref:`key-event-handling`
Parameters
----------
event : :class:`KeyEvent`
a key press/release event
canvas : :class:`FigureCanvasBase`
the backend-specific canvas instance
toolbar : :class:`NavigationToolbar2`
the navigation cursor toolbar
"""
# these bindings happen whether you are over an axes or not
if event.key is None:
return
# Load key-mappings from rcParams.
fullscreen_keys = rcParams['keymap.fullscreen']
home_keys = rcParams['keymap.home']
back_keys = rcParams['keymap.back']
forward_keys = rcParams['keymap.forward']
pan_keys = rcParams['keymap.pan']
zoom_keys = rcParams['keymap.zoom']
save_keys = rcParams['keymap.save']
quit_keys = rcParams['keymap.quit']
grid_keys = rcParams['keymap.grid']
grid_minor_keys = rcParams['keymap.grid_minor']
toggle_yscale_keys = rcParams['keymap.yscale']
toggle_xscale_keys = rcParams['keymap.xscale']
all_keys = rcParams['keymap.all_axes']
# toggle fullscreen mode ('f', 'ctrl + f')
if event.key in fullscreen_keys:
try:
canvas.manager.full_screen_toggle()
except AttributeError:
pass
# quit the figure (default key 'ctrl+w')
if event.key in quit_keys:
Gcf.destroy_fig(canvas.figure)
if toolbar is not None:
# home or reset mnemonic (default key 'h', 'home' and 'r')
if event.key in home_keys:
toolbar.home()
# forward / backward keys to enable left handed quick navigation
# (default key for backward: 'left', 'backspace' and 'c')
elif event.key in back_keys:
toolbar.back()
# (default key for forward: 'right' and 'v')
elif event.key in forward_keys:
toolbar.forward()
# pan mnemonic (default key 'p')
elif event.key in pan_keys:
toolbar.pan()
toolbar._set_cursor(event)
# zoom mnemonic (default key 'o')
elif event.key in zoom_keys:
toolbar.zoom()
toolbar._set_cursor(event)
# saving current figure (default key 's')
elif event.key in save_keys:
toolbar.save_figure()
if event.inaxes is None:
return
# these bindings require the mouse to be over an axes to trigger
def _get_uniform_gridstate(ticks):
# Return True/False if all grid lines are on or off, None if they are
# not all in the same state.
if all(tick.gridline.get_visible() for tick in ticks):
return True
elif not any(tick.gridline.get_visible() for tick in ticks):
return False
else:
return None
ax = event.inaxes
# toggle major grids in current axes (default key 'g')
# Both here and below (for 'G'), we do nothing if *any* grid (major or
# minor, x or y) is not in a uniform state, to avoid messing up user
# customization.
if (event.key in grid_keys
# Exclude minor grids not in a uniform state.
and None not in [_get_uniform_gridstate(ax.xaxis.minorTicks),
_get_uniform_gridstate(ax.yaxis.minorTicks)]):
x_state = _get_uniform_gridstate(ax.xaxis.majorTicks)
y_state = _get_uniform_gridstate(ax.yaxis.majorTicks)
cycle = [(False, False), (True, False), (True, True), (False, True)]
try:
x_state, y_state = (
cycle[(cycle.index((x_state, y_state)) + 1) % len(cycle)])
except ValueError:
# Exclude major grids not in a uniform state.
pass
else:
# If turning major grids off, also turn minor grids off.
ax.grid(x_state, which="major" if x_state else "both", axis="x")
ax.grid(y_state, which="major" if y_state else "both", axis="y")
canvas.draw_idle()
# toggle major and minor grids in current axes (default key 'G')
if (event.key in grid_minor_keys
# Exclude major grids not in a uniform state.
and None not in [_get_uniform_gridstate(ax.xaxis.majorTicks),
_get_uniform_gridstate(ax.yaxis.majorTicks)]):
x_state = _get_uniform_gridstate(ax.xaxis.minorTicks)
y_state = _get_uniform_gridstate(ax.yaxis.minorTicks)
cycle = [(False, False), (True, False), (True, True), (False, True)]
try:
x_state, y_state = (
cycle[(cycle.index((x_state, y_state)) + 1) % len(cycle)])
except ValueError:
# Exclude minor grids not in a uniform state.
pass
else:
ax.grid(x_state, which="both", axis="x")
ax.grid(y_state, which="both", axis="y")
canvas.draw_idle()
# toggle scaling of y-axes between 'log and 'linear' (default key 'l')
elif event.key in toggle_yscale_keys:
scale = ax.get_yscale()
if scale == 'log':
ax.set_yscale('linear')
ax.figure.canvas.draw_idle()
elif scale == 'linear':
try:
ax.set_yscale('log')
except ValueError as exc:
_log.warning(str(exc))
ax.set_yscale('linear')
ax.figure.canvas.draw_idle()
# toggle scaling of x-axes between 'log and 'linear' (default key 'k')
elif event.key in toggle_xscale_keys:
scalex = ax.get_xscale()
if scalex == 'log':
ax.set_xscale('linear')
ax.figure.canvas.draw_idle()
elif scalex == 'linear':
try:
ax.set_xscale('log')
except ValueError as exc:
_log.warning(str(exc))
ax.set_xscale('linear')
ax.figure.canvas.draw_idle()
# enable nagivation for all axes that contain the event (default key 'a')
elif event.key in all_keys:
for a in canvas.figure.get_axes():
if (event.x is not None and event.y is not None
and a.in_axes(event)): # FIXME: Why only these?
a.set_navigate(True)
# enable navigation only for axes with this index (if such an axes exist,
# otherwise do nothing)
elif event.key.isdigit() and event.key != '0':
n = int(event.key) - 1
if n < len(canvas.figure.get_axes()):
for i, a in enumerate(canvas.figure.get_axes()):
if (event.x is not None and event.y is not None
and a.in_axes(event)): # FIXME: Why only these?
a.set_navigate(i == n)
def button_press_handler(event, canvas, toolbar=None):
"""
The default Matplotlib button actions for extra mouse buttons.
"""
if toolbar is not None:
button_name = str(MouseButton(event.button))
if button_name in rcParams['keymap.back']:
toolbar.back()
elif button_name in rcParams['keymap.forward']:
toolbar.forward()
class NonGuiException(Exception):
pass
class FigureManagerBase(object):
"""
Helper class for pyplot mode, wraps everything up into a neat bundle
Attributes
----------
canvas : :class:`FigureCanvasBase`
The backend-specific canvas instance
num : int or str
The figure number
key_press_handler_id : int
The default key handler cid, when using the toolmanager.
To disable the default key press handling use::
figure.canvas.mpl_disconnect(
figure.canvas.manager.key_press_handler_id)
button_press_handler_id : int
The default mouse button handler cid, when using the toolmanager.
To disable the default button press handling use::
figure.canvas.mpl_disconnect(
figure.canvas.manager.button_press_handler_id)
"""
def __init__(self, canvas, num):
self.canvas = canvas
canvas.manager = self # store a pointer to parent
self.num = num
self.key_press_handler_id = None
self.button_press_handler_id = None
if rcParams['toolbar'] != 'toolmanager':
self.key_press_handler_id = self.canvas.mpl_connect(
'key_press_event',
self.key_press)
self.button_press_handler_id = self.canvas.mpl_connect(
'button_press_event',
self.button_press)
self.toolmanager = None
self.toolbar = None
@self.canvas.figure.add_axobserver
def notify_axes_change(fig):
# Called whenever the current axes is changed.
if self.toolmanager is None and self.toolbar is not None:
self.toolbar.update()
def show(self):
"""
For GUI backends, show the figure window and redraw.
For non-GUI backends, raise an exception to be caught
by :meth:`~matplotlib.figure.Figure.show`, for an
optional warning.
"""
raise NonGuiException()
def destroy(self):
pass
def full_screen_toggle(self):
pass
def resize(self, w, h):
""""For GUI backends, resize the window (in pixels)."""
def key_press(self, event):
"""
Implement the default mpl key bindings defined at
:ref:`key-event-handling`
"""
if rcParams['toolbar'] != 'toolmanager':
key_press_handler(event, self.canvas, self.canvas.toolbar)
def button_press(self, event):
"""
The default Matplotlib button actions for extra mouse buttons.
"""
if rcParams['toolbar'] != 'toolmanager':
button_press_handler(event, self.canvas, self.canvas.toolbar)
def get_window_title(self):
"""Get the title text of the window containing the figure.
Return None for non-GUI (e.g., PS) backends.
"""
return 'image'
def set_window_title(self, title):
"""Set the title text of the window containing the figure.
This has no effect for non-GUI (e.g., PS) backends.
"""
cursors = tools.cursors
class NavigationToolbar2(object):
"""
Base class for the navigation cursor, version 2
backends must implement a canvas that handles connections for
'button_press_event' and 'button_release_event'. See
:meth:`FigureCanvasBase.mpl_connect` for more information
They must also define
:meth:`save_figure`
save the current figure
:meth:`set_cursor`
if you want the pointer icon to change
:meth:`_init_toolbar`
create your toolbar widget
:meth:`draw_rubberband` (optional)
draw the zoom to rect "rubberband" rectangle
:meth:`press` (optional)
whenever a mouse button is pressed, you'll be notified with
the event
:meth:`release` (optional)
whenever a mouse button is released, you'll be notified with
the event
:meth:`set_message` (optional)
display message
:meth:`set_history_buttons` (optional)
you can change the history back / forward buttons to
indicate disabled / enabled state.
That's it, we'll do the rest!
"""
# list of toolitems to add to the toolbar, format is:
# (
# text, # the text of the button (often not visible to users)
# tooltip_text, # the tooltip shown on hover (where possible)
# image_file, # name of the image for the button (without the extension)
# name_of_method, # name of the method in NavigationToolbar2 to call
# )
toolitems = (
('Home', 'Reset original view', 'home', 'home'),
('Back', 'Back to previous view', 'back', 'back'),
('Forward', 'Forward to next view', 'forward', 'forward'),
(None, None, None, None),
('Pan', 'Pan axes with left mouse, zoom with right', 'move', 'pan'),
('Zoom', 'Zoom to rectangle', 'zoom_to_rect', 'zoom'),
('Subplots', 'Configure subplots', 'subplots', 'configure_subplots'),
(None, None, None, None),
('Save', 'Save the figure', 'filesave', 'save_figure'),
)
def __init__(self, canvas):
self.canvas = canvas
canvas.toolbar = self
self._nav_stack = cbook.Stack()
self._xypress = None # the location and axis info at the time
# of the press
self._idPress = None
self._idRelease = None
self._active = None
# This cursor will be set after the initial draw.
self._lastCursor = cursors.POINTER
self._init_toolbar()
self._idDrag = self.canvas.mpl_connect(
'motion_notify_event', self.mouse_move)
self._ids_zoom = []
self._zoom_mode = None
self._button_pressed = None # determined by the button pressed
# at start
self.mode = '' # a mode string for the status bar
self.set_history_buttons()
def set_message(self, s):
"""Display a message on toolbar or in status bar."""
def back(self, *args):
"""move back up the view lim stack"""
self._nav_stack.back()
self.set_history_buttons()
self._update_view()
def draw_rubberband(self, event, x0, y0, x1, y1):
"""Draw a rectangle rubberband to indicate zoom limits.
Note that it is not guaranteed that ``x0 <= x1`` and ``y0 <= y1``.
"""
def remove_rubberband(self):
"""Remove the rubberband."""
def forward(self, *args):
"""Move forward in the view lim stack."""
self._nav_stack.forward()
self.set_history_buttons()
self._update_view()
def home(self, *args):
"""Restore the original view."""
self._nav_stack.home()
self.set_history_buttons()
self._update_view()
def _init_toolbar(self):
"""
This is where you actually build the GUI widgets (called by
__init__). The icons ``home.xpm``, ``back.xpm``, ``forward.xpm``,
``hand.xpm``, ``zoom_to_rect.xpm`` and ``filesave.xpm`` are standard
across backends (there are ppm versions in CVS also).
You just need to set the callbacks
home : self.home
back : self.back
forward : self.forward
hand : self.pan
zoom_to_rect : self.zoom
filesave : self.save_figure
You only need to define the last one - the others are in the base
class implementation.
"""
raise NotImplementedError
def _set_cursor(self, event):
if not event.inaxes or not self._active:
if self._lastCursor != cursors.POINTER:
self.set_cursor(cursors.POINTER)
self._lastCursor = cursors.POINTER
else:
if (self._active == 'ZOOM'
and self._lastCursor != cursors.SELECT_REGION):
self.set_cursor(cursors.SELECT_REGION)
self._lastCursor = cursors.SELECT_REGION
elif (self._active == 'PAN' and
self._lastCursor != cursors.MOVE):
self.set_cursor(cursors.MOVE)
self._lastCursor = cursors.MOVE
def mouse_move(self, event):
self._set_cursor(event)
if event.inaxes and event.inaxes.get_navigate():
try:
s = event.inaxes.format_coord(event.xdata, event.ydata)
except (ValueError, OverflowError):
pass
else:
artists = [a for a in event.inaxes._mouseover_set
if a.contains(event)[0] and a.get_visible()]
if artists:
a = cbook._topmost_artist(artists)
if a is not event.inaxes.patch:
data = a.get_cursor_data(event)
if data is not None:
data_str = a.format_cursor_data(data)
if data_str is not None:
s = s + ' ' + data_str
if len(self.mode):
self.set_message('%s, %s' % (self.mode, s))
else:
self.set_message(s)
else:
self.set_message(self.mode)
def pan(self, *args):
"""Activate the pan/zoom tool. pan with left button, zoom with right"""
# set the pointer icon and button press funcs to the
# appropriate callbacks
if self._active == 'PAN':
self._active = None
else:
self._active = 'PAN'
if self._idPress is not None:
self._idPress = self.canvas.mpl_disconnect(self._idPress)
self.mode = ''
if self._idRelease is not None:
self._idRelease = self.canvas.mpl_disconnect(self._idRelease)
self.mode = ''
if self._active:
self._idPress = self.canvas.mpl_connect(
'button_press_event', self.press_pan)
self._idRelease = self.canvas.mpl_connect(
'button_release_event', self.release_pan)
self.mode = 'pan/zoom'
self.canvas.widgetlock(self)
else:
self.canvas.widgetlock.release(self)
for a in self.canvas.figure.get_axes():
a.set_navigate_mode(self._active)
self.set_message(self.mode)
def press(self, event):
"""Called whenever a mouse button is pressed."""
def press_pan(self, event):
"""Callback for mouse button press in pan/zoom mode."""
if event.button == 1:
self._button_pressed = 1
elif event.button == 3:
self._button_pressed = 3
else:
self._button_pressed = None
return
if self._nav_stack() is None:
# set the home button to this view
self.push_current()
x, y = event.x, event.y
self._xypress = []
for i, a in enumerate(self.canvas.figure.get_axes()):
if (x is not None and y is not None and a.in_axes(event) and
a.get_navigate() and a.can_pan()):
a.start_pan(x, y, event.button)
self._xypress.append((a, i))
self.canvas.mpl_disconnect(self._idDrag)
self._idDrag = self.canvas.mpl_connect('motion_notify_event',
self.drag_pan)
self.press(event)
def press_zoom(self, event):
"""Callback for mouse button press in zoom to rect mode."""
# If we're already in the middle of a zoom, pressing another
# button works to "cancel"
if self._ids_zoom != []:
for zoom_id in self._ids_zoom:
self.canvas.mpl_disconnect(zoom_id)
self.release(event)
self.draw()
self._xypress = None
self._button_pressed = None
self._ids_zoom = []
return
if event.button == 1:
self._button_pressed = 1
elif event.button == 3:
self._button_pressed = 3
else:
self._button_pressed = None
return
if self._nav_stack() is None:
# set the home button to this view
self.push_current()
x, y = event.x, event.y
self._xypress = []
for i, a in enumerate(self.canvas.figure.get_axes()):
if (x is not None and y is not None and a.in_axes(event) and
a.get_navigate() and a.can_zoom()):
self._xypress.append((x, y, a, i, a._get_view()))
id1 = self.canvas.mpl_connect('motion_notify_event', self.drag_zoom)
id2 = self.canvas.mpl_connect('key_press_event',
self._switch_on_zoom_mode)
id3 = self.canvas.mpl_connect('key_release_event',
self._switch_off_zoom_mode)
self._ids_zoom = id1, id2, id3
self._zoom_mode = event.key
self.press(event)
def _switch_on_zoom_mode(self, event):
self._zoom_mode = event.key
self.mouse_move(event)
def _switch_off_zoom_mode(self, event):
self._zoom_mode = None
self.mouse_move(event)
def push_current(self):
"""Push the current view limits and position onto the stack."""
self._nav_stack.push(
WeakKeyDictionary(
{ax: (ax._get_view(),
# Store both the original and modified positions.
(ax.get_position(True).frozen(),
ax.get_position().frozen()))
for ax in self.canvas.figure.axes}))
self.set_history_buttons()
def release(self, event):
"""Callback for mouse button release."""
def release_pan(self, event):
"""Callback for mouse button release in pan/zoom mode."""
if self._button_pressed is None:
return
self.canvas.mpl_disconnect(self._idDrag)
self._idDrag = self.canvas.mpl_connect(
'motion_notify_event', self.mouse_move)
for a, ind in self._xypress:
a.end_pan()
if not self._xypress:
return
self._xypress = []
self._button_pressed = None
self.push_current()
self.release(event)
self.draw()
def drag_pan(self, event):
"""Callback for dragging in pan/zoom mode."""
for a, ind in self._xypress:
#safer to use the recorded button at the press than current button:
#multiple button can get pressed during motion...
a.drag_pan(self._button_pressed, event.key, event.x, event.y)
self.canvas.draw_idle()
def drag_zoom(self, event):
"""Callback for dragging in zoom mode."""
if self._xypress:
x, y = event.x, event.y
lastx, lasty, a, ind, view = self._xypress[0]
(x1, y1), (x2, y2) = np.clip(
[[lastx, lasty], [x, y]], a.bbox.min, a.bbox.max)
if self._zoom_mode == "x":
y1, y2 = a.bbox.intervaly
elif self._zoom_mode == "y":
x1, x2 = a.bbox.intervalx
self.draw_rubberband(event, x1, y1, x2, y2)
def release_zoom(self, event):
"""Callback for mouse button release in zoom to rect mode."""
for zoom_id in self._ids_zoom:
self.canvas.mpl_disconnect(zoom_id)
self._ids_zoom = []
self.remove_rubberband()
if not self._xypress:
return
last_a = []
for cur_xypress in self._xypress:
x, y = event.x, event.y
lastx, lasty, a, ind, view = cur_xypress
# ignore singular clicks - 5 pixels is a threshold
# allows the user to "cancel" a zoom action
# by zooming by less than 5 pixels
if ((abs(x - lastx) < 5 and self._zoom_mode != "y") or
(abs(y - lasty) < 5 and self._zoom_mode != "x")):
self._xypress = None
self.release(event)
self.draw()
return
# detect twinx,y axes and avoid double zooming
twinx, twiny = False, False
if last_a:
for la in last_a:
if a.get_shared_x_axes().joined(a, la):
twinx = True
if a.get_shared_y_axes().joined(a, la):
twiny = True
last_a.append(a)
if self._button_pressed == 1:
direction = 'in'
elif self._button_pressed == 3:
direction = 'out'
else:
continue
a._set_view_from_bbox((lastx, lasty, x, y), direction,
self._zoom_mode, twinx, twiny)
self.draw()
self._xypress = None
self._button_pressed = None
self._zoom_mode = None
self.push_current()
self.release(event)
def draw(self):
"""Redraw the canvases, update the locators."""
for a in self.canvas.figure.get_axes():
xaxis = getattr(a, 'xaxis', None)
yaxis = getattr(a, 'yaxis', None)
locators = []
if xaxis is not None:
locators.append(xaxis.get_major_locator())
locators.append(xaxis.get_minor_locator())
if yaxis is not None:
locators.append(yaxis.get_major_locator())
locators.append(yaxis.get_minor_locator())
for loc in locators:
loc.refresh()
self.canvas.draw_idle()
def _update_view(self):
"""Update the viewlim and position from the view and
position stack for each axes.
"""
nav_info = self._nav_stack()
if nav_info is None:
return
# Retrieve all items at once to avoid any risk of GC deleting an Axes
# while in the middle of the loop below.
items = list(nav_info.items())
for ax, (view, (pos_orig, pos_active)) in items:
ax._set_view(view)
# Restore both the original and modified positions
ax._set_position(pos_orig, 'original')
ax._set_position(pos_active, 'active')
self.canvas.draw_idle()
def save_figure(self, *args):
"""Save the current figure."""
raise NotImplementedError
def set_cursor(self, cursor):
"""Set the current cursor to one of the :class:`Cursors` enums values.
If required by the backend, this method should trigger an update in
the backend event loop after the cursor is set, as this method may be
called e.g. before a long-running task during which the GUI is not
updated.
"""
def update(self):
"""Reset the axes stack."""
self._nav_stack.clear()
self.set_history_buttons()
def zoom(self, *args):
"""Activate zoom to rect mode."""
if self._active == 'ZOOM':
self._active = None
else:
self._active = 'ZOOM'
if self._idPress is not None:
self._idPress = self.canvas.mpl_disconnect(self._idPress)
self.mode = ''
if self._idRelease is not None:
self._idRelease = self.canvas.mpl_disconnect(self._idRelease)
self.mode = ''
if self._active:
self._idPress = self.canvas.mpl_connect('button_press_event',
self.press_zoom)
self._idRelease = self.canvas.mpl_connect('button_release_event',
self.release_zoom)
self.mode = 'zoom rect'
self.canvas.widgetlock(self)
else:
self.canvas.widgetlock.release(self)
for a in self.canvas.figure.get_axes():
a.set_navigate_mode(self._active)
self.set_message(self.mode)
def set_history_buttons(self):
"""Enable or disable the back/forward button."""
class ToolContainerBase(object):
"""
Base class for all tool containers, e.g. toolbars.
Attributes
----------
toolmanager : `ToolManager`
The tools with which this `ToolContainer` wants to communicate.
"""
_icon_extension = '.png'
"""
Toolcontainer button icon image format extension
**String**: Image extension
"""
def __init__(self, toolmanager):
self.toolmanager = toolmanager
self.toolmanager.toolmanager_connect('tool_removed_event',
self._remove_tool_cbk)
def _tool_toggled_cbk(self, event):
"""
Captures the 'tool_trigger_[name]'
This only gets used for toggled tools
"""
self.toggle_toolitem(event.tool.name, event.tool.toggled)
def add_tool(self, tool, group, position=-1):
"""
Adds a tool to this container
Parameters
----------
tool : tool_like
The tool to add, see `ToolManager.get_tool`.
group : str
The name of the group to add this tool to.
position : int (optional)
The position within the group to place this tool. Defaults to end.
"""
tool = self.toolmanager.get_tool(tool)
image = self._get_image_filename(tool.image)
toggle = getattr(tool, 'toggled', None) is not None
self.add_toolitem(tool.name, group, position,
image, tool.description, toggle)
if toggle:
self.toolmanager.toolmanager_connect('tool_trigger_%s' % tool.name,
self._tool_toggled_cbk)
# If initially toggled
if tool.toggled:
self.toggle_toolitem(tool.name, True)
def _remove_tool_cbk(self, event):
"""Captures the 'tool_removed_event' signal and removes the tool."""
self.remove_toolitem(event.tool.name)
def _get_image_filename(self, image):
"""Find the image based on its name."""
if not image:
return None
basedir = os.path.join(rcParams['datapath'], 'images')
possible_images = (
image,
image + self._icon_extension,
os.path.join(basedir, image),
os.path.join(basedir, image) + self._icon_extension)
for fname in possible_images:
if os.path.isfile(fname):
return fname
def trigger_tool(self, name):
"""
Trigger the tool
Parameters
----------
name : string
Name (id) of the tool triggered from within the container
"""
self.toolmanager.trigger_tool(name, sender=self)
def add_toolitem(self, name, group, position, image, description, toggle):
"""
Add a toolitem to the container
This method must get implemented per backend
The callback associated with the button click event,
must be **EXACTLY** `self.trigger_tool(name)`
Parameters
----------
name : string
Name of the tool to add, this gets used as the tool's ID and as the
default label of the buttons
group : String
Name of the group that this tool belongs to
position : Int
Position of the tool within its group, if -1 it goes at the End
image_file : String
Filename of the image for the button or `None`
description : String
Description of the tool, used for the tooltips
toggle : Bool
* `True` : The button is a toggle (change the pressed/unpressed
state between consecutive clicks)
* `False` : The button is a normal button (returns to unpressed
state after release)
"""
raise NotImplementedError
def toggle_toolitem(self, name, toggled):
"""
Toggle the toolitem without firing event
Parameters
----------
name : String
Id of the tool to toggle
toggled : bool
Whether to set this tool as toggled or not.
"""
raise NotImplementedError
def remove_toolitem(self, name):
"""
Remove a toolitem from the `ToolContainer`
This method must get implemented per backend
Called when `ToolManager` emits a `tool_removed_event`
Parameters
----------
name : string
Name of the tool to remove
"""
raise NotImplementedError
class StatusbarBase(object):
"""Base class for the statusbar"""
def __init__(self, toolmanager):
self.toolmanager = toolmanager
self.toolmanager.toolmanager_connect('tool_message_event',
self._message_cbk)
def _message_cbk(self, event):
"""Captures the 'tool_message_event' and set the message"""
self.set_message(event.message)
def set_message(self, s):
"""
Display a message on toolbar or in status bar
Parameters
----------
s : str
Message text
"""
pass
class _Backend(object):
# A backend can be defined by using the following pattern:
#
# @_Backend.export
# class FooBackend(_Backend):
# # override the attributes and methods documented below.
# Set to one of {"qt5", "qt4", "gtk3", "wx", "tk", "macosx"} if an
# interactive framework is required, or None otherwise.
required_interactive_framework = None
# `backend_version` may be overridden by the subclass.
backend_version = "unknown"
# The `FigureCanvas` class must be defined.
FigureCanvas = None
# For interactive backends, the `FigureManager` class must be overridden.
FigureManager = FigureManagerBase
# The following methods must be left as None for non-interactive backends.
# For interactive backends, `trigger_manager_draw` should be a function
# taking a manager as argument and triggering a canvas draw, and `mainloop`
# should be a function taking no argument and starting the backend main
# loop.
trigger_manager_draw = None
mainloop = None
# The following methods will be automatically defined and exported, but
# can be overridden.
@classmethod
def new_figure_manager(cls, num, *args, **kwargs):
"""Create a new figure manager instance.
"""
# This import needs to happen here due to circular imports.
from matplotlib.figure import Figure
fig_cls = kwargs.pop('FigureClass', Figure)
fig = fig_cls(*args, **kwargs)
return cls.new_figure_manager_given_figure(num, fig)
@classmethod
def new_figure_manager_given_figure(cls, num, figure):
"""Create a new figure manager instance for the given figure.
"""
canvas = cls.FigureCanvas(figure)
manager = cls.FigureManager(canvas, num)
return manager
@classmethod
def draw_if_interactive(cls):
if cls.trigger_manager_draw is not None and is_interactive():
manager = Gcf.get_active()
if manager:
cls.trigger_manager_draw(manager)
@classmethod
@cbook._make_keyword_only("3.1", "block")
def show(cls, block=None):
"""
Show all figures.
`show` blocks by calling `mainloop` if *block* is ``True``, or if it
is ``None`` and we are neither in IPython's ``%pylab`` mode, nor in
`interactive` mode.
"""
managers = Gcf.get_all_fig_managers()
if not managers:
return
for manager in managers:
# Emits a warning if the backend is non-interactive.
manager.canvas.figure.show()
if cls.mainloop is None:
return
if block is None:
# Hack: Are we in IPython's pylab mode?
from matplotlib import pyplot
try:
# IPython versions >= 0.10 tack the _needmain attribute onto
# pyplot.show, and always set it to False, when in %pylab mode.
ipython_pylab = not pyplot.show._needmain
except AttributeError:
ipython_pylab = False
block = not ipython_pylab and not is_interactive()
# TODO: The above is a hack to get the WebAgg backend working with
# ipython's `%pylab` mode until proper integration is implemented.
if get_backend() == "WebAgg":
block = True
if block:
cls.mainloop()
# This method is the one actually exporting the required methods.
@staticmethod
def export(cls):
for name in ["required_interactive_framework",
"backend_version",
"FigureCanvas",
"FigureManager",
"new_figure_manager",
"new_figure_manager_given_figure",
"draw_if_interactive",
"show"]:
setattr(sys.modules[cls.__module__], name, getattr(cls, name))
# For back-compatibility, generate a shim `Show` class.
class Show(ShowBase):
def mainloop(self):
return cls.mainloop()
setattr(sys.modules[cls.__module__], "Show", Show)
return cls
class ShowBase(_Backend):
"""
Simple base class to generate a show() callable in backends.
Subclass must override mainloop() method.
"""
def __call__(self, block=None):
return self.show(block=block)
|
6816a4f9ee552a96691ff2f262a354c805f8be0462b19ab8b1f784715e39fa3e
|
"""
This module contains a class representing a Type 1 font.
This version reads pfa and pfb files and splits them for embedding in
pdf files. It also supports SlantFont and ExtendFont transformations,
similarly to pdfTeX and friends. There is no support yet for
subsetting.
Usage::
>>> font = Type1Font(filename)
>>> clear_part, encrypted_part, finale = font.parts
>>> slanted_font = font.transform({'slant': 0.167})
>>> extended_font = font.transform({'extend': 1.2})
Sources:
* Adobe Technical Note #5040, Supporting Downloadable PostScript
Language Fonts.
* Adobe Type 1 Font Format, Adobe Systems Incorporated, third printing,
v1.1, 1993. ISBN 0-201-57044-0.
"""
import binascii
import enum
import itertools
import re
import struct
import numpy as np
# token types
_TokenType = enum.Enum('_TokenType',
'whitespace name string delimiter number')
class Type1Font(object):
"""
A class representing a Type-1 font, for use by backends.
Attributes
----------
parts : tuple
A 3-tuple of the cleartext part, the encrypted part, and the finale of
zeros.
prop : Dict[str, Any]
A dictionary of font properties.
"""
__slots__ = ('parts', 'prop')
def __init__(self, input):
"""
Initialize a Type-1 font. *input* can be either the file name of
a pfb file or a 3-tuple of already-decoded Type-1 font parts.
"""
if isinstance(input, tuple) and len(input) == 3:
self.parts = input
else:
with open(input, 'rb') as file:
data = self._read(file)
self.parts = self._split(data)
self._parse()
def _read(self, file):
"""
Read the font from a file, decoding into usable parts.
"""
rawdata = file.read()
if not rawdata.startswith(b'\x80'):
return rawdata
data = b''
while rawdata:
if not rawdata.startswith(b'\x80'):
raise RuntimeError('Broken pfb file (expected byte 128, '
'got %d)' % rawdata[0])
type = rawdata[1]
if type in (1, 2):
length, = struct.unpack('<i', rawdata[2:6])
segment = rawdata[6:6 + length]
rawdata = rawdata[6 + length:]
if type == 1: # ASCII text: include verbatim
data += segment
elif type == 2: # binary data: encode in hexadecimal
data += binascii.hexlify(segment)
elif type == 3: # end of file
break
else:
raise RuntimeError('Unknown segment type %d in pfb file' %
type)
return data
def _split(self, data):
"""
Split the Type 1 font into its three main parts.
The three parts are: (1) the cleartext part, which ends in a
eexec operator; (2) the encrypted part; (3) the fixed part,
which contains 512 ASCII zeros possibly divided on various
lines, a cleartomark operator, and possibly something else.
"""
# Cleartext part: just find the eexec and skip whitespace
idx = data.index(b'eexec')
idx += len(b'eexec')
while data[idx] in b' \t\r\n':
idx += 1
len1 = idx
# Encrypted part: find the cleartomark operator and count
# zeros backward
idx = data.rindex(b'cleartomark') - 1
zeros = 512
while zeros and data[idx] in b'0' or data[idx] in b'\r\n':
if data[idx] in b'0':
zeros -= 1
idx -= 1
if zeros:
raise RuntimeError('Insufficiently many zeros in Type 1 font')
# Convert encrypted part to binary (if we read a pfb file, we may end
# up converting binary to hexadecimal to binary again; but if we read
# a pfa file, this part is already in hex, and I am not quite sure if
# even the pfb format guarantees that it will be in binary).
binary = binascii.unhexlify(data[len1:idx+1])
return data[:len1], binary, data[idx+1:]
_whitespace_re = re.compile(br'[\0\t\r\014\n ]+')
_token_re = re.compile(br'/{0,2}[^]\0\t\r\v\n ()<>{}/%[]+')
_comment_re = re.compile(br'%[^\r\n\v]*')
_instring_re = re.compile(br'[()\\]')
@classmethod
def _tokens(cls, text):
"""
A PostScript tokenizer. Yield (token, value) pairs such as
(_TokenType.whitespace, ' ') or (_TokenType.name, '/Foobar').
"""
pos = 0
while pos < len(text):
match = (cls._comment_re.match(text[pos:]) or
cls._whitespace_re.match(text[pos:]))
if match:
yield (_TokenType.whitespace, match.group())
pos += match.end()
elif text[pos] == b'(':
start = pos
pos += 1
depth = 1
while depth:
match = cls._instring_re.search(text[pos:])
if match is None:
return
pos += match.end()
if match.group() == b'(':
depth += 1
elif match.group() == b')':
depth -= 1
else: # a backslash - skip the next character
pos += 1
yield (_TokenType.string, text[start:pos])
elif text[pos:pos + 2] in (b'<<', b'>>'):
yield (_TokenType.delimiter, text[pos:pos + 2])
pos += 2
elif text[pos] == b'<':
start = pos
pos += text[pos:].index(b'>')
yield (_TokenType.string, text[start:pos])
else:
match = cls._token_re.match(text[pos:])
if match:
try:
float(match.group())
yield (_TokenType.number, match.group())
except ValueError:
yield (_TokenType.name, match.group())
pos += match.end()
else:
yield (_TokenType.delimiter, text[pos:pos + 1])
pos += 1
def _parse(self):
"""
Find the values of various font properties. This limited kind
of parsing is described in Chapter 10 "Adobe Type Manager
Compatibility" of the Type-1 spec.
"""
# Start with reasonable defaults
prop = {'weight': 'Regular', 'ItalicAngle': 0.0, 'isFixedPitch': False,
'UnderlinePosition': -100, 'UnderlineThickness': 50}
filtered = ((token, value)
for token, value in self._tokens(self.parts[0])
if token is not _TokenType.whitespace)
# The spec calls this an ASCII format; in Python 2.x we could
# just treat the strings and names as opaque bytes but let's
# turn them into proper Unicode, and be lenient in case of high bytes.
convert = lambda x: x.decode('ascii', 'replace')
for token, value in filtered:
if token is _TokenType.name and value.startswith(b'/'):
key = convert(value[1:])
token, value = next(filtered)
if token is _TokenType.name:
if value in (b'true', b'false'):
value = value == b'true'
else:
value = convert(value.lstrip(b'/'))
elif token is _TokenType.string:
value = convert(value.lstrip(b'(').rstrip(b')'))
elif token is _TokenType.number:
if b'.' in value:
value = float(value)
else:
value = int(value)
else: # more complicated value such as an array
value = None
if key != 'FontInfo' and value is not None:
prop[key] = value
# Fill in the various *Name properties
if 'FontName' not in prop:
prop['FontName'] = (prop.get('FullName') or
prop.get('FamilyName') or
'Unknown')
if 'FullName' not in prop:
prop['FullName'] = prop['FontName']
if 'FamilyName' not in prop:
extras = ('(?i)([ -](regular|plain|italic|oblique|(semi)?bold|'
'(ultra)?light|extra|condensed))+$')
prop['FamilyName'] = re.sub(extras, '', prop['FullName'])
self.prop = prop
@classmethod
def _transformer(cls, tokens, slant, extend):
def fontname(name):
result = name
if slant:
result += b'_Slant_%d' % int(1000 * slant)
if extend != 1.0:
result += b'_Extend_%d' % int(1000 * extend)
return result
def italicangle(angle):
return b'%a' % (float(angle) - np.arctan(slant) / np.pi * 180)
def fontmatrix(array):
array = array.lstrip(b'[').rstrip(b']').split()
array = [float(x) for x in array]
oldmatrix = np.eye(3, 3)
oldmatrix[0:3, 0] = array[::2]
oldmatrix[0:3, 1] = array[1::2]
modifier = np.array([[extend, 0, 0],
[slant, 1, 0],
[0, 0, 1]])
newmatrix = np.dot(modifier, oldmatrix)
array[::2] = newmatrix[0:3, 0]
array[1::2] = newmatrix[0:3, 1]
# Not directly using `b'%a' % x for x in array` for now as that
# produces longer reprs on numpy<1.14, causing test failures.
as_string = '[' + ' '.join(str(x) for x in array) + ']'
return as_string.encode('latin-1')
def replace(fun):
def replacer(tokens):
token, value = next(tokens) # name, e.g., /FontMatrix
yield value
token, value = next(tokens) # possible whitespace
while token is _TokenType.whitespace:
yield value
token, value = next(tokens)
if value != b'[': # name/number/etc.
yield fun(value)
else: # array, e.g., [1 2 3]
result = b''
while value != b']':
result += value
token, value = next(tokens)
result += value
yield fun(result)
return replacer
def suppress(tokens):
for x in itertools.takewhile(lambda x: x[1] != b'def', tokens):
pass
yield b''
table = {b'/FontName': replace(fontname),
b'/ItalicAngle': replace(italicangle),
b'/FontMatrix': replace(fontmatrix),
b'/UniqueID': suppress}
for token, value in tokens:
if token is _TokenType.name and value in table:
yield from table[value](
itertools.chain([(token, value)], tokens))
else:
yield value
def transform(self, effects):
"""
Transform the font by slanting or extending. *effects* should
be a dict where ``effects['slant']`` is the tangent of the
angle that the font is to be slanted to the right (so negative
values slant to the left) and ``effects['extend']`` is the
multiplier by which the font is to be extended (so values less
than 1.0 condense). Returns a new :class:`Type1Font` object.
"""
tokenizer = self._tokens(self.parts[0])
transformed = self._transformer(tokenizer,
slant=effects.get('slant', 0.0),
extend=effects.get('extend', 1.0))
return Type1Font((b"".join(transformed), self.parts[1], self.parts[2]))
|
3d70fcdd2f3af5799320c654014ee4d08e9f143ff60398301610ddb90f7b3ae3
|
"""
Support for plotting vector fields.
Presently this contains Quiver and Barb. Quiver plots an arrow in the
direction of the vector, with the size of the arrow related to the
magnitude of the vector.
Barbs are like quiver in that they point along a vector, but
the magnitude of the vector is given schematically by the presence of barbs
or flags on the barb.
This will also become a home for things such as standard
deviation ellipses, which can and will be derived very easily from
the Quiver code.
"""
import math
import weakref
import numpy as np
from numpy import ma
from matplotlib import cbook, docstring, font_manager
import matplotlib.artist as martist
import matplotlib.collections as mcollections
from matplotlib.patches import CirclePolygon
import matplotlib.text as mtext
import matplotlib.transforms as transforms
_quiver_doc = """
Plot a 2-D field of arrows.
Call signatures::
quiver(U, V, **kw)
quiver(U, V, C, **kw)
quiver(X, Y, U, V, **kw)
quiver(X, Y, U, V, C, **kw)
*U* and *V* are the arrow data, *X* and *Y* set the location of the
arrows, and *C* sets the color of the arrows. These arguments may be 1-D or
2-D arrays or sequences.
If *X* and *Y* are absent, they will be generated as a uniform grid.
If *U* and *V* are 2-D arrays and *X* and *Y* are 1-D, and if ``len(X)`` and
``len(Y)`` match the column and row dimensions of *U*, then *X* and *Y* will be
expanded with :func:`numpy.meshgrid`.
The default settings auto-scales the length of the arrows to a reasonable size.
To change this behavior see the *scale* and *scale_units* kwargs.
The defaults give a slightly swept-back arrow; to make the head a
triangle, make *headaxislength* the same as *headlength*. To make the
arrow more pointed, reduce *headwidth* or increase *headlength* and
*headaxislength*. To make the head smaller relative to the shaft,
scale down all the head parameters. You will probably do best to leave
minshaft alone.
*linewidths* and *edgecolors* can be used to customize the arrow
outlines.
Parameters
----------
X : 1D or 2D array, sequence, optional
The x coordinates of the arrow locations
Y : 1D or 2D array, sequence, optional
The y coordinates of the arrow locations
U : 1D or 2D array or masked array, sequence
The x components of the arrow vectors
V : 1D or 2D array or masked array, sequence
The y components of the arrow vectors
C : 1D or 2D array, sequence, optional
The arrow colors
units : [ 'width' | 'height' | 'dots' | 'inches' | 'x' | 'y' | 'xy' ]
The arrow dimensions (except for *length*) are measured in multiples of
this unit.
'width' or 'height': the width or height of the axis
'dots' or 'inches': pixels or inches, based on the figure dpi
'x', 'y', or 'xy': respectively *X*, *Y*, or :math:`\\sqrt{X^2 + Y^2}`
in data units
The arrows scale differently depending on the units. For
'x' or 'y', the arrows get larger as one zooms in; for other
units, the arrow size is independent of the zoom state. For
'width or 'height', the arrow size increases with the width and
height of the axes, respectively, when the window is resized;
for 'dots' or 'inches', resizing does not change the arrows.
angles : [ 'uv' | 'xy' ], array, optional
Method for determining the angle of the arrows. Default is 'uv'.
'uv': the arrow axis aspect ratio is 1 so that
if *U*==*V* the orientation of the arrow on the plot is 45 degrees
counter-clockwise from the horizontal axis (positive to the right).
'xy': arrows point from (x,y) to (x+u, y+v).
Use this for plotting a gradient field, for example.
Alternatively, arbitrary angles may be specified as an array
of values in degrees, counter-clockwise from the horizontal axis.
Note: inverting a data axis will correspondingly invert the
arrows only with ``angles='xy'``.
scale : None, float, optional
Number of data units per arrow length unit, e.g., m/s per plot width; a
smaller scale parameter makes the arrow longer. Default is *None*.
If *None*, a simple autoscaling algorithm is used, based on the average
vector length and the number of vectors. The arrow length unit is given by
the *scale_units* parameter
scale_units : [ 'width' | 'height' | 'dots' | 'inches' | 'x' | 'y' | 'xy' ], \
None, optional
If the *scale* kwarg is *None*, the arrow length unit. Default is *None*.
e.g. *scale_units* is 'inches', *scale* is 2.0, and
``(u,v) = (1,0)``, then the vector will be 0.5 inches long.
If *scale_units* is 'width'/'height', then the vector will be half the
width/height of the axes.
If *scale_units* is 'x' then the vector will be 0.5 x-axis
units. To plot vectors in the x-y plane, with u and v having
the same units as x and y, use
``angles='xy', scale_units='xy', scale=1``.
width : scalar, optional
Shaft width in arrow units; default depends on choice of units,
above, and number of vectors; a typical starting value is about
0.005 times the width of the plot.
headwidth : scalar, optional
Head width as multiple of shaft width, default is 3
headlength : scalar, optional
Head length as multiple of shaft width, default is 5
headaxislength : scalar, optional
Head length at shaft intersection, default is 4.5
minshaft : scalar, optional
Length below which arrow scales, in units of head length. Do not
set this to less than 1, or small arrows will look terrible!
Default is 1
minlength : scalar, optional
Minimum length as a multiple of shaft width; if an arrow length
is less than this, plot a dot (hexagon) of this diameter instead.
Default is 1.
pivot : [ 'tail' | 'mid' | 'middle' | 'tip' ], optional
The part of the arrow that is at the grid point; the arrow rotates
about this point, hence the name *pivot*.
color : [ color | color sequence ], optional
This is a synonym for the
:class:`~matplotlib.collections.PolyCollection` facecolor kwarg.
If *C* has been set, *color* has no effect.
Notes
-----
Additional :class:`~matplotlib.collections.PolyCollection`
keyword arguments:
%(PolyCollection)s
See Also
--------
quiverkey : Add a key to a quiver plot
""" % docstring.interpd.params
_quiverkey_doc = """
Add a key to a quiver plot.
Call signature::
quiverkey(Q, X, Y, U, label, **kw)
Arguments:
*Q*:
The Quiver instance returned by a call to quiver.
*X*, *Y*:
The location of the key; additional explanation follows.
*U*:
The length of the key
*label*:
A string with the length and units of the key
Keyword arguments:
*angle* = 0
The angle of the key arrow. Measured in degrees anti-clockwise from the
x-axis.
*coordinates* = [ 'axes' | 'figure' | 'data' | 'inches' ]
Coordinate system and units for *X*, *Y*: 'axes' and 'figure' are
normalized coordinate systems with 0,0 in the lower left and 1,1
in the upper right; 'data' are the axes data coordinates (used for
the locations of the vectors in the quiver plot itself); 'inches'
is position in the figure in inches, with 0,0 at the lower left
corner.
*color*:
overrides face and edge colors from *Q*.
*labelpos* = [ 'N' | 'S' | 'E' | 'W' ]
Position the label above, below, to the right, to the left of the
arrow, respectively.
*labelsep*:
Distance in inches between the arrow and the label. Default is
0.1
*labelcolor*:
defaults to default :class:`~matplotlib.text.Text` color.
*fontproperties*:
A dictionary with keyword arguments accepted by the
:class:`~matplotlib.font_manager.FontProperties` initializer:
*family*, *style*, *variant*, *size*, *weight*
Any additional keyword arguments are used to override vector
properties taken from *Q*.
The positioning of the key depends on *X*, *Y*, *coordinates*, and
*labelpos*. If *labelpos* is 'N' or 'S', *X*, *Y* give the position
of the middle of the key arrow. If *labelpos* is 'E', *X*, *Y*
positions the head, and if *labelpos* is 'W', *X*, *Y* positions the
tail; in either of these two cases, *X*, *Y* is somewhere in the
middle of the arrow+label key object.
"""
class QuiverKey(martist.Artist):
""" Labelled arrow for use as a quiver plot scale key."""
halign = {'N': 'center', 'S': 'center', 'E': 'left', 'W': 'right'}
valign = {'N': 'bottom', 'S': 'top', 'E': 'center', 'W': 'center'}
pivot = {'N': 'middle', 'S': 'middle', 'E': 'tip', 'W': 'tail'}
def __init__(self, Q, X, Y, U, label,
*, angle=0, coordinates='axes', color=None, labelsep=0.1,
labelpos='N', labelcolor=None, fontproperties=None,
**kw):
martist.Artist.__init__(self)
self.Q = Q
self.X = X
self.Y = Y
self.U = U
self.angle = angle
self.coord = coordinates
self.color = color
self.label = label
self._labelsep_inches = labelsep
self.labelsep = (self._labelsep_inches * Q.ax.figure.dpi)
# try to prevent closure over the real self
weak_self = weakref.ref(self)
def on_dpi_change(fig):
self_weakref = weak_self()
if self_weakref is not None:
self_weakref.labelsep = (self_weakref._labelsep_inches*fig.dpi)
self_weakref._initialized = False # simple brute force update
# works because _init is
# called at the start of
# draw.
self._cid = Q.ax.figure.callbacks.connect('dpi_changed',
on_dpi_change)
self.labelpos = labelpos
self.labelcolor = labelcolor
self.fontproperties = fontproperties or dict()
self.kw = kw
_fp = self.fontproperties
# boxprops = dict(facecolor='red')
self.text = mtext.Text(
text=label, # bbox=boxprops,
horizontalalignment=self.halign[self.labelpos],
verticalalignment=self.valign[self.labelpos],
fontproperties=font_manager.FontProperties(**_fp))
if self.labelcolor is not None:
self.text.set_color(self.labelcolor)
self._initialized = False
self.zorder = Q.zorder + 0.1
def remove(self):
"""
Overload the remove method
"""
self.Q.ax.figure.callbacks.disconnect(self._cid)
self._cid = None
# pass the remove call up the stack
martist.Artist.remove(self)
__init__.__doc__ = _quiverkey_doc
def _init(self):
if True: # not self._initialized:
if not self.Q._initialized:
self.Q._init()
self._set_transform()
_pivot = self.Q.pivot
self.Q.pivot = self.pivot[self.labelpos]
# Hack: save and restore the Umask
_mask = self.Q.Umask
self.Q.Umask = ma.nomask
u = self.U * np.cos(np.radians(self.angle))
v = self.U * np.sin(np.radians(self.angle))
angle = self.Q.angles if isinstance(self.Q.angles, str) else 'uv'
self.verts = self.Q._make_verts(
np.array([u]), np.array([v]), angle)
self.Q.Umask = _mask
self.Q.pivot = _pivot
kw = self.Q.polykw
kw.update(self.kw)
self.vector = mcollections.PolyCollection(
self.verts,
offsets=[(self.X, self.Y)],
transOffset=self.get_transform(),
**kw)
if self.color is not None:
self.vector.set_color(self.color)
self.vector.set_transform(self.Q.get_transform())
self.vector.set_figure(self.get_figure())
self._initialized = True
def _text_x(self, x):
if self.labelpos == 'E':
return x + self.labelsep
elif self.labelpos == 'W':
return x - self.labelsep
else:
return x
def _text_y(self, y):
if self.labelpos == 'N':
return y + self.labelsep
elif self.labelpos == 'S':
return y - self.labelsep
else:
return y
@martist.allow_rasterization
def draw(self, renderer):
self._init()
self.vector.draw(renderer)
x, y = self.get_transform().transform_point((self.X, self.Y))
self.text.set_x(self._text_x(x))
self.text.set_y(self._text_y(y))
self.text.draw(renderer)
self.stale = False
def _set_transform(self):
if self.coord == 'data':
self.set_transform(self.Q.ax.transData)
elif self.coord == 'axes':
self.set_transform(self.Q.ax.transAxes)
elif self.coord == 'figure':
self.set_transform(self.Q.ax.figure.transFigure)
elif self.coord == 'inches':
self.set_transform(self.Q.ax.figure.dpi_scale_trans)
else:
raise ValueError('unrecognized coordinates')
def set_figure(self, fig):
martist.Artist.set_figure(self, fig)
self.text.set_figure(fig)
def contains(self, mouseevent):
# Maybe the dictionary should allow one to
# distinguish between a text hit and a vector hit.
if (self.text.contains(mouseevent)[0] or
self.vector.contains(mouseevent)[0]):
return True, {}
return False, {}
quiverkey_doc = _quiverkey_doc
# This is a helper function that parses out the various combination of
# arguments for doing colored vector plots. Pulling it out here
# allows both Quiver and Barbs to use it
def _parse_args(*args):
X = Y = U = V = C = None
args = list(args)
# The use of atleast_1d allows for handling scalar arguments while also
# keeping masked arrays
if len(args) == 3 or len(args) == 5:
C = np.atleast_1d(args.pop(-1))
V = np.atleast_1d(args.pop(-1))
U = np.atleast_1d(args.pop(-1))
cbook._check_not_matrix(U=U, V=V, C=C)
if U.ndim == 1:
nr, nc = 1, U.shape[0]
else:
nr, nc = U.shape
if len(args) == 2: # remaining after removing U,V,C
X, Y = [np.array(a).ravel() for a in args]
if len(X) == nc and len(Y) == nr:
X, Y = [a.ravel() for a in np.meshgrid(X, Y)]
else:
indexgrid = np.meshgrid(np.arange(nc), np.arange(nr))
X, Y = [np.ravel(a) for a in indexgrid]
return X, Y, U, V, C
def _check_consistent_shapes(*arrays):
all_shapes = {a.shape for a in arrays}
if len(all_shapes) != 1:
raise ValueError('The shapes of the passed in arrays do not match')
class Quiver(mcollections.PolyCollection):
"""
Specialized PolyCollection for arrows.
The only API method is set_UVC(), which can be used
to change the size, orientation, and color of the
arrows; their locations are fixed when the class is
instantiated. Possibly this method will be useful
in animations.
Much of the work in this class is done in the draw()
method so that as much information as possible is available
about the plot. In subsequent draw() calls, recalculation
is limited to things that might have changed, so there
should be no performance penalty from putting the calculations
in the draw() method.
"""
_PIVOT_VALS = ('tail', 'middle', 'tip')
@docstring.Substitution(_quiver_doc)
def __init__(self, ax, *args,
scale=None, headwidth=3, headlength=5, headaxislength=4.5,
minshaft=1, minlength=1, units='width', scale_units=None,
angles='uv', width=None, color='k', pivot='tail', **kw):
"""
The constructor takes one required argument, an Axes
instance, followed by the args and kwargs described
by the following pyplot interface documentation:
%s
"""
self.ax = ax
X, Y, U, V, C = _parse_args(*args)
self.X = X
self.Y = Y
self.XY = np.column_stack((X, Y))
self.N = len(X)
self.scale = scale
self.headwidth = headwidth
self.headlength = float(headlength)
self.headaxislength = headaxislength
self.minshaft = minshaft
self.minlength = minlength
self.units = units
self.scale_units = scale_units
self.angles = angles
self.width = width
if pivot.lower() == 'mid':
pivot = 'middle'
self.pivot = pivot.lower()
cbook._check_in_list(self._PIVOT_VALS, pivot=self.pivot)
self.transform = kw.pop('transform', ax.transData)
kw.setdefault('facecolors', color)
kw.setdefault('linewidths', (0,))
mcollections.PolyCollection.__init__(self, [], offsets=self.XY,
transOffset=self.transform,
closed=False,
**kw)
self.polykw = kw
self.set_UVC(U, V, C)
self._initialized = False
# try to prevent closure over the real self
weak_self = weakref.ref(self)
def on_dpi_change(fig):
self_weakref = weak_self()
if self_weakref is not None:
self_weakref._new_UV = True # vertices depend on width, span
# which in turn depend on dpi
self_weakref._initialized = False # simple brute force update
# works because _init is
# called at the start of
# draw.
self._cid = self.ax.figure.callbacks.connect('dpi_changed',
on_dpi_change)
@cbook.deprecated("3.1", alternative="get_facecolor()")
@property
def color(self):
return self.get_facecolor()
@cbook.deprecated("3.1")
@property
def keyvec(self):
return None
@cbook.deprecated("3.1")
@property
def keytext(self):
return None
def remove(self):
"""
Overload the remove method
"""
# disconnect the call back
self.ax.figure.callbacks.disconnect(self._cid)
self._cid = None
# pass the remove call up the stack
mcollections.PolyCollection.remove(self)
def _init(self):
"""
Initialization delayed until first draw;
allow time for axes setup.
"""
# It seems that there are not enough event notifications
# available to have this work on an as-needed basis at present.
if True: # not self._initialized:
trans = self._set_transform()
ax = self.ax
sx, sy = trans.inverted().transform_point(
(ax.bbox.width, ax.bbox.height))
self.span = sx
if self.width is None:
sn = np.clip(math.sqrt(self.N), 8, 25)
self.width = 0.06 * self.span / sn
# _make_verts sets self.scale if not already specified
if not self._initialized and self.scale is None:
self._make_verts(self.U, self.V, self.angles)
self._initialized = True
def get_datalim(self, transData):
trans = self.get_transform()
transOffset = self.get_offset_transform()
full_transform = (trans - transData) + (transOffset - transData)
XY = full_transform.transform(self.XY)
bbox = transforms.Bbox.null()
bbox.update_from_data_xy(XY, ignore=True)
return bbox
@martist.allow_rasterization
def draw(self, renderer):
self._init()
verts = self._make_verts(self.U, self.V, self.angles)
self.set_verts(verts, closed=False)
self._new_UV = False
mcollections.PolyCollection.draw(self, renderer)
self.stale = False
def set_UVC(self, U, V, C=None):
# We need to ensure we have a copy, not a reference
# to an array that might change before draw().
U = ma.masked_invalid(U, copy=True).ravel()
V = ma.masked_invalid(V, copy=True).ravel()
mask = ma.mask_or(U.mask, V.mask, copy=False, shrink=True)
if C is not None:
C = ma.masked_invalid(C, copy=True).ravel()
mask = ma.mask_or(mask, C.mask, copy=False, shrink=True)
if mask is ma.nomask:
C = C.filled()
else:
C = ma.array(C, mask=mask, copy=False)
self.U = U.filled(1)
self.V = V.filled(1)
self.Umask = mask
if C is not None:
self.set_array(C)
self._new_UV = True
self.stale = True
def _dots_per_unit(self, units):
"""
Return a scale factor for converting from units to pixels
"""
ax = self.ax
if units in ('x', 'y', 'xy'):
if units == 'x':
dx0 = ax.viewLim.width
dx1 = ax.bbox.width
elif units == 'y':
dx0 = ax.viewLim.height
dx1 = ax.bbox.height
else: # 'xy' is assumed
dxx0 = ax.viewLim.width
dxx1 = ax.bbox.width
dyy0 = ax.viewLim.height
dyy1 = ax.bbox.height
dx1 = np.hypot(dxx1, dyy1)
dx0 = np.hypot(dxx0, dyy0)
dx = dx1 / dx0
else:
if units == 'width':
dx = ax.bbox.width
elif units == 'height':
dx = ax.bbox.height
elif units == 'dots':
dx = 1.0
elif units == 'inches':
dx = ax.figure.dpi
else:
raise ValueError('unrecognized units')
return dx
def _set_transform(self):
"""
Sets the PolygonCollection transform to go
from arrow width units to pixels.
"""
dx = self._dots_per_unit(self.units)
self._trans_scale = dx # pixels per arrow width unit
trans = transforms.Affine2D().scale(dx)
self.set_transform(trans)
return trans
def _angles_lengths(self, U, V, eps=1):
xy = self.ax.transData.transform(self.XY)
uv = np.column_stack((U, V))
xyp = self.ax.transData.transform(self.XY + eps * uv)
dxy = xyp - xy
angles = np.arctan2(dxy[:, 1], dxy[:, 0])
lengths = np.hypot(*dxy.T) / eps
return angles, lengths
def _make_verts(self, U, V, angles):
uv = (U + V * 1j)
str_angles = angles if isinstance(angles, str) else ''
if str_angles == 'xy' and self.scale_units == 'xy':
# Here eps is 1 so that if we get U, V by diffing
# the X, Y arrays, the vectors will connect the
# points, regardless of the axis scaling (including log).
angles, lengths = self._angles_lengths(U, V, eps=1)
elif str_angles == 'xy' or self.scale_units == 'xy':
# Calculate eps based on the extents of the plot
# so that we don't end up with roundoff error from
# adding a small number to a large.
eps = np.abs(self.ax.dataLim.extents).max() * 0.001
angles, lengths = self._angles_lengths(U, V, eps=eps)
if str_angles and self.scale_units == 'xy':
a = lengths
else:
a = np.abs(uv)
if self.scale is None:
sn = max(10, math.sqrt(self.N))
if self.Umask is not ma.nomask:
amean = a[~self.Umask].mean()
else:
amean = a.mean()
# crude auto-scaling
# scale is typical arrow length as a multiple of the arrow width
scale = 1.8 * amean * sn / self.span
if self.scale_units is None:
if self.scale is None:
self.scale = scale
widthu_per_lenu = 1.0
else:
if self.scale_units == 'xy':
dx = 1
else:
dx = self._dots_per_unit(self.scale_units)
widthu_per_lenu = dx / self._trans_scale
if self.scale is None:
self.scale = scale * widthu_per_lenu
length = a * (widthu_per_lenu / (self.scale * self.width))
X, Y = self._h_arrows(length)
if str_angles == 'xy':
theta = angles
elif str_angles == 'uv':
theta = np.angle(uv)
else:
theta = ma.masked_invalid(np.deg2rad(angles)).filled(0)
theta = theta.reshape((-1, 1)) # for broadcasting
xy = (X + Y * 1j) * np.exp(1j * theta) * self.width
XY = np.stack((xy.real, xy.imag), axis=2)
if self.Umask is not ma.nomask:
XY = ma.array(XY)
XY[self.Umask] = ma.masked
# This might be handled more efficiently with nans, given
# that nans will end up in the paths anyway.
return XY
def _h_arrows(self, length):
""" length is in arrow width units """
# It might be possible to streamline the code
# and speed it up a bit by using complex (x,y)
# instead of separate arrays; but any gain would be slight.
minsh = self.minshaft * self.headlength
N = len(length)
length = length.reshape(N, 1)
# This number is chosen based on when pixel values overflow in Agg
# causing rendering errors
# length = np.minimum(length, 2 ** 16)
np.clip(length, 0, 2 ** 16, out=length)
# x, y: normal horizontal arrow
x = np.array([0, -self.headaxislength,
-self.headlength, 0],
np.float64)
x = x + np.array([0, 1, 1, 1]) * length
y = 0.5 * np.array([1, 1, self.headwidth, 0], np.float64)
y = np.repeat(y[np.newaxis, :], N, axis=0)
# x0, y0: arrow without shaft, for short vectors
x0 = np.array([0, minsh - self.headaxislength,
minsh - self.headlength, minsh], np.float64)
y0 = 0.5 * np.array([1, 1, self.headwidth, 0], np.float64)
ii = [0, 1, 2, 3, 2, 1, 0, 0]
X = x[:, ii]
Y = y[:, ii]
Y[:, 3:-1] *= -1
X0 = x0[ii]
Y0 = y0[ii]
Y0[3:-1] *= -1
shrink = length / minsh if minsh != 0. else 0.
X0 = shrink * X0[np.newaxis, :]
Y0 = shrink * Y0[np.newaxis, :]
short = np.repeat(length < minsh, 8, axis=1)
# Now select X0, Y0 if short, otherwise X, Y
np.copyto(X, X0, where=short)
np.copyto(Y, Y0, where=short)
if self.pivot == 'middle':
X -= 0.5 * X[:, 3, np.newaxis]
elif self.pivot == 'tip':
X = X - X[:, 3, np.newaxis] # numpy bug? using -= does not
# work here unless we multiply
# by a float first, as with 'mid'.
elif self.pivot != 'tail':
raise ValueError(("Quiver.pivot must have value in {{'middle', "
"'tip', 'tail'}} not {0}").format(self.pivot))
tooshort = length < self.minlength
if tooshort.any():
# Use a heptagonal dot:
th = np.arange(0, 8, 1, np.float64) * (np.pi / 3.0)
x1 = np.cos(th) * self.minlength * 0.5
y1 = np.sin(th) * self.minlength * 0.5
X1 = np.repeat(x1[np.newaxis, :], N, axis=0)
Y1 = np.repeat(y1[np.newaxis, :], N, axis=0)
tooshort = np.repeat(tooshort, 8, 1)
np.copyto(X, X1, where=tooshort)
np.copyto(Y, Y1, where=tooshort)
# Mask handling is deferred to the caller, _make_verts.
return X, Y
quiver_doc = _quiver_doc
_barbs_doc = r"""
Plot a 2-D field of barbs.
Call signatures::
barb(U, V, **kw)
barb(U, V, C, **kw)
barb(X, Y, U, V, **kw)
barb(X, Y, U, V, C, **kw)
Arguments:
*X*, *Y*:
The x and y coordinates of the barb locations
(default is head of barb; see *pivot* kwarg)
*U*, *V*:
Give the x and y components of the barb shaft
*C*:
An optional array used to map colors to the barbs
All arguments may be 1-D or 2-D arrays or sequences. If *X* and *Y*
are absent, they will be generated as a uniform grid. If *U* and *V*
are 2-D arrays but *X* and *Y* are 1-D, and if ``len(X)`` and ``len(Y)``
match the column and row dimensions of *U*, then *X* and *Y* will be
expanded with :func:`numpy.meshgrid`.
*U*, *V*, *C* may be masked arrays, but masked *X*, *Y* are not
supported at present.
Keyword arguments:
*length*:
Length of the barb in points; the other parts of the barb
are scaled against this.
Default is 7.
*pivot*: [ 'tip' | 'middle' | float ]
The part of the arrow that is at the grid point; the arrow rotates
about this point, hence the name *pivot*. Default is 'tip'. Can
also be a number, which shifts the start of the barb that many
points from the origin.
*barbcolor*: [ color | color sequence ]
Specifies the color all parts of the barb except any flags. This
parameter is analogous to the *edgecolor* parameter for polygons,
which can be used instead. However this parameter will override
facecolor.
*flagcolor*: [ color | color sequence ]
Specifies the color of any flags on the barb. This parameter is
analogous to the *facecolor* parameter for polygons, which can be
used instead. However this parameter will override facecolor. If
this is not set (and *C* has not either) then *flagcolor* will be
set to match *barbcolor* so that the barb has a uniform color. If
*C* has been set, *flagcolor* has no effect.
*sizes*:
A dictionary of coefficients specifying the ratio of a given
feature to the length of the barb. Only those values one wishes to
override need to be included. These features include:
- 'spacing' - space between features (flags, full/half barbs)
- 'height' - height (distance from shaft to top) of a flag or
full barb
- 'width' - width of a flag, twice the width of a full barb
- 'emptybarb' - radius of the circle used for low magnitudes
*fill_empty*:
A flag on whether the empty barbs (circles) that are drawn should
be filled with the flag color. If they are not filled, they will
be drawn such that no color is applied to the center. Default is
False
*rounding*:
A flag to indicate whether the vector magnitude should be rounded
when allocating barb components. If True, the magnitude is
rounded to the nearest multiple of the half-barb increment. If
False, the magnitude is simply truncated to the next lowest
multiple. Default is True
*barb_increments*:
A dictionary of increments specifying values to associate with
different parts of the barb. Only those values one wishes to
override need to be included.
- 'half' - half barbs (Default is 5)
- 'full' - full barbs (Default is 10)
- 'flag' - flags (default is 50)
*flip_barb*:
Either a single boolean flag or an array of booleans. Single
boolean indicates whether the lines and flags should point
opposite to normal for all barbs. An array (which should be the
same size as the other data arrays) indicates whether to flip for
each individual barb. Normal behavior is for the barbs and lines
to point right (comes from wind barbs having these features point
towards low pressure in the Northern Hemisphere.) Default is
False
Barbs are traditionally used in meteorology as a way to plot the speed
and direction of wind observations, but can technically be used to
plot any two dimensional vector quantity. As opposed to arrows, which
give vector magnitude by the length of the arrow, the barbs give more
quantitative information about the vector magnitude by putting slanted
lines or a triangle for various increments in magnitude, as show
schematically below::
: /\ \\
: / \ \\
: / \ \ \\
: / \ \ \\
: ------------------------------
.. note the double \\ at the end of each line to make the figure
.. render correctly
The largest increment is given by a triangle (or "flag"). After those
come full lines (barbs). The smallest increment is a half line. There
is only, of course, ever at most 1 half line. If the magnitude is
small and only needs a single half-line and no full lines or
triangles, the half-line is offset from the end of the barb so that it
can be easily distinguished from barbs with a single full line. The
magnitude for the barb shown above would nominally be 65, using the
standard increments of 50, 10, and 5.
linewidths and edgecolors can be used to customize the barb.
Additional :class:`~matplotlib.collections.PolyCollection` keyword
arguments:
%(PolyCollection)s
""" % docstring.interpd.params
docstring.interpd.update(barbs_doc=_barbs_doc)
class Barbs(mcollections.PolyCollection):
'''
Specialized PolyCollection for barbs.
The only API method is :meth:`set_UVC`, which can be used to
change the size, orientation, and color of the arrows. Locations
are changed using the :meth:`set_offsets` collection method.
Possibly this method will be useful in animations.
There is one internal function :meth:`_find_tails` which finds
exactly what should be put on the barb given the vector magnitude.
From there :meth:`_make_barbs` is used to find the vertices of the
polygon to represent the barb based on this information.
'''
# This may be an abuse of polygons here to render what is essentially maybe
# 1 triangle and a series of lines. It works fine as far as I can tell
# however.
@docstring.interpd
def __init__(self, ax, *args,
pivot='tip', length=7, barbcolor=None, flagcolor=None,
sizes=None, fill_empty=False, barb_increments=None,
rounding=True, flip_barb=False, **kw):
"""
The constructor takes one required argument, an Axes
instance, followed by the args and kwargs described
by the following pyplot interface documentation:
%(barbs_doc)s
"""
self.sizes = sizes or dict()
self.fill_empty = fill_empty
self.barb_increments = barb_increments or dict()
self.rounding = rounding
self.flip = flip_barb
transform = kw.pop('transform', ax.transData)
self._pivot = pivot
self._length = length
barbcolor = barbcolor
flagcolor = flagcolor
# Flagcolor and barbcolor provide convenience parameters for
# setting the facecolor and edgecolor, respectively, of the barb
# polygon. We also work here to make the flag the same color as the
# rest of the barb by default
if None in (barbcolor, flagcolor):
kw['edgecolors'] = 'face'
if flagcolor:
kw['facecolors'] = flagcolor
elif barbcolor:
kw['facecolors'] = barbcolor
else:
# Set to facecolor passed in or default to black
kw.setdefault('facecolors', 'k')
else:
kw['edgecolors'] = barbcolor
kw['facecolors'] = flagcolor
# Explicitly set a line width if we're not given one, otherwise
# polygons are not outlined and we get no barbs
if 'linewidth' not in kw and 'lw' not in kw:
kw['linewidth'] = 1
# Parse out the data arrays from the various configurations supported
x, y, u, v, c = _parse_args(*args)
self.x = x
self.y = y
xy = np.column_stack((x, y))
# Make a collection
barb_size = self._length ** 2 / 4 # Empirically determined
mcollections.PolyCollection.__init__(self, [], (barb_size,),
offsets=xy,
transOffset=transform, **kw)
self.set_transform(transforms.IdentityTransform())
self.set_UVC(u, v, c)
def _find_tails(self, mag, rounding=True, half=5, full=10, flag=50):
'''
Find how many of each of the tail pieces is necessary. Flag
specifies the increment for a flag, barb for a full barb, and half for
half a barb. Mag should be the magnitude of a vector (i.e., >= 0).
This returns a tuple of:
(*number of flags*, *number of barbs*, *half_flag*, *empty_flag*)
*half_flag* is a boolean whether half of a barb is needed,
since there should only ever be one half on a given
barb. *empty_flag* flag is an array of flags to easily tell if
a barb is empty (too low to plot any barbs/flags.
'''
# If rounding, round to the nearest multiple of half, the smallest
# increment
if rounding:
mag = half * (mag / half + 0.5).astype(int)
num_flags = np.floor(mag / flag).astype(int)
mag = mag % flag
num_barb = np.floor(mag / full).astype(int)
mag = mag % full
half_flag = mag >= half
empty_flag = ~(half_flag | (num_flags > 0) | (num_barb > 0))
return num_flags, num_barb, half_flag, empty_flag
def _make_barbs(self, u, v, nflags, nbarbs, half_barb, empty_flag, length,
pivot, sizes, fill_empty, flip):
'''
This function actually creates the wind barbs. *u* and *v*
are components of the vector in the *x* and *y* directions,
respectively.
*nflags*, *nbarbs*, and *half_barb*, empty_flag* are,
*respectively, the number of flags, number of barbs, flag for
*half a barb, and flag for empty barb, ostensibly obtained
*from :meth:`_find_tails`.
*length* is the length of the barb staff in points.
*pivot* specifies the point on the barb around which the
entire barb should be rotated. Right now, valid options are
'tip' and 'middle'. Can also be a number, which shifts the start
of the barb that many points from the origin.
*sizes* is a dictionary of coefficients specifying the ratio
of a given feature to the length of the barb. These features
include:
- *spacing*: space between features (flags, full/half
barbs)
- *height*: distance from shaft of top of a flag or full
barb
- *width* - width of a flag, twice the width of a full barb
- *emptybarb* - radius of the circle used for low
magnitudes
*fill_empty* specifies whether the circle representing an
empty barb should be filled or not (this changes the drawing
of the polygon).
*flip* is a flag indicating whether the features should be flipped to
the other side of the barb (useful for winds in the southern
hemisphere).
This function returns list of arrays of vertices, defining a polygon
for each of the wind barbs. These polygons have been rotated to
properly align with the vector direction.
'''
# These control the spacing and size of barb elements relative to the
# length of the shaft
spacing = length * sizes.get('spacing', 0.125)
full_height = length * sizes.get('height', 0.4)
full_width = length * sizes.get('width', 0.25)
empty_rad = length * sizes.get('emptybarb', 0.15)
# Controls y point where to pivot the barb.
pivot_points = dict(tip=0.0, middle=-length / 2.)
# Check for flip
if flip:
full_height = -full_height
endx = 0.0
try:
endy = float(pivot)
except ValueError:
endy = pivot_points[pivot.lower()]
# Get the appropriate angle for the vector components. The offset is
# due to the way the barb is initially drawn, going down the y-axis.
# This makes sense in a meteorological mode of thinking since there 0
# degrees corresponds to north (the y-axis traditionally)
angles = -(ma.arctan2(v, u) + np.pi / 2)
# Used for low magnitude. We just get the vertices, so if we make it
# out here, it can be reused. The center set here should put the
# center of the circle at the location(offset), rather than at the
# same point as the barb pivot; this seems more sensible.
circ = CirclePolygon((0, 0), radius=empty_rad).get_verts()
if fill_empty:
empty_barb = circ
else:
# If we don't want the empty one filled, we make a degenerate
# polygon that wraps back over itself
empty_barb = np.concatenate((circ, circ[::-1]))
barb_list = []
for index, angle in np.ndenumerate(angles):
# If the vector magnitude is too weak to draw anything, plot an
# empty circle instead
if empty_flag[index]:
# We can skip the transform since the circle has no preferred
# orientation
barb_list.append(empty_barb)
continue
poly_verts = [(endx, endy)]
offset = length
# Add vertices for each flag
for i in range(nflags[index]):
# The spacing that works for the barbs is a little to much for
# the flags, but this only occurs when we have more than 1
# flag.
if offset != length:
offset += spacing / 2.
poly_verts.extend(
[[endx, endy + offset],
[endx + full_height, endy - full_width / 2 + offset],
[endx, endy - full_width + offset]])
offset -= full_width + spacing
# Add vertices for each barb. These really are lines, but works
# great adding 3 vertices that basically pull the polygon out and
# back down the line
for i in range(nbarbs[index]):
poly_verts.extend(
[(endx, endy + offset),
(endx + full_height, endy + offset + full_width / 2),
(endx, endy + offset)])
offset -= spacing
# Add the vertices for half a barb, if needed
if half_barb[index]:
# If the half barb is the first on the staff, traditionally it
# is offset from the end to make it easy to distinguish from a
# barb with a full one
if offset == length:
poly_verts.append((endx, endy + offset))
offset -= 1.5 * spacing
poly_verts.extend(
[(endx, endy + offset),
(endx + full_height / 2, endy + offset + full_width / 4),
(endx, endy + offset)])
# Rotate the barb according the angle. Making the barb first and
# then rotating it made the math for drawing the barb really easy.
# Also, the transform framework makes doing the rotation simple.
poly_verts = transforms.Affine2D().rotate(-angle).transform(
poly_verts)
barb_list.append(poly_verts)
return barb_list
def set_UVC(self, U, V, C=None):
self.u = ma.masked_invalid(U, copy=False).ravel()
self.v = ma.masked_invalid(V, copy=False).ravel()
if C is not None:
c = ma.masked_invalid(C, copy=False).ravel()
x, y, u, v, c = cbook.delete_masked_points(
self.x.ravel(), self.y.ravel(), self.u, self.v, c)
_check_consistent_shapes(x, y, u, v, c)
else:
x, y, u, v = cbook.delete_masked_points(
self.x.ravel(), self.y.ravel(), self.u, self.v)
_check_consistent_shapes(x, y, u, v)
magnitude = np.hypot(u, v)
flags, barbs, halves, empty = self._find_tails(magnitude,
self.rounding,
**self.barb_increments)
# Get the vertices for each of the barbs
plot_barbs = self._make_barbs(u, v, flags, barbs, halves, empty,
self._length, self._pivot, self.sizes,
self.fill_empty, self.flip)
self.set_verts(plot_barbs)
# Set the color array
if C is not None:
self.set_array(c)
# Update the offsets in case the masked data changed
xy = np.column_stack((x, y))
self._offsets = xy
self.stale = True
def set_offsets(self, xy):
"""
Set the offsets for the barb polygons. This saves the offsets passed
in and masks them as appropriate for the existing U/V data.
Parameters
----------
xy : sequence of pairs of floats
"""
self.x = xy[:, 0]
self.y = xy[:, 1]
x, y, u, v = cbook.delete_masked_points(
self.x.ravel(), self.y.ravel(), self.u, self.v)
_check_consistent_shapes(x, y, u, v)
xy = np.column_stack((x, y))
mcollections.PolyCollection.set_offsets(self, xy)
self.stale = True
barbs_doc = _barbs_doc
|
6958c6bfff7c129f531ea8fe953974a79a63539e721c9cf6ee46318582bf7747
|
from collections import OrderedDict, namedtuple
from functools import wraps
import inspect
import logging
from numbers import Number
import re
import warnings
import numpy as np
import matplotlib
from . import cbook, docstring, rcParams
from .path import Path
from .transforms import (Bbox, IdentityTransform, Transform, TransformedBbox,
TransformedPatchPath, TransformedPath)
_log = logging.getLogger(__name__)
def allow_rasterization(draw):
"""
Decorator for Artist.draw method. Provides routines
that run before and after the draw call. The before and after functions
are useful for changing artist-dependent renderer attributes or making
other setup function calls, such as starting and flushing a mixed-mode
renderer.
"""
# the axes class has a second argument inframe for its draw method.
@wraps(draw)
def draw_wrapper(artist, renderer, *args, **kwargs):
try:
if artist.get_rasterized():
renderer.start_rasterizing()
if artist.get_agg_filter() is not None:
renderer.start_filter()
return draw(artist, renderer, *args, **kwargs)
finally:
if artist.get_agg_filter() is not None:
renderer.stop_filter(artist.get_agg_filter())
if artist.get_rasterized():
renderer.stop_rasterizing()
draw_wrapper._supports_rasterization = True
return draw_wrapper
def _stale_axes_callback(self, val):
if self.axes:
self.axes.stale = val
_XYPair = namedtuple("_XYPair", "x y")
class Artist(object):
"""
Abstract base class for objects that render into a FigureCanvas.
Typically, all visible elements in a figure are subclasses of Artist.
"""
@cbook.deprecated("3.1")
@property
def aname(self):
return 'Artist'
zorder = 0
# order of precedence when bulk setting/updating properties
# via update. The keys should be property names and the values
# integers
_prop_order = dict(color=-1)
def __init__(self):
self._stale = True
self.stale_callback = None
self._axes = None
self.figure = None
self._transform = None
self._transformSet = False
self._visible = True
self._animated = False
self._alpha = None
self.clipbox = None
self._clippath = None
self._clipon = True
self._label = ''
self._picker = None
self._contains = None
self._rasterized = None
self._agg_filter = None
self._mouseover = False
self.eventson = False # fire events only if eventson
self._oid = 0 # an observer id
self._propobservers = {} # a dict from oids to funcs
try:
self.axes = None
except AttributeError:
# Handle self.axes as a read-only property, as in Figure.
pass
self._remove_method = None
self._url = None
self._gid = None
self._snap = None
self._sketch = rcParams['path.sketch']
self._path_effects = rcParams['path.effects']
self._sticky_edges = _XYPair([], [])
self._in_layout = True
def __getstate__(self):
d = self.__dict__.copy()
# remove the unpicklable remove method, this will get re-added on load
# (by the axes) if the artist lives on an axes.
d['stale_callback'] = None
return d
def remove(self):
"""
Remove the artist from the figure if possible.
The effect will not be visible until the figure is redrawn, e.g.,
with `.FigureCanvasBase.draw_idle`. Call `~.axes.Axes.relim` to
update the axes limits if desired.
Note: `~.axes.Axes.relim` will not see collections even if the
collection was added to the axes with *autolim* = True.
Note: there is no support for removing the artist's legend entry.
"""
# There is no method to set the callback. Instead the parent should
# set the _remove_method attribute directly. This would be a
# protected attribute if Python supported that sort of thing. The
# callback has one parameter, which is the child to be removed.
if self._remove_method is not None:
self._remove_method(self)
# clear stale callback
self.stale_callback = None
_ax_flag = False
if hasattr(self, 'axes') and self.axes:
# remove from the mouse hit list
self.axes._mouseover_set.discard(self)
# mark the axes as stale
self.axes.stale = True
# decouple the artist from the axes
self.axes = None
_ax_flag = True
if self.figure:
self.figure = None
if not _ax_flag:
self.figure = True
else:
raise NotImplementedError('cannot remove artist')
# TODO: the fix for the collections relim problem is to move the
# limits calculation into the artist itself, including the property of
# whether or not the artist should affect the limits. Then there will
# be no distinction between axes.add_line, axes.add_patch, etc.
# TODO: add legend support
def have_units(self):
"""Return *True* if units are set on the *x* or *y* axes."""
ax = self.axes
if ax is None or ax.xaxis is None:
return False
return ax.xaxis.have_units() or ax.yaxis.have_units()
def convert_xunits(self, x):
"""
Convert *x* using the unit type of the xaxis.
If the artist is not in contained in an Axes or if the xaxis does not
have units, *x* itself is returned.
"""
ax = getattr(self, 'axes', None)
if ax is None or ax.xaxis is None:
return x
return ax.xaxis.convert_units(x)
def convert_yunits(self, y):
"""
Convert *y* using the unit type of the yaxis.
If the artist is not in contained in an Axes or if the yaxis does not
have units, *y* itself is returned.
"""
ax = getattr(self, 'axes', None)
if ax is None or ax.yaxis is None:
return y
return ax.yaxis.convert_units(y)
@property
def axes(self):
"""The `~.axes.Axes` instance the artist resides in, or *None*."""
return self._axes
@axes.setter
def axes(self, new_axes):
if (new_axes is not None and self._axes is not None
and new_axes != self._axes):
raise ValueError("Can not reset the axes. You are probably "
"trying to re-use an artist in more than one "
"Axes which is not supported")
self._axes = new_axes
if new_axes is not None and new_axes is not self:
self.stale_callback = _stale_axes_callback
return new_axes
@property
def stale(self):
"""
Whether the artist is 'stale' and needs to be re-drawn for the output
to match the internal state of the artist.
"""
return self._stale
@stale.setter
def stale(self, val):
self._stale = val
# if the artist is animated it does not take normal part in the
# draw stack and is not expected to be drawn as part of the normal
# draw loop (when not saving) so do not propagate this change
if self.get_animated():
return
if val and self.stale_callback is not None:
self.stale_callback(self, val)
def get_window_extent(self, renderer):
"""
Get the axes bounding box in display space.
The bounding box' width and height are nonnegative.
Subclasses should override for inclusion in the bounding box
"tight" calculation. Default is to return an empty bounding
box at 0, 0.
Be careful when using this function, the results will not update
if the artist window extent of the artist changes. The extent
can change due to any changes in the transform stack, such as
changing the axes limits, the figure size, or the canvas used
(as is done when saving a figure). This can lead to unexpected
behavior where interactive figures will look fine on the screen,
but will save incorrectly.
"""
return Bbox([[0, 0], [0, 0]])
def get_tightbbox(self, renderer):
"""
Like `Artist.get_window_extent`, but includes any clipping.
Parameters
----------
renderer : `.RendererBase` instance
renderer that will be used to draw the figures (i.e.
``fig.canvas.get_renderer()``)
Returns
-------
bbox : `.BBox`
The enclosing bounding box (in figure pixel co-ordinates).
"""
bbox = self.get_window_extent(renderer)
if self.get_clip_on():
clip_box = self.get_clip_box()
if clip_box is not None:
bbox = Bbox.intersection(bbox, clip_box)
clip_path = self.get_clip_path()
if clip_path is not None and bbox is not None:
clip_path = clip_path.get_fully_transformed_path()
bbox = Bbox.intersection(bbox, clip_path.get_extents())
return bbox
def add_callback(self, func):
"""
Add a callback function that will be called whenever one of the
`.Artist`'s properties changes.
Parameters
----------
func : callable
The callback function. It must have the signature::
def func(artist: Artist) -> Any
where *artist* is the calling `.Artist`. Return values may exist
but are ignored.
Returns
-------
oid : int
The observer id associated with the callback. This id can be
used for removing the callback with `.remove_callback` later.
See Also
--------
remove_callback
"""
oid = self._oid
self._propobservers[oid] = func
self._oid += 1
return oid
def remove_callback(self, oid):
"""
Remove a callback based on its observer id.
See Also
--------
add_callback
"""
try:
del self._propobservers[oid]
except KeyError:
pass
def pchanged(self):
"""
Call all of the registered callbacks.
This function is triggered internally when a property is changed.
See Also
--------
add_callback
remove_callback
"""
for oid, func in self._propobservers.items():
func(self)
def is_transform_set(self):
"""
Return whether the Artist has an explicitly set transform.
This is *True* after `.set_transform` has been called.
"""
return self._transformSet
def set_transform(self, t):
"""
Set the artist transform.
Parameters
----------
t : `.Transform`
"""
self._transform = t
self._transformSet = True
self.pchanged()
self.stale = True
def get_transform(self):
"""Return the `.Transform` instance used by this artist."""
if self._transform is None:
self._transform = IdentityTransform()
elif (not isinstance(self._transform, Transform)
and hasattr(self._transform, '_as_mpl_transform')):
self._transform = self._transform._as_mpl_transform(self.axes)
return self._transform
def get_children(self):
r"""Return a list of the child `.Artist`\s of this `.Artist`."""
return []
def contains(self, mouseevent):
"""Test whether the artist contains the mouse event.
Parameters
----------
mouseevent : `matplotlib.backend_bases.MouseEvent`
Returns
-------
contains : bool
Whether any values are within the radius.
details : dict
An artist-specific dictionary of details of the event context,
such as which points are contained in the pick radius. See the
individual Artist subclasses for details.
See Also
--------
set_contains, get_contains
"""
if self._contains is not None:
return self._contains(self, mouseevent)
_log.warning("%r needs 'contains' method", self.__class__.__name__)
return False, {}
def set_contains(self, picker):
"""
Define a custom contains test for the artist.
The provided callable replaces the default `.contains` method
of the artist.
Parameters
----------
picker : callable
A custom picker function to evaluate if an event is within the
artist. The function must have the signature::
def contains(artist: Artist, event: MouseEvent) -> bool, dict
that returns:
- a bool indicating if the event is within the artist
- a dict of additional information. The dict should at least
return the same information as the default ``contains()``
implementation of the respective artist, but may provide
additional information.
"""
if not callable(picker):
raise TypeError("picker is not a callable")
self._contains = picker
def get_contains(self):
"""
Return the custom contains function of the artist if set, or *None*.
See Also
--------
set_contains
"""
return self._contains
def pickable(self):
"""
Return whether the artist is pickable.
See Also
--------
set_picker, get_picker, pick
"""
return self.figure is not None and self._picker is not None
def pick(self, mouseevent):
"""
Process a pick event.
Each child artist will fire a pick event if *mouseevent* is over
the artist and the artist has picker set.
See Also
--------
set_picker, get_picker, pickable
"""
# Pick self
if self.pickable():
picker = self.get_picker()
if callable(picker):
inside, prop = picker(self, mouseevent)
else:
inside, prop = self.contains(mouseevent)
if inside:
self.figure.canvas.pick_event(mouseevent, self, **prop)
# Pick children
for a in self.get_children():
# make sure the event happened in the same axes
ax = getattr(a, 'axes', None)
if (mouseevent.inaxes is None or ax is None
or mouseevent.inaxes == ax):
# we need to check if mouseevent.inaxes is None
# because some objects associated with an axes (e.g., a
# tick label) can be outside the bounding box of the
# axes and inaxes will be None
# also check that ax is None so that it traverse objects
# which do no have an axes property but children might
a.pick(mouseevent)
def set_picker(self, picker):
"""
Define the picking behavior of the artist.
Parameters
----------
picker : None or bool or float or callable
This can be one of the following:
- *None*: Picking is disabled for this artist (default).
- A boolean: If *True* then picking will be enabled and the
artist will fire a pick event if the mouse event is over
the artist.
- A float: If picker is a number it is interpreted as an
epsilon tolerance in points and the artist will fire
off an event if it's data is within epsilon of the mouse
event. For some artists like lines and patch collections,
the artist may provide additional data to the pick event
that is generated, e.g., the indices of the data within
epsilon of the pick event
- A function: If picker is callable, it is a user supplied
function which determines whether the artist is hit by the
mouse event::
hit, props = picker(artist, mouseevent)
to determine the hit test. if the mouse event is over the
artist, return *hit=True* and props is a dictionary of
properties you want added to the PickEvent attributes.
"""
self._picker = picker
def get_picker(self):
"""
Return the picking behavior of the artist.
The possible values are described in `.set_picker`.
See Also
--------
set_picker, pickable, pick
"""
return self._picker
def get_url(self):
"""Return the url."""
return self._url
def set_url(self, url):
"""
Set the url for the artist.
Parameters
----------
url : str
"""
self._url = url
def get_gid(self):
"""Return the group id."""
return self._gid
def set_gid(self, gid):
"""
Set the (group) id for the artist.
Parameters
----------
gid : str
"""
self._gid = gid
def get_snap(self):
"""
Returns the snap setting.
See `.set_snap` for details.
"""
if rcParams['path.snap']:
return self._snap
else:
return False
def set_snap(self, snap):
"""
Set the snapping behavior.
Snapping aligns positions with the pixel grid, which results in
clearer images. For example, if a black line of 1px width was
defined at a position in between two pixels, the resulting image
would contain the interpolated value of that line in the pixel grid,
which would be a grey value on both adjacent pixel positions. In
contrast, snapping will move the line to the nearest integer pixel
value, so that the resulting image will really contain a 1px wide
black line.
Snapping is currently only supported by the Agg and MacOSX backends.
Parameters
----------
snap : bool or None
Possible values:
- *True*: Snap vertices to the nearest pixel center.
- *False*: Do not modify vertex positions.
- *None*: (auto) If the path contains only rectilinear line
segments, round to the nearest pixel center.
"""
self._snap = snap
self.stale = True
def get_sketch_params(self):
"""
Returns the sketch parameters for the artist.
Returns
-------
sketch_params : tuple or None
A 3-tuple with the following elements:
- *scale*: The amplitude of the wiggle perpendicular to the
source line.
- *length*: The length of the wiggle along the line.
- *randomness*: The scale factor by which the length is
shrunken or expanded.
Returns *None* if no sketch parameters were set.
"""
return self._sketch
def set_sketch_params(self, scale=None, length=None, randomness=None):
"""
Sets the sketch parameters.
Parameters
----------
scale : float, optional
The amplitude of the wiggle perpendicular to the source
line, in pixels. If scale is `None`, or not provided, no
sketch filter will be provided.
length : float, optional
The length of the wiggle along the line, in pixels
(default 128.0)
randomness : float, optional
The scale factor by which the length is shrunken or
expanded (default 16.0)
.. ACCEPTS: (scale: float, length: float, randomness: float)
"""
if scale is None:
self._sketch = None
else:
self._sketch = (scale, length or 128.0, randomness or 16.0)
self.stale = True
def set_path_effects(self, path_effects):
"""Set the path effects.
Parameters
----------
path_effects : `.AbstractPathEffect`
"""
self._path_effects = path_effects
self.stale = True
def get_path_effects(self):
return self._path_effects
def get_figure(self):
"""Return the `.Figure` instance the artist belongs to."""
return self.figure
def set_figure(self, fig):
"""
Set the `.Figure` instance the artist belongs to.
Parameters
----------
fig : `.Figure`
"""
# if this is a no-op just return
if self.figure is fig:
return
# if we currently have a figure (the case of both `self.figure`
# and `fig` being none is taken care of above) we then user is
# trying to change the figure an artist is associated with which
# is not allowed for the same reason as adding the same instance
# to more than one Axes
if self.figure is not None:
raise RuntimeError("Can not put single artist in "
"more than one figure")
self.figure = fig
if self.figure and self.figure is not self:
self.pchanged()
self.stale = True
def set_clip_box(self, clipbox):
"""
Set the artist's clip `.Bbox`.
Parameters
----------
clipbox : `.Bbox`
"""
self.clipbox = clipbox
self.pchanged()
self.stale = True
def set_clip_path(self, path, transform=None):
"""
Set the artist's clip path, which may be:
- a :class:`~matplotlib.patches.Patch` (or subclass) instance; or
- a :class:`~matplotlib.path.Path` instance, in which case a
:class:`~matplotlib.transforms.Transform` instance, which will be
applied to the path before using it for clipping, must be provided;
or
- ``None``, to remove a previously set clipping path.
For efficiency, if the path happens to be an axis-aligned rectangle,
this method will set the clipping box to the corresponding rectangle
and set the clipping path to ``None``.
ACCEPTS: [(`~matplotlib.path.Path`, `.Transform`) | `.Patch` | None]
"""
from matplotlib.patches import Patch, Rectangle
success = False
if transform is None:
if isinstance(path, Rectangle):
self.clipbox = TransformedBbox(Bbox.unit(),
path.get_transform())
self._clippath = None
success = True
elif isinstance(path, Patch):
self._clippath = TransformedPatchPath(path)
success = True
elif isinstance(path, tuple):
path, transform = path
if path is None:
self._clippath = None
success = True
elif isinstance(path, Path):
self._clippath = TransformedPath(path, transform)
success = True
elif isinstance(path, TransformedPatchPath):
self._clippath = path
success = True
elif isinstance(path, TransformedPath):
self._clippath = path
success = True
if not success:
raise TypeError(
"Invalid arguments to set_clip_path, of type {} and {}"
.format(type(path).__name__, type(transform).__name__))
# This may result in the callbacks being hit twice, but guarantees they
# will be hit at least once.
self.pchanged()
self.stale = True
def get_alpha(self):
"""
Return the alpha value used for blending - not supported on all
backends
"""
return self._alpha
def get_visible(self):
"""Return the visibility."""
return self._visible
def get_animated(self):
"""Return the animated state."""
return self._animated
def get_in_layout(self):
"""
Return boolean flag, ``True`` if artist is included in layout
calculations.
E.g. :doc:`/tutorials/intermediate/constrainedlayout_guide`,
`.Figure.tight_layout()`, and
``fig.savefig(fname, bbox_inches='tight')``.
"""
return self._in_layout
def get_clip_on(self):
"""Return whether the artist uses clipping."""
return self._clipon
def get_clip_box(self):
"""Return the clipbox."""
return self.clipbox
def get_clip_path(self):
"""Return the clip path."""
return self._clippath
def get_transformed_clip_path_and_affine(self):
'''
Return the clip path with the non-affine part of its
transformation applied, and the remaining affine part of its
transformation.
'''
if self._clippath is not None:
return self._clippath.get_transformed_path_and_affine()
return None, None
def set_clip_on(self, b):
"""
Set whether the artist uses clipping.
When False artists will be visible out side of the axes which
can lead to unexpected results.
Parameters
----------
b : bool
"""
self._clipon = b
# This may result in the callbacks being hit twice, but ensures they
# are hit at least once
self.pchanged()
self.stale = True
def _set_gc_clip(self, gc):
'Set the clip properly for the gc'
if self._clipon:
if self.clipbox is not None:
gc.set_clip_rectangle(self.clipbox)
gc.set_clip_path(self._clippath)
else:
gc.set_clip_rectangle(None)
gc.set_clip_path(None)
def get_rasterized(self):
"""Return whether the artist is to be rasterized."""
return self._rasterized
def set_rasterized(self, rasterized):
"""
Force rasterized (bitmap) drawing in vector backend output.
Defaults to None, which implies the backend's default behavior.
Parameters
----------
rasterized : bool or None
"""
if rasterized and not hasattr(self.draw, "_supports_rasterization"):
cbook._warn_external(
"Rasterization of '%s' will be ignored" % self)
self._rasterized = rasterized
def get_agg_filter(self):
"""Return filter function to be used for agg filter."""
return self._agg_filter
def set_agg_filter(self, filter_func):
"""Set the agg filter.
Parameters
----------
filter_func : callable
A filter function, which takes a (m, n, 3) float array and a dpi
value, and returns a (m, n, 3) array.
.. ACCEPTS: a filter function, which takes a (m, n, 3) float array
and a dpi value, and returns a (m, n, 3) array
"""
self._agg_filter = filter_func
self.stale = True
def draw(self, renderer, *args, **kwargs):
"""
Draw the Artist using the given renderer.
This method will be overridden in the Artist subclasses. Typically,
it is implemented to not have any effect if the Artist is not visible
(`.Artist.get_visible` is *False*).
Parameters
----------
renderer : `.RendererBase` subclass.
"""
if not self.get_visible():
return
self.stale = False
def set_alpha(self, alpha):
"""
Set the alpha value used for blending - not supported on all backends.
Parameters
----------
alpha : float or None
"""
if alpha is not None and not isinstance(alpha, Number):
raise TypeError('alpha must be a float or None')
self._alpha = alpha
self.pchanged()
self.stale = True
def set_visible(self, b):
"""
Set the artist's visibility.
Parameters
----------
b : bool
"""
self._visible = b
self.pchanged()
self.stale = True
def set_animated(self, b):
"""
Set the artist's animation state.
Parameters
----------
b : bool
"""
if self._animated != b:
self._animated = b
self.pchanged()
def set_in_layout(self, in_layout):
"""
Set if artist is to be included in layout calculations,
E.g. :doc:`/tutorials/intermediate/constrainedlayout_guide`,
`.Figure.tight_layout()`, and
``fig.savefig(fname, bbox_inches='tight')``.
Parameters
----------
in_layout : bool
"""
self._in_layout = in_layout
def update(self, props):
"""
Update this artist's properties from the dictionary *props*.
"""
def _update_property(self, k, v):
"""Sorting out how to update property (setter or setattr).
Parameters
----------
k : str
The name of property to update
v : obj
The value to assign to the property
Returns
-------
ret : obj or None
If using a `set_*` method return it's return, else None.
"""
k = k.lower()
# white list attributes we want to be able to update through
# art.update, art.set, setp
if k in {'axes'}:
return setattr(self, k, v)
else:
func = getattr(self, 'set_' + k, None)
if not callable(func):
raise AttributeError('{!r} object has no property {!r}'
.format(type(self).__name__, k))
return func(v)
with cbook._setattr_cm(self, eventson=False):
ret = [_update_property(self, k, v) for k, v in props.items()]
if len(ret):
self.pchanged()
self.stale = True
return ret
def get_label(self):
"""Return the label used for this artist in the legend."""
return self._label
def set_label(self, s):
"""
Set a label that will be displayed in the legend.
Parameters
----------
s : object
*s* will be converted to a string by calling `str`.
"""
if s is not None:
self._label = str(s)
else:
self._label = None
self.pchanged()
self.stale = True
def get_zorder(self):
"""Return the artist's zorder."""
return self.zorder
def set_zorder(self, level):
"""
Set the zorder for the artist. Artists with lower zorder
values are drawn first.
Parameters
----------
level : float
"""
if level is None:
level = self.__class__.zorder
self.zorder = level
self.pchanged()
self.stale = True
@property
def sticky_edges(self):
"""
``x`` and ``y`` sticky edge lists for autoscaling.
When performing autoscaling, if a data limit coincides with a value in
the corresponding sticky_edges list, then no margin will be added--the
view limit "sticks" to the edge. A typical use case is histograms,
where one usually expects no margin on the bottom edge (0) of the
histogram.
This attribute cannot be assigned to; however, the ``x`` and ``y``
lists can be modified in place as needed.
Examples
--------
>>> artist.sticky_edges.x[:] = (xmin, xmax)
>>> artist.sticky_edges.y[:] = (ymin, ymax)
"""
return self._sticky_edges
def update_from(self, other):
'Copy properties from *other* to *self*.'
self._transform = other._transform
self._transformSet = other._transformSet
self._visible = other._visible
self._alpha = other._alpha
self.clipbox = other.clipbox
self._clipon = other._clipon
self._clippath = other._clippath
self._label = other._label
self._sketch = other._sketch
self._path_effects = other._path_effects
self.sticky_edges.x[:] = other.sticky_edges.x[:]
self.sticky_edges.y[:] = other.sticky_edges.y[:]
self.pchanged()
self.stale = True
def properties(self):
"""Return a dictionary of all the properties of the artist."""
return ArtistInspector(self).properties()
def set(self, **kwargs):
"""A property batch setter. Pass *kwargs* to set properties."""
kwargs = cbook.normalize_kwargs(kwargs, self)
props = OrderedDict(
sorted(kwargs.items(), reverse=True,
key=lambda x: (self._prop_order.get(x[0], 0), x[0])))
return self.update(props)
def findobj(self, match=None, include_self=True):
"""
Find artist objects.
Recursively find all `.Artist` instances contained in the artist.
Parameters
----------
match
A filter criterion for the matches. This can be
- *None*: Return all objects contained in artist.
- A function with signature ``def match(artist: Artist) -> bool``.
The result will only contain artists for which the function
returns *True*.
- A class instance: e.g., `.Line2D`. The result will only contain
artists of this class or its subclasses (``isinstance`` check).
include_self : bool
Include *self* in the list to be checked for a match.
Returns
-------
artists : list of `.Artist`
"""
if match is None: # always return True
def matchfunc(x):
return True
elif isinstance(match, type) and issubclass(match, Artist):
def matchfunc(x):
return isinstance(x, match)
elif callable(match):
matchfunc = match
else:
raise ValueError('match must be None, a matplotlib.artist.Artist '
'subclass, or a callable')
artists = sum([c.findobj(matchfunc) for c in self.get_children()], [])
if include_self and matchfunc(self):
artists.append(self)
return artists
def get_cursor_data(self, event):
"""
Return the cursor data for a given event.
.. note::
This method is intended to be overridden by artist subclasses.
As an end-user of Matplotlib you will most likely not call this
method yourself.
Cursor data can be used by Artists to provide additional context
information for a given event. The default implementation just returns
*None*.
Subclasses can override the method and return arbitrary data. However,
when doing so, they must ensure that `.format_cursor_data` can convert
the data to a string representation.
The only current use case is displaying the z-value of an `.AxesImage`
in the status bar of a plot window, while moving the mouse.
Parameters
----------
event : `matplotlib.backend_bases.MouseEvent`
See Also
--------
format_cursor_data
"""
return None
def format_cursor_data(self, data):
"""
Return a string representation of *data*.
.. note::
This method is intended to be overridden by artist subclasses.
As an end-user of Matplotlib you will most likely not call this
method yourself.
The default implementation converts ints and floats and arrays of ints
and floats into a comma-separated string enclosed in square brackets.
See Also
--------
get_cursor_data
"""
try:
data[0]
except (TypeError, IndexError):
data = [data]
data_str = ', '.join('{:0.3g}'.format(item) for item in data
if isinstance(item, Number))
return "[" + data_str + "]"
@property
def mouseover(self):
return self._mouseover
@mouseover.setter
def mouseover(self, val):
val = bool(val)
self._mouseover = val
ax = self.axes
if ax:
if val:
ax._mouseover_set.add(self)
else:
ax._mouseover_set.discard(self)
class ArtistInspector(object):
"""
A helper class to inspect an `~matplotlib.artist.Artist` and return
information about its settable properties and their current values.
"""
def __init__(self, o):
r"""
Initialize the artist inspector with an `Artist` or an iterable of
`Artist`\s. If an iterable is used, we assume it is a homogeneous
sequence (all `Artists` are of the same type) and it is your
responsibility to make sure this is so.
"""
if not isinstance(o, Artist):
if np.iterable(o):
o = list(o)
if len(o):
o = o[0]
self.oorig = o
if not isinstance(o, type):
o = type(o)
self.o = o
self.aliasd = self.get_aliases()
def get_aliases(self):
"""
Get a dict mapping property fullnames to sets of aliases for each alias
in the :class:`~matplotlib.artist.ArtistInspector`.
e.g., for lines::
{'markerfacecolor': {'mfc'},
'linewidth' : {'lw'},
}
"""
names = [name for name in dir(self.o)
if name.startswith(('set_', 'get_'))
and callable(getattr(self.o, name))]
aliases = {}
for name in names:
func = getattr(self.o, name)
if not self.is_alias(func):
continue
propname = re.search("`({}.*)`".format(name[:4]), # get_.*/set_.*
inspect.getdoc(func)).group(1)
aliases.setdefault(propname[4:], set()).add(name[4:])
return aliases
_get_valid_values_regex = re.compile(
r"\n\s*(?:\.\.\s+)?ACCEPTS:\s*((?:.|\n)*?)(?:$|(?:\n\n))"
)
def get_valid_values(self, attr):
"""
Get the legal arguments for the setter associated with *attr*.
This is done by querying the docstring of the setter for a line that
begins with "ACCEPTS:" or ".. ACCEPTS:", and then by looking for a
numpydoc-style documentation for the setter's first argument.
"""
name = 'set_%s' % attr
if not hasattr(self.o, name):
raise AttributeError('%s has no function %s' % (self.o, name))
func = getattr(self.o, name)
docstring = inspect.getdoc(func)
if docstring is None:
return 'unknown'
if docstring.startswith('Alias for '):
return None
match = self._get_valid_values_regex.search(docstring)
if match is not None:
return re.sub("\n *", " ", match.group(1))
# Much faster than list(inspect.signature(func).parameters)[1],
# although barely relevant wrt. matplotlib's total import time.
param_name = func.__code__.co_varnames[1]
# We could set the presence * based on whether the parameter is a
# varargs (it can't be a varkwargs) but it's not really worth the it.
match = re.search(r"(?m)^ *\*?{} : (.+)".format(param_name), docstring)
if match:
return match.group(1)
return 'unknown'
def _get_setters_and_targets(self):
"""
Get the attribute strings and a full path to where the setter
is defined for all setters in an object.
"""
setters = []
for name in dir(self.o):
if not name.startswith('set_'):
continue
func = getattr(self.o, name)
if not callable(func):
continue
nargs = len(inspect.getfullargspec(func).args)
if nargs < 2 or self.is_alias(func):
continue
source_class = self.o.__module__ + "." + self.o.__name__
for cls in self.o.mro():
if name in cls.__dict__:
source_class = cls.__module__ + "." + cls.__name__
break
source_class = self._replace_path(source_class)
setters.append((name[4:], source_class + "." + name))
return setters
def _replace_path(self, source_class):
"""
Changes the full path to the public API path that is used
in sphinx. This is needed for links to work.
"""
replace_dict = {'_base._AxesBase': 'Axes',
'_axes.Axes': 'Axes'}
for key, value in replace_dict.items():
source_class = source_class.replace(key, value)
return source_class
def get_setters(self):
"""
Get the attribute strings with setters for object. e.g., for a line,
return ``['markerfacecolor', 'linewidth', ....]``.
"""
return [prop for prop, target in self._get_setters_and_targets()]
def is_alias(self, o):
"""Return whether method object *o* is an alias for another method."""
ds = inspect.getdoc(o)
if ds is None:
return False
return ds.startswith('Alias for ')
def aliased_name(self, s):
"""
Return 'PROPNAME or alias' if *s* has an alias, else return 'PROPNAME'.
e.g., for the line markerfacecolor property, which has an
alias, return 'markerfacecolor or mfc' and for the transform
property, which does not, return 'transform'.
"""
aliases = ''.join(' or %s' % x for x in sorted(self.aliasd.get(s, [])))
return s + aliases
def aliased_name_rest(self, s, target):
"""
Return 'PROPNAME or alias' if *s* has an alias, else return 'PROPNAME',
formatted for ReST.
e.g., for the line markerfacecolor property, which has an
alias, return 'markerfacecolor or mfc' and for the transform
property, which does not, return 'transform'.
"""
aliases = ''.join(' or %s' % x for x in sorted(self.aliasd.get(s, [])))
return ':meth:`%s <%s>`%s' % (s, target, aliases)
def pprint_setters(self, prop=None, leadingspace=2):
"""
If *prop* is *None*, return a list of strings of all settable
properties and their valid values.
If *prop* is not *None*, it is a valid property name and that
property will be returned as a string of property : valid
values.
"""
if leadingspace:
pad = ' ' * leadingspace
else:
pad = ''
if prop is not None:
accepts = self.get_valid_values(prop)
return '%s%s: %s' % (pad, prop, accepts)
attrs = self._get_setters_and_targets()
attrs.sort()
lines = []
for prop, path in attrs:
accepts = self.get_valid_values(prop)
name = self.aliased_name(prop)
lines.append('%s%s: %s' % (pad, name, accepts))
return lines
def pprint_setters_rest(self, prop=None, leadingspace=4):
"""
If *prop* is *None*, return a list of strings of all settable
properties and their valid values. Format the output for ReST
If *prop* is not *None*, it is a valid property name and that
property will be returned as a string of property : valid
values.
"""
if leadingspace:
pad = ' ' * leadingspace
else:
pad = ''
if prop is not None:
accepts = self.get_valid_values(prop)
return '%s%s: %s' % (pad, prop, accepts)
attrs = sorted(self._get_setters_and_targets())
names = [self.aliased_name_rest(prop, target)
for prop, target in attrs]
accepts = [self.get_valid_values(prop) for prop, target in attrs]
col0_len = max(len(n) for n in names)
col1_len = max(len(a) for a in accepts)
table_formatstr = pad + ' ' + '=' * col0_len + ' ' + '=' * col1_len
return [
'',
pad + '.. table::',
pad + ' :class: property-table',
'',
table_formatstr,
pad + ' ' + 'Property'.ljust(col0_len)
+ ' ' + 'Description'.ljust(col1_len),
table_formatstr,
*[pad + ' ' + n.ljust(col0_len) + ' ' + a.ljust(col1_len)
for n, a in zip(names, accepts)],
table_formatstr,
'',
]
def properties(self):
"""Return a dictionary mapping property name -> value."""
o = self.oorig
getters = [name for name in dir(o)
if name.startswith('get_') and callable(getattr(o, name))]
getters.sort()
d = {}
for name in getters:
func = getattr(o, name)
if self.is_alias(func):
continue
try:
with warnings.catch_warnings():
warnings.simplefilter('ignore')
val = func()
except Exception:
continue
else:
d[name[4:]] = val
return d
def pprint_getters(self):
"""Return the getters and actual values as list of strings."""
lines = []
for name, val in sorted(self.properties().items()):
if getattr(val, 'shape', ()) != () and len(val) > 6:
s = str(val[:6]) + '...'
else:
s = str(val)
s = s.replace('\n', ' ')
if len(s) > 50:
s = s[:50] + '...'
name = self.aliased_name(name)
lines.append(' %s = %s' % (name, s))
return lines
def getp(obj, property=None):
"""
Return the value of object's property. *property* is an optional string
for the property you want to return
Example usage::
getp(obj) # get all the object properties
getp(obj, 'linestyle') # get the linestyle property
*obj* is a :class:`Artist` instance, e.g.,
:class:`~matplotlib.lines.Line2D` or an instance of a
:class:`~matplotlib.axes.Axes` or :class:`matplotlib.text.Text`.
If the *property* is 'somename', this function returns
obj.get_somename()
:func:`getp` can be used to query all the gettable properties with
``getp(obj)``. Many properties have aliases for shorter typing, e.g.
'lw' is an alias for 'linewidth'. In the output, aliases and full
property names will be listed as:
property or alias = value
e.g.:
linewidth or lw = 2
"""
if property is None:
insp = ArtistInspector(obj)
ret = insp.pprint_getters()
print('\n'.join(ret))
return
func = getattr(obj, 'get_' + property)
return func()
# alias
get = getp
def setp(obj, *args, **kwargs):
"""
Set a property on an artist object.
matplotlib supports the use of :func:`setp` ("set property") and
:func:`getp` to set and get object properties, as well as to do
introspection on the object. For example, to set the linestyle of a
line to be dashed, you can do::
>>> line, = plot([1,2,3])
>>> setp(line, linestyle='--')
If you want to know the valid types of arguments, you can provide
the name of the property you want to set without a value::
>>> setp(line, 'linestyle')
linestyle: [ '-' | '--' | '-.' | ':' | 'steps' | 'None' ]
If you want to see all the properties that can be set, and their
possible values, you can do::
>>> setp(line)
... long output listing omitted
You may specify another output file to `setp` if `sys.stdout` is not
acceptable for some reason using the `file` keyword-only argument::
>>> with fopen('output.log') as f:
>>> setp(line, file=f)
:func:`setp` operates on a single instance or a iterable of
instances. If you are in query mode introspecting the possible
values, only the first instance in the sequence is used. When
actually setting values, all the instances will be set. e.g.,
suppose you have a list of two lines, the following will make both
lines thicker and red::
>>> x = arange(0,1.0,0.01)
>>> y1 = sin(2*pi*x)
>>> y2 = sin(4*pi*x)
>>> lines = plot(x, y1, x, y2)
>>> setp(lines, linewidth=2, color='r')
:func:`setp` works with the MATLAB style string/value pairs or
with python kwargs. For example, the following are equivalent::
>>> setp(lines, 'linewidth', 2, 'color', 'r') # MATLAB style
>>> setp(lines, linewidth=2, color='r') # python style
"""
if isinstance(obj, Artist):
objs = [obj]
else:
objs = list(cbook.flatten(obj))
if not objs:
return
insp = ArtistInspector(objs[0])
# file has to be popped before checking if kwargs is empty
printArgs = {}
if 'file' in kwargs:
printArgs['file'] = kwargs.pop('file')
if not kwargs and len(args) < 2:
if args:
print(insp.pprint_setters(prop=args[0]), **printArgs)
else:
print('\n'.join(insp.pprint_setters()), **printArgs)
return
if len(args) % 2:
raise ValueError('The set args must be string, value pairs')
# put args into ordereddict to maintain order
funcvals = OrderedDict((k, v) for k, v in zip(args[::2], args[1::2]))
ret = [o.update(funcvals) for o in objs] + [o.set(**kwargs) for o in objs]
return list(cbook.flatten(ret))
def kwdoc(artist):
r"""
Inspect an `~matplotlib.artist.Artist` class (using `.ArtistInspector`) and
return information about its settable properties and their current values.
Parameters
----------
artist : `~matplotlib.artist.Artist` or an iterable of `Artist`\s
Returns
-------
string
The settable properties of *artist*, as plain text if
:rc:`docstring.hardcopy` is False and as a rst table (intended for
use in Sphinx) if it is True.
"""
hardcopy = matplotlib.rcParams['docstring.hardcopy']
if hardcopy:
return '\n'.join(ArtistInspector(artist).pprint_setters_rest(
leadingspace=4))
else:
return '\n'.join(ArtistInspector(artist).pprint_setters(
leadingspace=2))
docstring.interpd.update(Artist=kwdoc(Artist))
|
4c9c9cc3d9f2cf921de188b9baf4d0896aa3d2a698d040f37b584aa6fcc57eb6
|
"""
This module contains functions to handle markers. Used by both the
marker functionality of `~matplotlib.axes.Axes.plot` and
`~matplotlib.axes.Axes.scatter`.
All possible markers are defined here:
============================== ====== =========================================
marker symbol description
============================== ====== =========================================
``"."`` |m00| point
``","`` |m01| pixel
``"o"`` |m02| circle
``"v"`` |m03| triangle_down
``"^"`` |m04| triangle_up
``"<"`` |m05| triangle_left
``">"`` |m06| triangle_right
``"1"`` |m07| tri_down
``"2"`` |m08| tri_up
``"3"`` |m09| tri_left
``"4"`` |m10| tri_right
``"8"`` |m11| octagon
``"s"`` |m12| square
``"p"`` |m13| pentagon
``"P"`` |m23| plus (filled)
``"*"`` |m14| star
``"h"`` |m15| hexagon1
``"H"`` |m16| hexagon2
``"+"`` |m17| plus
``"x"`` |m18| x
``"X"`` |m24| x (filled)
``"D"`` |m19| diamond
``"d"`` |m20| thin_diamond
``"|"`` |m21| vline
``"_"`` |m22| hline
``0`` (``TICKLEFT``) |m25| tickleft
``1`` (``TICKRIGHT``) |m26| tickright
``2`` (``TICKUP``) |m27| tickup
``3`` (``TICKDOWN``) |m28| tickdown
``4`` (``CARETLEFT``) |m29| caretleft
``5`` (``CARETRIGHT``) |m30| caretright
``6`` (``CARETUP``) |m31| caretup
``7`` (``CARETDOWN``) |m32| caretdown
``8`` (``CARETLEFTBASE``) |m33| caretleft (centered at base)
``9`` (``CARETRIGHTBASE``) |m34| caretright (centered at base)
``10`` (``CARETUPBASE``) |m35| caretup (centered at base)
``11`` (``CARETDOWNBASE``) |m36| caretdown (centered at base)
``"None"``, ``" "`` or ``""`` nothing
``'$...$'`` |m37| Render the string using mathtext.
E.g ``"$f$"`` for marker showing the
letter ``f``.
``verts`` A list of (x, y) pairs used for Path
vertices. The center of the marker is
located at (0,0) and the size is
normalized, such that the created path
is encapsulated inside the unit cell.
path A `~matplotlib.path.Path` instance.
``(numsides, style, angle)`` The marker can also be a tuple
``(numsides, style, angle)``, which
will create a custom, regular symbol.
``numsides``:
the number of sides
``style``:
the style of the regular symbol:
- 0: a regular polygon
- 1: a star-like symbol
- 2: an asterisk
- 3: a circle (``numsides`` and
``angle`` is ignored);
deprecated.
``angle``:
the angle of rotation of the symbol
============================== ====== =========================================
For backward compatibility, the form ``(verts, 0)`` is also accepted, but it is
deprecated and equivalent to just ``verts`` for giving a raw set of vertices
that define the shape.
``None`` is the default which means 'nothing', however this table is
referred to from other docs for the valid inputs from marker inputs and in
those cases ``None`` still means 'default'.
Note that special symbols can be defined via the
:doc:`STIX math font </tutorials/text/mathtext>`,
e.g. ``"$\u266B$"``. For an overview over the STIX font symbols refer to the
`STIX font table <http://www.stixfonts.org/allGlyphs.html>`_.
Also see the :doc:`/gallery/text_labels_and_annotations/stix_fonts_demo`.
Integer numbers from ``0`` to ``11`` create lines and triangles. Those are
equally accessible via capitalized variables, like ``CARETDOWNBASE``.
Hence the following are equivalent::
plt.plot([1,2,3], marker=11)
plt.plot([1,2,3], marker=matplotlib.markers.CARETDOWNBASE)
Examples showing the use of markers:
* :doc:`/gallery/lines_bars_and_markers/marker_reference`
* :doc:`/gallery/lines_bars_and_markers/marker_fillstyle_reference`
* :doc:`/gallery/shapes_and_collections/marker_path`
.. |m00| image:: /_static/markers/m00.png
.. |m01| image:: /_static/markers/m01.png
.. |m02| image:: /_static/markers/m02.png
.. |m03| image:: /_static/markers/m03.png
.. |m04| image:: /_static/markers/m04.png
.. |m05| image:: /_static/markers/m05.png
.. |m06| image:: /_static/markers/m06.png
.. |m07| image:: /_static/markers/m07.png
.. |m08| image:: /_static/markers/m08.png
.. |m09| image:: /_static/markers/m09.png
.. |m10| image:: /_static/markers/m10.png
.. |m11| image:: /_static/markers/m11.png
.. |m12| image:: /_static/markers/m12.png
.. |m13| image:: /_static/markers/m13.png
.. |m14| image:: /_static/markers/m14.png
.. |m15| image:: /_static/markers/m15.png
.. |m16| image:: /_static/markers/m16.png
.. |m17| image:: /_static/markers/m17.png
.. |m18| image:: /_static/markers/m18.png
.. |m19| image:: /_static/markers/m19.png
.. |m20| image:: /_static/markers/m20.png
.. |m21| image:: /_static/markers/m21.png
.. |m22| image:: /_static/markers/m22.png
.. |m23| image:: /_static/markers/m23.png
.. |m24| image:: /_static/markers/m24.png
.. |m25| image:: /_static/markers/m25.png
.. |m26| image:: /_static/markers/m26.png
.. |m27| image:: /_static/markers/m27.png
.. |m28| image:: /_static/markers/m28.png
.. |m29| image:: /_static/markers/m29.png
.. |m30| image:: /_static/markers/m30.png
.. |m31| image:: /_static/markers/m31.png
.. |m32| image:: /_static/markers/m32.png
.. |m33| image:: /_static/markers/m33.png
.. |m34| image:: /_static/markers/m34.png
.. |m35| image:: /_static/markers/m35.png
.. |m36| image:: /_static/markers/m36.png
.. |m37| image:: /_static/markers/m37.png
"""
from collections.abc import Sized
from numbers import Number
import numpy as np
from . import cbook, rcParams
from .path import Path
from .transforms import IdentityTransform, Affine2D
# special-purpose marker identifiers:
(TICKLEFT, TICKRIGHT, TICKUP, TICKDOWN,
CARETLEFT, CARETRIGHT, CARETUP, CARETDOWN,
CARETLEFTBASE, CARETRIGHTBASE, CARETUPBASE, CARETDOWNBASE) = range(12)
_empty_path = Path(np.empty((0, 2)))
class MarkerStyle(object):
markers = {
'.': 'point',
',': 'pixel',
'o': 'circle',
'v': 'triangle_down',
'^': 'triangle_up',
'<': 'triangle_left',
'>': 'triangle_right',
'1': 'tri_down',
'2': 'tri_up',
'3': 'tri_left',
'4': 'tri_right',
'8': 'octagon',
's': 'square',
'p': 'pentagon',
'*': 'star',
'h': 'hexagon1',
'H': 'hexagon2',
'+': 'plus',
'x': 'x',
'D': 'diamond',
'd': 'thin_diamond',
'|': 'vline',
'_': 'hline',
'P': 'plus_filled',
'X': 'x_filled',
TICKLEFT: 'tickleft',
TICKRIGHT: 'tickright',
TICKUP: 'tickup',
TICKDOWN: 'tickdown',
CARETLEFT: 'caretleft',
CARETRIGHT: 'caretright',
CARETUP: 'caretup',
CARETDOWN: 'caretdown',
CARETLEFTBASE: 'caretleftbase',
CARETRIGHTBASE: 'caretrightbase',
CARETUPBASE: 'caretupbase',
CARETDOWNBASE: 'caretdownbase',
"None": 'nothing',
None: 'nothing',
' ': 'nothing',
'': 'nothing'
}
# Just used for informational purposes. is_filled()
# is calculated in the _set_* functions.
filled_markers = (
'o', 'v', '^', '<', '>', '8', 's', 'p', '*', 'h', 'H', 'D', 'd',
'P', 'X')
fillstyles = ('full', 'left', 'right', 'bottom', 'top', 'none')
_half_fillstyles = ('left', 'right', 'bottom', 'top')
# TODO: Is this ever used as a non-constant?
_point_size_reduction = 0.5
def __init__(self, marker=None, fillstyle=None):
"""
Attributes
----------
markers : list of known marks
fillstyles : list of known fillstyles
filled_markers : list of known filled markers.
Parameters
----------
marker : string or array_like, optional, default: None
See the descriptions of possible markers in the module docstring.
fillstyle : string, optional, default: 'full'
'full', 'left", 'right', 'bottom', 'top', 'none'
"""
self._marker_function = None
self.set_fillstyle(fillstyle)
self.set_marker(marker)
def _recache(self):
if self._marker_function is None:
return
self._path = _empty_path
self._transform = IdentityTransform()
self._alt_path = None
self._alt_transform = None
self._snap_threshold = None
self._joinstyle = 'round'
self._capstyle = 'butt'
self._filled = True
self._marker_function()
def __bool__(self):
return bool(len(self._path.vertices))
def is_filled(self):
return self._filled
def get_fillstyle(self):
return self._fillstyle
def set_fillstyle(self, fillstyle):
"""
Sets fillstyle
Parameters
----------
fillstyle : string amongst known fillstyles
"""
if fillstyle is None:
fillstyle = rcParams['markers.fillstyle']
if fillstyle not in self.fillstyles:
raise ValueError("Unrecognized fillstyle %s"
% ' '.join(self.fillstyles))
self._fillstyle = fillstyle
self._recache()
def get_joinstyle(self):
return self._joinstyle
def get_capstyle(self):
return self._capstyle
def get_marker(self):
return self._marker
def set_marker(self, marker):
if (isinstance(marker, np.ndarray) and marker.ndim == 2 and
marker.shape[1] == 2):
self._marker_function = self._set_vertices
elif isinstance(marker, str) and cbook.is_math_text(marker):
self._marker_function = self._set_mathtext_path
elif isinstance(marker, Path):
self._marker_function = self._set_path_marker
elif (isinstance(marker, Sized) and len(marker) in (2, 3) and
marker[1] in (0, 1, 2, 3)):
self._marker_function = self._set_tuple_marker
elif (not isinstance(marker, (np.ndarray, list)) and
marker in self.markers):
self._marker_function = getattr(
self, '_set_' + self.markers[marker])
else:
try:
Path(marker)
self._marker_function = self._set_vertices
except ValueError:
raise ValueError('Unrecognized marker style {!r}'
.format(marker))
self._marker = marker
self._recache()
def get_path(self):
return self._path
def get_transform(self):
return self._transform.frozen()
def get_alt_path(self):
return self._alt_path
def get_alt_transform(self):
return self._alt_transform.frozen()
def get_snap_threshold(self):
return self._snap_threshold
def _set_nothing(self):
self._filled = False
def _set_custom_marker(self, path):
verts = path.vertices
rescale = max(np.max(np.abs(verts[:, 0])),
np.max(np.abs(verts[:, 1])))
self._transform = Affine2D().scale(0.5 / rescale)
self._path = path
def _set_path_marker(self):
self._set_custom_marker(self._marker)
def _set_vertices(self):
verts = self._marker
marker = Path(verts)
self._set_custom_marker(marker)
def _set_tuple_marker(self):
marker = self._marker
if isinstance(marker[0], Number):
if len(marker) == 2:
numsides, rotation = marker[0], 0.0
elif len(marker) == 3:
numsides, rotation = marker[0], marker[2]
symstyle = marker[1]
if symstyle == 0:
self._path = Path.unit_regular_polygon(numsides)
self._joinstyle = 'miter'
elif symstyle == 1:
self._path = Path.unit_regular_star(numsides)
self._joinstyle = 'bevel'
elif symstyle == 2:
self._path = Path.unit_regular_asterisk(numsides)
self._filled = False
self._joinstyle = 'bevel'
elif symstyle == 3:
cbook.warn_deprecated(
"3.0", message="Setting a circle marker using `(..., 3)` "
"is deprecated since Matplotlib 3.0, and support for it "
"will be removed in 3.2. Directly pass 'o' instead.")
self._path = Path.unit_circle()
self._transform = Affine2D().scale(0.5).rotate_deg(rotation)
else:
cbook.warn_deprecated(
"3.0", message="Passing vertices as `(verts, 0)` is "
"deprecated since Matplotlib 3.0, and support for it will be "
"removed in 3.2. Directly pass `verts` instead.")
verts = np.asarray(marker[0])
path = Path(verts)
self._set_custom_marker(path)
def _set_mathtext_path(self):
"""
Draws mathtext markers '$...$' using TextPath object.
Submitted by tcb
"""
from matplotlib.text import TextPath
from matplotlib.font_manager import FontProperties
# again, the properties could be initialised just once outside
# this function
text = TextPath(xy=(0, 0), s=self.get_marker(),
usetex=rcParams['text.usetex'])
if len(text.vertices) == 0:
return
xmin, ymin = text.vertices.min(axis=0)
xmax, ymax = text.vertices.max(axis=0)
width = xmax - xmin
height = ymax - ymin
max_dim = max(width, height)
self._transform = Affine2D() \
.translate(-xmin + 0.5 * -width, -ymin + 0.5 * -height) \
.scale(1.0 / max_dim)
self._path = text
self._snap = False
def _half_fill(self):
fs = self.get_fillstyle()
result = fs in self._half_fillstyles
return result
def _set_circle(self, reduction=1.0):
self._transform = Affine2D().scale(0.5 * reduction)
self._snap_threshold = np.inf
fs = self.get_fillstyle()
if not self._half_fill():
self._path = Path.unit_circle()
else:
# build a right-half circle
if fs == 'bottom':
rotate = 270.
elif fs == 'top':
rotate = 90.
elif fs == 'left':
rotate = 180.
else:
rotate = 0.
self._path = self._alt_path = Path.unit_circle_righthalf()
self._transform.rotate_deg(rotate)
self._alt_transform = self._transform.frozen().rotate_deg(180.)
def _set_pixel(self):
self._path = Path.unit_rectangle()
# Ideally, you'd want -0.5, -0.5 here, but then the snapping
# algorithm in the Agg backend will round this to a 2x2
# rectangle from (-1, -1) to (1, 1). By offsetting it
# slightly, we can force it to be (0, 0) to (1, 1), which both
# makes it only be a single pixel and places it correctly
# aligned to 1-width stroking (i.e. the ticks). This hack is
# the best of a number of bad alternatives, mainly because the
# backends are not aware of what marker is actually being used
# beyond just its path data.
self._transform = Affine2D().translate(-0.49999, -0.49999)
self._snap_threshold = None
def _set_point(self):
self._set_circle(reduction=self._point_size_reduction)
_triangle_path = Path(
[[0.0, 1.0], [-1.0, -1.0], [1.0, -1.0], [0.0, 1.0]],
[Path.MOVETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY])
# Going down halfway looks to small. Golden ratio is too far.
_triangle_path_u = Path(
[[0.0, 1.0], [-3 / 5., -1 / 5.], [3 / 5., -1 / 5.], [0.0, 1.0]],
[Path.MOVETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY])
_triangle_path_d = Path(
[[-3 / 5., -1 / 5.], [3 / 5., -1 / 5.], [1.0, -1.0], [-1.0, -1.0],
[-3 / 5., -1 / 5.]],
[Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY])
_triangle_path_l = Path(
[[0.0, 1.0], [0.0, -1.0], [-1.0, -1.0], [0.0, 1.0]],
[Path.MOVETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY])
_triangle_path_r = Path(
[[0.0, 1.0], [0.0, -1.0], [1.0, -1.0], [0.0, 1.0]],
[Path.MOVETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY])
def _set_triangle(self, rot, skip):
self._transform = Affine2D().scale(0.5, 0.5).rotate_deg(rot)
self._snap_threshold = 5.0
fs = self.get_fillstyle()
if not self._half_fill():
self._path = self._triangle_path
else:
mpaths = [self._triangle_path_u,
self._triangle_path_l,
self._triangle_path_d,
self._triangle_path_r]
if fs == 'top':
self._path = mpaths[(0 + skip) % 4]
self._alt_path = mpaths[(2 + skip) % 4]
elif fs == 'bottom':
self._path = mpaths[(2 + skip) % 4]
self._alt_path = mpaths[(0 + skip) % 4]
elif fs == 'left':
self._path = mpaths[(1 + skip) % 4]
self._alt_path = mpaths[(3 + skip) % 4]
else:
self._path = mpaths[(3 + skip) % 4]
self._alt_path = mpaths[(1 + skip) % 4]
self._alt_transform = self._transform
self._joinstyle = 'miter'
def _set_triangle_up(self):
return self._set_triangle(0.0, 0)
def _set_triangle_down(self):
return self._set_triangle(180.0, 2)
def _set_triangle_left(self):
return self._set_triangle(90.0, 3)
def _set_triangle_right(self):
return self._set_triangle(270.0, 1)
def _set_square(self):
self._transform = Affine2D().translate(-0.5, -0.5)
self._snap_threshold = 2.0
fs = self.get_fillstyle()
if not self._half_fill():
self._path = Path.unit_rectangle()
else:
# build a bottom filled square out of two rectangles, one
# filled. Use the rotation to support left, right, bottom
# or top
if fs == 'bottom':
rotate = 0.
elif fs == 'top':
rotate = 180.
elif fs == 'left':
rotate = 270.
else:
rotate = 90.
self._path = Path([[0.0, 0.0], [1.0, 0.0], [1.0, 0.5],
[0.0, 0.5], [0.0, 0.0]])
self._alt_path = Path([[0.0, 0.5], [1.0, 0.5], [1.0, 1.0],
[0.0, 1.0], [0.0, 0.5]])
self._transform.rotate_deg(rotate)
self._alt_transform = self._transform
self._joinstyle = 'miter'
def _set_diamond(self):
self._transform = Affine2D().translate(-0.5, -0.5).rotate_deg(45)
self._snap_threshold = 5.0
fs = self.get_fillstyle()
if not self._half_fill():
self._path = Path.unit_rectangle()
else:
self._path = Path([[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 0.0]])
self._alt_path = Path([[0.0, 0.0], [0.0, 1.0],
[1.0, 1.0], [0.0, 0.0]])
if fs == 'bottom':
rotate = 270.
elif fs == 'top':
rotate = 90.
elif fs == 'left':
rotate = 180.
else:
rotate = 0.
self._transform.rotate_deg(rotate)
self._alt_transform = self._transform
self._joinstyle = 'miter'
def _set_thin_diamond(self):
self._set_diamond()
self._transform.scale(0.6, 1.0)
def _set_pentagon(self):
self._transform = Affine2D().scale(0.5)
self._snap_threshold = 5.0
polypath = Path.unit_regular_polygon(5)
fs = self.get_fillstyle()
if not self._half_fill():
self._path = polypath
else:
verts = polypath.vertices
y = (1 + np.sqrt(5)) / 4.
top = Path([verts[0], verts[1], verts[4], verts[0]])
bottom = Path([verts[1], verts[2], verts[3], verts[4], verts[1]])
left = Path([verts[0], verts[1], verts[2], [0, -y], verts[0]])
right = Path([verts[0], verts[4], verts[3], [0, -y], verts[0]])
if fs == 'top':
mpath, mpath_alt = top, bottom
elif fs == 'bottom':
mpath, mpath_alt = bottom, top
elif fs == 'left':
mpath, mpath_alt = left, right
else:
mpath, mpath_alt = right, left
self._path = mpath
self._alt_path = mpath_alt
self._alt_transform = self._transform
self._joinstyle = 'miter'
def _set_star(self):
self._transform = Affine2D().scale(0.5)
self._snap_threshold = 5.0
fs = self.get_fillstyle()
polypath = Path.unit_regular_star(5, innerCircle=0.381966)
if not self._half_fill():
self._path = polypath
else:
verts = polypath.vertices
top = Path(np.vstack((verts[0:4, :], verts[7:10, :], verts[0])))
bottom = Path(np.vstack((verts[3:8, :], verts[3])))
left = Path(np.vstack((verts[0:6, :], verts[0])))
right = Path(np.vstack((verts[0], verts[5:10, :], verts[0])))
if fs == 'top':
mpath, mpath_alt = top, bottom
elif fs == 'bottom':
mpath, mpath_alt = bottom, top
elif fs == 'left':
mpath, mpath_alt = left, right
else:
mpath, mpath_alt = right, left
self._path = mpath
self._alt_path = mpath_alt
self._alt_transform = self._transform
self._joinstyle = 'bevel'
def _set_hexagon1(self):
self._transform = Affine2D().scale(0.5)
self._snap_threshold = None
fs = self.get_fillstyle()
polypath = Path.unit_regular_polygon(6)
if not self._half_fill():
self._path = polypath
else:
verts = polypath.vertices
# not drawing inside lines
x = np.abs(np.cos(5 * np.pi / 6.))
top = Path(np.vstack(([-x, 0], verts[(1, 0, 5), :], [x, 0])))
bottom = Path(np.vstack(([-x, 0], verts[2:5, :], [x, 0])))
left = Path(verts[(0, 1, 2, 3), :])
right = Path(verts[(0, 5, 4, 3), :])
if fs == 'top':
mpath, mpath_alt = top, bottom
elif fs == 'bottom':
mpath, mpath_alt = bottom, top
elif fs == 'left':
mpath, mpath_alt = left, right
else:
mpath, mpath_alt = right, left
self._path = mpath
self._alt_path = mpath_alt
self._alt_transform = self._transform
self._joinstyle = 'miter'
def _set_hexagon2(self):
self._transform = Affine2D().scale(0.5).rotate_deg(30)
self._snap_threshold = None
fs = self.get_fillstyle()
polypath = Path.unit_regular_polygon(6)
if not self._half_fill():
self._path = polypath
else:
verts = polypath.vertices
# not drawing inside lines
x, y = np.sqrt(3) / 4, 3 / 4.
top = Path(verts[(1, 0, 5, 4, 1), :])
bottom = Path(verts[(1, 2, 3, 4), :])
left = Path(np.vstack(([x, y], verts[(0, 1, 2), :],
[-x, -y], [x, y])))
right = Path(np.vstack(([x, y], verts[(5, 4, 3), :], [-x, -y])))
if fs == 'top':
mpath, mpath_alt = top, bottom
elif fs == 'bottom':
mpath, mpath_alt = bottom, top
elif fs == 'left':
mpath, mpath_alt = left, right
else:
mpath, mpath_alt = right, left
self._path = mpath
self._alt_path = mpath_alt
self._alt_transform = self._transform
self._joinstyle = 'miter'
def _set_octagon(self):
self._transform = Affine2D().scale(0.5)
self._snap_threshold = 5.0
fs = self.get_fillstyle()
polypath = Path.unit_regular_polygon(8)
if not self._half_fill():
self._transform.rotate_deg(22.5)
self._path = polypath
else:
x = np.sqrt(2.) / 4.
half = Path([[0, -1], [0, 1], [-x, 1], [-1, x],
[-1, -x], [-x, -1], [0, -1]])
if fs == 'bottom':
rotate = 90.
elif fs == 'top':
rotate = 270.
elif fs == 'right':
rotate = 180.
else:
rotate = 0.
self._transform.rotate_deg(rotate)
self._path = self._alt_path = half
self._alt_transform = self._transform.frozen().rotate_deg(180.0)
self._joinstyle = 'miter'
_line_marker_path = Path([[0.0, -1.0], [0.0, 1.0]])
def _set_vline(self):
self._transform = Affine2D().scale(0.5)
self._snap_threshold = 1.0
self._filled = False
self._path = self._line_marker_path
def _set_hline(self):
self._set_vline()
self._transform = self._transform.rotate_deg(90)
_tickhoriz_path = Path([[0.0, 0.0], [1.0, 0.0]])
def _set_tickleft(self):
self._transform = Affine2D().scale(-1.0, 1.0)
self._snap_threshold = 1.0
self._filled = False
self._path = self._tickhoriz_path
def _set_tickright(self):
self._transform = Affine2D().scale(1.0, 1.0)
self._snap_threshold = 1.0
self._filled = False
self._path = self._tickhoriz_path
_tickvert_path = Path([[-0.0, 0.0], [-0.0, 1.0]])
def _set_tickup(self):
self._transform = Affine2D().scale(1.0, 1.0)
self._snap_threshold = 1.0
self._filled = False
self._path = self._tickvert_path
def _set_tickdown(self):
self._transform = Affine2D().scale(1.0, -1.0)
self._snap_threshold = 1.0
self._filled = False
self._path = self._tickvert_path
_tri_path = Path([[0.0, 0.0], [0.0, -1.0],
[0.0, 0.0], [0.8, 0.5],
[0.0, 0.0], [-0.8, 0.5]],
[Path.MOVETO, Path.LINETO,
Path.MOVETO, Path.LINETO,
Path.MOVETO, Path.LINETO])
def _set_tri_down(self):
self._transform = Affine2D().scale(0.5)
self._snap_threshold = 5.0
self._filled = False
self._path = self._tri_path
def _set_tri_up(self):
self._set_tri_down()
self._transform = self._transform.rotate_deg(180)
def _set_tri_left(self):
self._set_tri_down()
self._transform = self._transform.rotate_deg(270)
def _set_tri_right(self):
self._set_tri_down()
self._transform = self._transform.rotate_deg(90)
_caret_path = Path([[-1.0, 1.5], [0.0, 0.0], [1.0, 1.5]])
def _set_caretdown(self):
self._transform = Affine2D().scale(0.5)
self._snap_threshold = 3.0
self._filled = False
self._path = self._caret_path
self._joinstyle = 'miter'
def _set_caretup(self):
self._set_caretdown()
self._transform = self._transform.rotate_deg(180)
def _set_caretleft(self):
self._set_caretdown()
self._transform = self._transform.rotate_deg(270)
def _set_caretright(self):
self._set_caretdown()
self._transform = self._transform.rotate_deg(90)
_caret_path_base = Path([[-1.0, 0.0], [0.0, -1.5], [1.0, 0]])
def _set_caretdownbase(self):
self._set_caretdown()
self._path = self._caret_path_base
def _set_caretupbase(self):
self._set_caretdownbase()
self._transform = self._transform.rotate_deg(180)
def _set_caretleftbase(self):
self._set_caretdownbase()
self._transform = self._transform.rotate_deg(270)
def _set_caretrightbase(self):
self._set_caretdownbase()
self._transform = self._transform.rotate_deg(90)
_plus_path = Path([[-1.0, 0.0], [1.0, 0.0],
[0.0, -1.0], [0.0, 1.0]],
[Path.MOVETO, Path.LINETO,
Path.MOVETO, Path.LINETO])
def _set_plus(self):
self._transform = Affine2D().scale(0.5)
self._snap_threshold = 1.0
self._filled = False
self._path = self._plus_path
_x_path = Path([[-1.0, -1.0], [1.0, 1.0],
[-1.0, 1.0], [1.0, -1.0]],
[Path.MOVETO, Path.LINETO,
Path.MOVETO, Path.LINETO])
def _set_x(self):
self._transform = Affine2D().scale(0.5)
self._snap_threshold = 3.0
self._filled = False
self._path = self._x_path
_plus_filled_path = Path([(1/3, 0), (2/3, 0), (2/3, 1/3),
(1, 1/3), (1, 2/3), (2/3, 2/3),
(2/3, 1), (1/3, 1), (1/3, 2/3),
(0, 2/3), (0, 1/3), (1/3, 1/3),
(1/3, 0)],
[Path.MOVETO, Path.LINETO, Path.LINETO,
Path.LINETO, Path.LINETO, Path.LINETO,
Path.LINETO, Path.LINETO, Path.LINETO,
Path.LINETO, Path.LINETO, Path.LINETO,
Path.CLOSEPOLY])
_plus_filled_path_t = Path([(1, 1/2), (1, 2/3), (2/3, 2/3),
(2/3, 1), (1/3, 1), (1/3, 2/3),
(0, 2/3), (0, 1/2), (1, 1/2)],
[Path.MOVETO, Path.LINETO, Path.LINETO,
Path.LINETO, Path.LINETO, Path.LINETO,
Path.LINETO, Path.LINETO,
Path.CLOSEPOLY])
def _set_plus_filled(self):
self._transform = Affine2D().translate(-0.5, -0.5)
self._snap_threshold = 5.0
self._joinstyle = 'miter'
fs = self.get_fillstyle()
if not self._half_fill():
self._path = self._plus_filled_path
else:
# Rotate top half path to support all partitions
if fs == 'top':
rotate, rotate_alt = 0, 180
elif fs == 'bottom':
rotate, rotate_alt = 180, 0
elif fs == 'left':
rotate, rotate_alt = 90, 270
else:
rotate, rotate_alt = 270, 90
self._path = self._plus_filled_path_t
self._alt_path = self._plus_filled_path_t
self._alt_transform = Affine2D().translate(-0.5, -0.5)
self._transform.rotate_deg(rotate)
self._alt_transform.rotate_deg(rotate_alt)
_x_filled_path = Path([(0.25, 0), (0.5, 0.25), (0.75, 0), (1, 0.25),
(0.75, 0.5), (1, 0.75), (0.75, 1), (0.5, 0.75),
(0.25, 1), (0, 0.75), (0.25, 0.5), (0, 0.25),
(0.25, 0)],
[Path.MOVETO, Path.LINETO, Path.LINETO,
Path.LINETO, Path.LINETO, Path.LINETO,
Path.LINETO, Path.LINETO, Path.LINETO,
Path.LINETO, Path.LINETO, Path.LINETO,
Path.CLOSEPOLY])
_x_filled_path_t = Path([(0.75, 0.5), (1, 0.75), (0.75, 1),
(0.5, 0.75), (0.25, 1), (0, 0.75),
(0.25, 0.5), (0.75, 0.5)],
[Path.MOVETO, Path.LINETO, Path.LINETO,
Path.LINETO, Path.LINETO, Path.LINETO,
Path.LINETO, Path.CLOSEPOLY])
def _set_x_filled(self):
self._transform = Affine2D().translate(-0.5, -0.5)
self._snap_threshold = 5.0
self._joinstyle = 'miter'
fs = self.get_fillstyle()
if not self._half_fill():
self._path = self._x_filled_path
else:
# Rotate top half path to support all partitions
if fs == 'top':
rotate, rotate_alt = 0, 180
elif fs == 'bottom':
rotate, rotate_alt = 180, 0
elif fs == 'left':
rotate, rotate_alt = 90, 270
else:
rotate, rotate_alt = 270, 90
self._path = self._x_filled_path_t
self._alt_path = self._x_filled_path_t
self._alt_transform = Affine2D().translate(-0.5, -0.5)
self._transform.rotate_deg(rotate)
self._alt_transform.rotate_deg(rotate_alt)
|
b798b24e514d7337d97708b378d8398d3fc00ed3c017556b75365944504b2bd6
|
"""
Manage figures for pyplot interface.
"""
import atexit
import gc
class Gcf(object):
"""
Singleton to manage a set of integer-numbered figures.
This class is never instantiated; it consists of two class
attributes (a list and a dictionary), and a set of static
methods that operate on those attributes, accessing them
directly as class attributes.
Attributes:
*figs*:
dictionary of the form {*num*: *manager*, ...}
*_activeQue*:
list of *managers*, with active one at the end
"""
_activeQue = []
figs = {}
@classmethod
def get_fig_manager(cls, num):
"""
If figure manager *num* exists, make it the active
figure and return the manager; otherwise return *None*.
"""
manager = cls.figs.get(num, None)
if manager is not None:
cls.set_active(manager)
return manager
@classmethod
def destroy(cls, num):
"""
Try to remove all traces of figure *num*.
In the interactive backends, this is bound to the
window "destroy" and "delete" events.
"""
if not cls.has_fignum(num):
return
manager = cls.figs[num]
manager.canvas.mpl_disconnect(manager._cidgcf)
cls._activeQue.remove(manager)
del cls.figs[num]
manager.destroy()
gc.collect(1)
@classmethod
def destroy_fig(cls, fig):
"*fig* is a Figure instance"
num = next((manager.num for manager in cls.figs.values()
if manager.canvas.figure == fig), None)
if num is not None:
cls.destroy(num)
@classmethod
def destroy_all(cls):
# this is need to ensure that gc is available in corner cases
# where modules are being torn down after install with easy_install
import gc # noqa
for manager in list(cls.figs.values()):
manager.canvas.mpl_disconnect(manager._cidgcf)
manager.destroy()
cls._activeQue = []
cls.figs.clear()
gc.collect(1)
@classmethod
def has_fignum(cls, num):
"""
Return *True* if figure *num* exists.
"""
return num in cls.figs
@classmethod
def get_all_fig_managers(cls):
"""
Return a list of figure managers.
"""
return list(cls.figs.values())
@classmethod
def get_num_fig_managers(cls):
"""
Return the number of figures being managed.
"""
return len(cls.figs)
@classmethod
def get_active(cls):
"""
Return the manager of the active figure, or *None*.
"""
if len(cls._activeQue) == 0:
return None
else:
return cls._activeQue[-1]
@classmethod
def set_active(cls, manager):
"""
Make the figure corresponding to *manager* the active one.
"""
oldQue = cls._activeQue[:]
cls._activeQue = [m for m in oldQue if m != manager]
cls._activeQue.append(manager)
cls.figs[manager.num] = manager
@classmethod
def draw_all(cls, force=False):
"""
Redraw all figures registered with the pyplot
state machine.
"""
for f_mgr in cls.get_all_fig_managers():
if force or f_mgr.canvas.figure.stale:
f_mgr.canvas.draw_idle()
atexit.register(Gcf.destroy_all)
|
1294e343aa59f44fd4798e240dae9f53dcdafd51c1be1b8e9821ba7f0351be59
|
from .colors import ListedColormap
_magma_data = [[0.001462, 0.000466, 0.013866],
[0.002258, 0.001295, 0.018331],
[0.003279, 0.002305, 0.023708],
[0.004512, 0.003490, 0.029965],
[0.005950, 0.004843, 0.037130],
[0.007588, 0.006356, 0.044973],
[0.009426, 0.008022, 0.052844],
[0.011465, 0.009828, 0.060750],
[0.013708, 0.011771, 0.068667],
[0.016156, 0.013840, 0.076603],
[0.018815, 0.016026, 0.084584],
[0.021692, 0.018320, 0.092610],
[0.024792, 0.020715, 0.100676],
[0.028123, 0.023201, 0.108787],
[0.031696, 0.025765, 0.116965],
[0.035520, 0.028397, 0.125209],
[0.039608, 0.031090, 0.133515],
[0.043830, 0.033830, 0.141886],
[0.048062, 0.036607, 0.150327],
[0.052320, 0.039407, 0.158841],
[0.056615, 0.042160, 0.167446],
[0.060949, 0.044794, 0.176129],
[0.065330, 0.047318, 0.184892],
[0.069764, 0.049726, 0.193735],
[0.074257, 0.052017, 0.202660],
[0.078815, 0.054184, 0.211667],
[0.083446, 0.056225, 0.220755],
[0.088155, 0.058133, 0.229922],
[0.092949, 0.059904, 0.239164],
[0.097833, 0.061531, 0.248477],
[0.102815, 0.063010, 0.257854],
[0.107899, 0.064335, 0.267289],
[0.113094, 0.065492, 0.276784],
[0.118405, 0.066479, 0.286321],
[0.123833, 0.067295, 0.295879],
[0.129380, 0.067935, 0.305443],
[0.135053, 0.068391, 0.315000],
[0.140858, 0.068654, 0.324538],
[0.146785, 0.068738, 0.334011],
[0.152839, 0.068637, 0.343404],
[0.159018, 0.068354, 0.352688],
[0.165308, 0.067911, 0.361816],
[0.171713, 0.067305, 0.370771],
[0.178212, 0.066576, 0.379497],
[0.184801, 0.065732, 0.387973],
[0.191460, 0.064818, 0.396152],
[0.198177, 0.063862, 0.404009],
[0.204935, 0.062907, 0.411514],
[0.211718, 0.061992, 0.418647],
[0.218512, 0.061158, 0.425392],
[0.225302, 0.060445, 0.431742],
[0.232077, 0.059889, 0.437695],
[0.238826, 0.059517, 0.443256],
[0.245543, 0.059352, 0.448436],
[0.252220, 0.059415, 0.453248],
[0.258857, 0.059706, 0.457710],
[0.265447, 0.060237, 0.461840],
[0.271994, 0.060994, 0.465660],
[0.278493, 0.061978, 0.469190],
[0.284951, 0.063168, 0.472451],
[0.291366, 0.064553, 0.475462],
[0.297740, 0.066117, 0.478243],
[0.304081, 0.067835, 0.480812],
[0.310382, 0.069702, 0.483186],
[0.316654, 0.071690, 0.485380],
[0.322899, 0.073782, 0.487408],
[0.329114, 0.075972, 0.489287],
[0.335308, 0.078236, 0.491024],
[0.341482, 0.080564, 0.492631],
[0.347636, 0.082946, 0.494121],
[0.353773, 0.085373, 0.495501],
[0.359898, 0.087831, 0.496778],
[0.366012, 0.090314, 0.497960],
[0.372116, 0.092816, 0.499053],
[0.378211, 0.095332, 0.500067],
[0.384299, 0.097855, 0.501002],
[0.390384, 0.100379, 0.501864],
[0.396467, 0.102902, 0.502658],
[0.402548, 0.105420, 0.503386],
[0.408629, 0.107930, 0.504052],
[0.414709, 0.110431, 0.504662],
[0.420791, 0.112920, 0.505215],
[0.426877, 0.115395, 0.505714],
[0.432967, 0.117855, 0.506160],
[0.439062, 0.120298, 0.506555],
[0.445163, 0.122724, 0.506901],
[0.451271, 0.125132, 0.507198],
[0.457386, 0.127522, 0.507448],
[0.463508, 0.129893, 0.507652],
[0.469640, 0.132245, 0.507809],
[0.475780, 0.134577, 0.507921],
[0.481929, 0.136891, 0.507989],
[0.488088, 0.139186, 0.508011],
[0.494258, 0.141462, 0.507988],
[0.500438, 0.143719, 0.507920],
[0.506629, 0.145958, 0.507806],
[0.512831, 0.148179, 0.507648],
[0.519045, 0.150383, 0.507443],
[0.525270, 0.152569, 0.507192],
[0.531507, 0.154739, 0.506895],
[0.537755, 0.156894, 0.506551],
[0.544015, 0.159033, 0.506159],
[0.550287, 0.161158, 0.505719],
[0.556571, 0.163269, 0.505230],
[0.562866, 0.165368, 0.504692],
[0.569172, 0.167454, 0.504105],
[0.575490, 0.169530, 0.503466],
[0.581819, 0.171596, 0.502777],
[0.588158, 0.173652, 0.502035],
[0.594508, 0.175701, 0.501241],
[0.600868, 0.177743, 0.500394],
[0.607238, 0.179779, 0.499492],
[0.613617, 0.181811, 0.498536],
[0.620005, 0.183840, 0.497524],
[0.626401, 0.185867, 0.496456],
[0.632805, 0.187893, 0.495332],
[0.639216, 0.189921, 0.494150],
[0.645633, 0.191952, 0.492910],
[0.652056, 0.193986, 0.491611],
[0.658483, 0.196027, 0.490253],
[0.664915, 0.198075, 0.488836],
[0.671349, 0.200133, 0.487358],
[0.677786, 0.202203, 0.485819],
[0.684224, 0.204286, 0.484219],
[0.690661, 0.206384, 0.482558],
[0.697098, 0.208501, 0.480835],
[0.703532, 0.210638, 0.479049],
[0.709962, 0.212797, 0.477201],
[0.716387, 0.214982, 0.475290],
[0.722805, 0.217194, 0.473316],
[0.729216, 0.219437, 0.471279],
[0.735616, 0.221713, 0.469180],
[0.742004, 0.224025, 0.467018],
[0.748378, 0.226377, 0.464794],
[0.754737, 0.228772, 0.462509],
[0.761077, 0.231214, 0.460162],
[0.767398, 0.233705, 0.457755],
[0.773695, 0.236249, 0.455289],
[0.779968, 0.238851, 0.452765],
[0.786212, 0.241514, 0.450184],
[0.792427, 0.244242, 0.447543],
[0.798608, 0.247040, 0.444848],
[0.804752, 0.249911, 0.442102],
[0.810855, 0.252861, 0.439305],
[0.816914, 0.255895, 0.436461],
[0.822926, 0.259016, 0.433573],
[0.828886, 0.262229, 0.430644],
[0.834791, 0.265540, 0.427671],
[0.840636, 0.268953, 0.424666],
[0.846416, 0.272473, 0.421631],
[0.852126, 0.276106, 0.418573],
[0.857763, 0.279857, 0.415496],
[0.863320, 0.283729, 0.412403],
[0.868793, 0.287728, 0.409303],
[0.874176, 0.291859, 0.406205],
[0.879464, 0.296125, 0.403118],
[0.884651, 0.300530, 0.400047],
[0.889731, 0.305079, 0.397002],
[0.894700, 0.309773, 0.393995],
[0.899552, 0.314616, 0.391037],
[0.904281, 0.319610, 0.388137],
[0.908884, 0.324755, 0.385308],
[0.913354, 0.330052, 0.382563],
[0.917689, 0.335500, 0.379915],
[0.921884, 0.341098, 0.377376],
[0.925937, 0.346844, 0.374959],
[0.929845, 0.352734, 0.372677],
[0.933606, 0.358764, 0.370541],
[0.937221, 0.364929, 0.368567],
[0.940687, 0.371224, 0.366762],
[0.944006, 0.377643, 0.365136],
[0.947180, 0.384178, 0.363701],
[0.950210, 0.390820, 0.362468],
[0.953099, 0.397563, 0.361438],
[0.955849, 0.404400, 0.360619],
[0.958464, 0.411324, 0.360014],
[0.960949, 0.418323, 0.359630],
[0.963310, 0.425390, 0.359469],
[0.965549, 0.432519, 0.359529],
[0.967671, 0.439703, 0.359810],
[0.969680, 0.446936, 0.360311],
[0.971582, 0.454210, 0.361030],
[0.973381, 0.461520, 0.361965],
[0.975082, 0.468861, 0.363111],
[0.976690, 0.476226, 0.364466],
[0.978210, 0.483612, 0.366025],
[0.979645, 0.491014, 0.367783],
[0.981000, 0.498428, 0.369734],
[0.982279, 0.505851, 0.371874],
[0.983485, 0.513280, 0.374198],
[0.984622, 0.520713, 0.376698],
[0.985693, 0.528148, 0.379371],
[0.986700, 0.535582, 0.382210],
[0.987646, 0.543015, 0.385210],
[0.988533, 0.550446, 0.388365],
[0.989363, 0.557873, 0.391671],
[0.990138, 0.565296, 0.395122],
[0.990871, 0.572706, 0.398714],
[0.991558, 0.580107, 0.402441],
[0.992196, 0.587502, 0.406299],
[0.992785, 0.594891, 0.410283],
[0.993326, 0.602275, 0.414390],
[0.993834, 0.609644, 0.418613],
[0.994309, 0.616999, 0.422950],
[0.994738, 0.624350, 0.427397],
[0.995122, 0.631696, 0.431951],
[0.995480, 0.639027, 0.436607],
[0.995810, 0.646344, 0.441361],
[0.996096, 0.653659, 0.446213],
[0.996341, 0.660969, 0.451160],
[0.996580, 0.668256, 0.456192],
[0.996775, 0.675541, 0.461314],
[0.996925, 0.682828, 0.466526],
[0.997077, 0.690088, 0.471811],
[0.997186, 0.697349, 0.477182],
[0.997254, 0.704611, 0.482635],
[0.997325, 0.711848, 0.488154],
[0.997351, 0.719089, 0.493755],
[0.997351, 0.726324, 0.499428],
[0.997341, 0.733545, 0.505167],
[0.997285, 0.740772, 0.510983],
[0.997228, 0.747981, 0.516859],
[0.997138, 0.755190, 0.522806],
[0.997019, 0.762398, 0.528821],
[0.996898, 0.769591, 0.534892],
[0.996727, 0.776795, 0.541039],
[0.996571, 0.783977, 0.547233],
[0.996369, 0.791167, 0.553499],
[0.996162, 0.798348, 0.559820],
[0.995932, 0.805527, 0.566202],
[0.995680, 0.812706, 0.572645],
[0.995424, 0.819875, 0.579140],
[0.995131, 0.827052, 0.585701],
[0.994851, 0.834213, 0.592307],
[0.994524, 0.841387, 0.598983],
[0.994222, 0.848540, 0.605696],
[0.993866, 0.855711, 0.612482],
[0.993545, 0.862859, 0.619299],
[0.993170, 0.870024, 0.626189],
[0.992831, 0.877168, 0.633109],
[0.992440, 0.884330, 0.640099],
[0.992089, 0.891470, 0.647116],
[0.991688, 0.898627, 0.654202],
[0.991332, 0.905763, 0.661309],
[0.990930, 0.912915, 0.668481],
[0.990570, 0.920049, 0.675675],
[0.990175, 0.927196, 0.682926],
[0.989815, 0.934329, 0.690198],
[0.989434, 0.941470, 0.697519],
[0.989077, 0.948604, 0.704863],
[0.988717, 0.955742, 0.712242],
[0.988367, 0.962878, 0.719649],
[0.988033, 0.970012, 0.727077],
[0.987691, 0.977154, 0.734536],
[0.987387, 0.984288, 0.742002],
[0.987053, 0.991438, 0.749504]]
_inferno_data = [[0.001462, 0.000466, 0.013866],
[0.002267, 0.001270, 0.018570],
[0.003299, 0.002249, 0.024239],
[0.004547, 0.003392, 0.030909],
[0.006006, 0.004692, 0.038558],
[0.007676, 0.006136, 0.046836],
[0.009561, 0.007713, 0.055143],
[0.011663, 0.009417, 0.063460],
[0.013995, 0.011225, 0.071862],
[0.016561, 0.013136, 0.080282],
[0.019373, 0.015133, 0.088767],
[0.022447, 0.017199, 0.097327],
[0.025793, 0.019331, 0.105930],
[0.029432, 0.021503, 0.114621],
[0.033385, 0.023702, 0.123397],
[0.037668, 0.025921, 0.132232],
[0.042253, 0.028139, 0.141141],
[0.046915, 0.030324, 0.150164],
[0.051644, 0.032474, 0.159254],
[0.056449, 0.034569, 0.168414],
[0.061340, 0.036590, 0.177642],
[0.066331, 0.038504, 0.186962],
[0.071429, 0.040294, 0.196354],
[0.076637, 0.041905, 0.205799],
[0.081962, 0.043328, 0.215289],
[0.087411, 0.044556, 0.224813],
[0.092990, 0.045583, 0.234358],
[0.098702, 0.046402, 0.243904],
[0.104551, 0.047008, 0.253430],
[0.110536, 0.047399, 0.262912],
[0.116656, 0.047574, 0.272321],
[0.122908, 0.047536, 0.281624],
[0.129285, 0.047293, 0.290788],
[0.135778, 0.046856, 0.299776],
[0.142378, 0.046242, 0.308553],
[0.149073, 0.045468, 0.317085],
[0.155850, 0.044559, 0.325338],
[0.162689, 0.043554, 0.333277],
[0.169575, 0.042489, 0.340874],
[0.176493, 0.041402, 0.348111],
[0.183429, 0.040329, 0.354971],
[0.190367, 0.039309, 0.361447],
[0.197297, 0.038400, 0.367535],
[0.204209, 0.037632, 0.373238],
[0.211095, 0.037030, 0.378563],
[0.217949, 0.036615, 0.383522],
[0.224763, 0.036405, 0.388129],
[0.231538, 0.036405, 0.392400],
[0.238273, 0.036621, 0.396353],
[0.244967, 0.037055, 0.400007],
[0.251620, 0.037705, 0.403378],
[0.258234, 0.038571, 0.406485],
[0.264810, 0.039647, 0.409345],
[0.271347, 0.040922, 0.411976],
[0.277850, 0.042353, 0.414392],
[0.284321, 0.043933, 0.416608],
[0.290763, 0.045644, 0.418637],
[0.297178, 0.047470, 0.420491],
[0.303568, 0.049396, 0.422182],
[0.309935, 0.051407, 0.423721],
[0.316282, 0.053490, 0.425116],
[0.322610, 0.055634, 0.426377],
[0.328921, 0.057827, 0.427511],
[0.335217, 0.060060, 0.428524],
[0.341500, 0.062325, 0.429425],
[0.347771, 0.064616, 0.430217],
[0.354032, 0.066925, 0.430906],
[0.360284, 0.069247, 0.431497],
[0.366529, 0.071579, 0.431994],
[0.372768, 0.073915, 0.432400],
[0.379001, 0.076253, 0.432719],
[0.385228, 0.078591, 0.432955],
[0.391453, 0.080927, 0.433109],
[0.397674, 0.083257, 0.433183],
[0.403894, 0.085580, 0.433179],
[0.410113, 0.087896, 0.433098],
[0.416331, 0.090203, 0.432943],
[0.422549, 0.092501, 0.432714],
[0.428768, 0.094790, 0.432412],
[0.434987, 0.097069, 0.432039],
[0.441207, 0.099338, 0.431594],
[0.447428, 0.101597, 0.431080],
[0.453651, 0.103848, 0.430498],
[0.459875, 0.106089, 0.429846],
[0.466100, 0.108322, 0.429125],
[0.472328, 0.110547, 0.428334],
[0.478558, 0.112764, 0.427475],
[0.484789, 0.114974, 0.426548],
[0.491022, 0.117179, 0.425552],
[0.497257, 0.119379, 0.424488],
[0.503493, 0.121575, 0.423356],
[0.509730, 0.123769, 0.422156],
[0.515967, 0.125960, 0.420887],
[0.522206, 0.128150, 0.419549],
[0.528444, 0.130341, 0.418142],
[0.534683, 0.132534, 0.416667],
[0.540920, 0.134729, 0.415123],
[0.547157, 0.136929, 0.413511],
[0.553392, 0.139134, 0.411829],
[0.559624, 0.141346, 0.410078],
[0.565854, 0.143567, 0.408258],
[0.572081, 0.145797, 0.406369],
[0.578304, 0.148039, 0.404411],
[0.584521, 0.150294, 0.402385],
[0.590734, 0.152563, 0.400290],
[0.596940, 0.154848, 0.398125],
[0.603139, 0.157151, 0.395891],
[0.609330, 0.159474, 0.393589],
[0.615513, 0.161817, 0.391219],
[0.621685, 0.164184, 0.388781],
[0.627847, 0.166575, 0.386276],
[0.633998, 0.168992, 0.383704],
[0.640135, 0.171438, 0.381065],
[0.646260, 0.173914, 0.378359],
[0.652369, 0.176421, 0.375586],
[0.658463, 0.178962, 0.372748],
[0.664540, 0.181539, 0.369846],
[0.670599, 0.184153, 0.366879],
[0.676638, 0.186807, 0.363849],
[0.682656, 0.189501, 0.360757],
[0.688653, 0.192239, 0.357603],
[0.694627, 0.195021, 0.354388],
[0.700576, 0.197851, 0.351113],
[0.706500, 0.200728, 0.347777],
[0.712396, 0.203656, 0.344383],
[0.718264, 0.206636, 0.340931],
[0.724103, 0.209670, 0.337424],
[0.729909, 0.212759, 0.333861],
[0.735683, 0.215906, 0.330245],
[0.741423, 0.219112, 0.326576],
[0.747127, 0.222378, 0.322856],
[0.752794, 0.225706, 0.319085],
[0.758422, 0.229097, 0.315266],
[0.764010, 0.232554, 0.311399],
[0.769556, 0.236077, 0.307485],
[0.775059, 0.239667, 0.303526],
[0.780517, 0.243327, 0.299523],
[0.785929, 0.247056, 0.295477],
[0.791293, 0.250856, 0.291390],
[0.796607, 0.254728, 0.287264],
[0.801871, 0.258674, 0.283099],
[0.807082, 0.262692, 0.278898],
[0.812239, 0.266786, 0.274661],
[0.817341, 0.270954, 0.270390],
[0.822386, 0.275197, 0.266085],
[0.827372, 0.279517, 0.261750],
[0.832299, 0.283913, 0.257383],
[0.837165, 0.288385, 0.252988],
[0.841969, 0.292933, 0.248564],
[0.846709, 0.297559, 0.244113],
[0.851384, 0.302260, 0.239636],
[0.855992, 0.307038, 0.235133],
[0.860533, 0.311892, 0.230606],
[0.865006, 0.316822, 0.226055],
[0.869409, 0.321827, 0.221482],
[0.873741, 0.326906, 0.216886],
[0.878001, 0.332060, 0.212268],
[0.882188, 0.337287, 0.207628],
[0.886302, 0.342586, 0.202968],
[0.890341, 0.347957, 0.198286],
[0.894305, 0.353399, 0.193584],
[0.898192, 0.358911, 0.188860],
[0.902003, 0.364492, 0.184116],
[0.905735, 0.370140, 0.179350],
[0.909390, 0.375856, 0.174563],
[0.912966, 0.381636, 0.169755],
[0.916462, 0.387481, 0.164924],
[0.919879, 0.393389, 0.160070],
[0.923215, 0.399359, 0.155193],
[0.926470, 0.405389, 0.150292],
[0.929644, 0.411479, 0.145367],
[0.932737, 0.417627, 0.140417],
[0.935747, 0.423831, 0.135440],
[0.938675, 0.430091, 0.130438],
[0.941521, 0.436405, 0.125409],
[0.944285, 0.442772, 0.120354],
[0.946965, 0.449191, 0.115272],
[0.949562, 0.455660, 0.110164],
[0.952075, 0.462178, 0.105031],
[0.954506, 0.468744, 0.099874],
[0.956852, 0.475356, 0.094695],
[0.959114, 0.482014, 0.089499],
[0.961293, 0.488716, 0.084289],
[0.963387, 0.495462, 0.079073],
[0.965397, 0.502249, 0.073859],
[0.967322, 0.509078, 0.068659],
[0.969163, 0.515946, 0.063488],
[0.970919, 0.522853, 0.058367],
[0.972590, 0.529798, 0.053324],
[0.974176, 0.536780, 0.048392],
[0.975677, 0.543798, 0.043618],
[0.977092, 0.550850, 0.039050],
[0.978422, 0.557937, 0.034931],
[0.979666, 0.565057, 0.031409],
[0.980824, 0.572209, 0.028508],
[0.981895, 0.579392, 0.026250],
[0.982881, 0.586606, 0.024661],
[0.983779, 0.593849, 0.023770],
[0.984591, 0.601122, 0.023606],
[0.985315, 0.608422, 0.024202],
[0.985952, 0.615750, 0.025592],
[0.986502, 0.623105, 0.027814],
[0.986964, 0.630485, 0.030908],
[0.987337, 0.637890, 0.034916],
[0.987622, 0.645320, 0.039886],
[0.987819, 0.652773, 0.045581],
[0.987926, 0.660250, 0.051750],
[0.987945, 0.667748, 0.058329],
[0.987874, 0.675267, 0.065257],
[0.987714, 0.682807, 0.072489],
[0.987464, 0.690366, 0.079990],
[0.987124, 0.697944, 0.087731],
[0.986694, 0.705540, 0.095694],
[0.986175, 0.713153, 0.103863],
[0.985566, 0.720782, 0.112229],
[0.984865, 0.728427, 0.120785],
[0.984075, 0.736087, 0.129527],
[0.983196, 0.743758, 0.138453],
[0.982228, 0.751442, 0.147565],
[0.981173, 0.759135, 0.156863],
[0.980032, 0.766837, 0.166353],
[0.978806, 0.774545, 0.176037],
[0.977497, 0.782258, 0.185923],
[0.976108, 0.789974, 0.196018],
[0.974638, 0.797692, 0.206332],
[0.973088, 0.805409, 0.216877],
[0.971468, 0.813122, 0.227658],
[0.969783, 0.820825, 0.238686],
[0.968041, 0.828515, 0.249972],
[0.966243, 0.836191, 0.261534],
[0.964394, 0.843848, 0.273391],
[0.962517, 0.851476, 0.285546],
[0.960626, 0.859069, 0.298010],
[0.958720, 0.866624, 0.310820],
[0.956834, 0.874129, 0.323974],
[0.954997, 0.881569, 0.337475],
[0.953215, 0.888942, 0.351369],
[0.951546, 0.896226, 0.365627],
[0.950018, 0.903409, 0.380271],
[0.948683, 0.910473, 0.395289],
[0.947594, 0.917399, 0.410665],
[0.946809, 0.924168, 0.426373],
[0.946392, 0.930761, 0.442367],
[0.946403, 0.937159, 0.458592],
[0.946903, 0.943348, 0.474970],
[0.947937, 0.949318, 0.491426],
[0.949545, 0.955063, 0.507860],
[0.951740, 0.960587, 0.524203],
[0.954529, 0.965896, 0.540361],
[0.957896, 0.971003, 0.556275],
[0.961812, 0.975924, 0.571925],
[0.966249, 0.980678, 0.587206],
[0.971162, 0.985282, 0.602154],
[0.976511, 0.989753, 0.616760],
[0.982257, 0.994109, 0.631017],
[0.988362, 0.998364, 0.644924]]
_plasma_data = [[0.050383, 0.029803, 0.527975],
[0.063536, 0.028426, 0.533124],
[0.075353, 0.027206, 0.538007],
[0.086222, 0.026125, 0.542658],
[0.096379, 0.025165, 0.547103],
[0.105980, 0.024309, 0.551368],
[0.115124, 0.023556, 0.555468],
[0.123903, 0.022878, 0.559423],
[0.132381, 0.022258, 0.563250],
[0.140603, 0.021687, 0.566959],
[0.148607, 0.021154, 0.570562],
[0.156421, 0.020651, 0.574065],
[0.164070, 0.020171, 0.577478],
[0.171574, 0.019706, 0.580806],
[0.178950, 0.019252, 0.584054],
[0.186213, 0.018803, 0.587228],
[0.193374, 0.018354, 0.590330],
[0.200445, 0.017902, 0.593364],
[0.207435, 0.017442, 0.596333],
[0.214350, 0.016973, 0.599239],
[0.221197, 0.016497, 0.602083],
[0.227983, 0.016007, 0.604867],
[0.234715, 0.015502, 0.607592],
[0.241396, 0.014979, 0.610259],
[0.248032, 0.014439, 0.612868],
[0.254627, 0.013882, 0.615419],
[0.261183, 0.013308, 0.617911],
[0.267703, 0.012716, 0.620346],
[0.274191, 0.012109, 0.622722],
[0.280648, 0.011488, 0.625038],
[0.287076, 0.010855, 0.627295],
[0.293478, 0.010213, 0.629490],
[0.299855, 0.009561, 0.631624],
[0.306210, 0.008902, 0.633694],
[0.312543, 0.008239, 0.635700],
[0.318856, 0.007576, 0.637640],
[0.325150, 0.006915, 0.639512],
[0.331426, 0.006261, 0.641316],
[0.337683, 0.005618, 0.643049],
[0.343925, 0.004991, 0.644710],
[0.350150, 0.004382, 0.646298],
[0.356359, 0.003798, 0.647810],
[0.362553, 0.003243, 0.649245],
[0.368733, 0.002724, 0.650601],
[0.374897, 0.002245, 0.651876],
[0.381047, 0.001814, 0.653068],
[0.387183, 0.001434, 0.654177],
[0.393304, 0.001114, 0.655199],
[0.399411, 0.000859, 0.656133],
[0.405503, 0.000678, 0.656977],
[0.411580, 0.000577, 0.657730],
[0.417642, 0.000564, 0.658390],
[0.423689, 0.000646, 0.658956],
[0.429719, 0.000831, 0.659425],
[0.435734, 0.001127, 0.659797],
[0.441732, 0.001540, 0.660069],
[0.447714, 0.002080, 0.660240],
[0.453677, 0.002755, 0.660310],
[0.459623, 0.003574, 0.660277],
[0.465550, 0.004545, 0.660139],
[0.471457, 0.005678, 0.659897],
[0.477344, 0.006980, 0.659549],
[0.483210, 0.008460, 0.659095],
[0.489055, 0.010127, 0.658534],
[0.494877, 0.011990, 0.657865],
[0.500678, 0.014055, 0.657088],
[0.506454, 0.016333, 0.656202],
[0.512206, 0.018833, 0.655209],
[0.517933, 0.021563, 0.654109],
[0.523633, 0.024532, 0.652901],
[0.529306, 0.027747, 0.651586],
[0.534952, 0.031217, 0.650165],
[0.540570, 0.034950, 0.648640],
[0.546157, 0.038954, 0.647010],
[0.551715, 0.043136, 0.645277],
[0.557243, 0.047331, 0.643443],
[0.562738, 0.051545, 0.641509],
[0.568201, 0.055778, 0.639477],
[0.573632, 0.060028, 0.637349],
[0.579029, 0.064296, 0.635126],
[0.584391, 0.068579, 0.632812],
[0.589719, 0.072878, 0.630408],
[0.595011, 0.077190, 0.627917],
[0.600266, 0.081516, 0.625342],
[0.605485, 0.085854, 0.622686],
[0.610667, 0.090204, 0.619951],
[0.615812, 0.094564, 0.617140],
[0.620919, 0.098934, 0.614257],
[0.625987, 0.103312, 0.611305],
[0.631017, 0.107699, 0.608287],
[0.636008, 0.112092, 0.605205],
[0.640959, 0.116492, 0.602065],
[0.645872, 0.120898, 0.598867],
[0.650746, 0.125309, 0.595617],
[0.655580, 0.129725, 0.592317],
[0.660374, 0.134144, 0.588971],
[0.665129, 0.138566, 0.585582],
[0.669845, 0.142992, 0.582154],
[0.674522, 0.147419, 0.578688],
[0.679160, 0.151848, 0.575189],
[0.683758, 0.156278, 0.571660],
[0.688318, 0.160709, 0.568103],
[0.692840, 0.165141, 0.564522],
[0.697324, 0.169573, 0.560919],
[0.701769, 0.174005, 0.557296],
[0.706178, 0.178437, 0.553657],
[0.710549, 0.182868, 0.550004],
[0.714883, 0.187299, 0.546338],
[0.719181, 0.191729, 0.542663],
[0.723444, 0.196158, 0.538981],
[0.727670, 0.200586, 0.535293],
[0.731862, 0.205013, 0.531601],
[0.736019, 0.209439, 0.527908],
[0.740143, 0.213864, 0.524216],
[0.744232, 0.218288, 0.520524],
[0.748289, 0.222711, 0.516834],
[0.752312, 0.227133, 0.513149],
[0.756304, 0.231555, 0.509468],
[0.760264, 0.235976, 0.505794],
[0.764193, 0.240396, 0.502126],
[0.768090, 0.244817, 0.498465],
[0.771958, 0.249237, 0.494813],
[0.775796, 0.253658, 0.491171],
[0.779604, 0.258078, 0.487539],
[0.783383, 0.262500, 0.483918],
[0.787133, 0.266922, 0.480307],
[0.790855, 0.271345, 0.476706],
[0.794549, 0.275770, 0.473117],
[0.798216, 0.280197, 0.469538],
[0.801855, 0.284626, 0.465971],
[0.805467, 0.289057, 0.462415],
[0.809052, 0.293491, 0.458870],
[0.812612, 0.297928, 0.455338],
[0.816144, 0.302368, 0.451816],
[0.819651, 0.306812, 0.448306],
[0.823132, 0.311261, 0.444806],
[0.826588, 0.315714, 0.441316],
[0.830018, 0.320172, 0.437836],
[0.833422, 0.324635, 0.434366],
[0.836801, 0.329105, 0.430905],
[0.840155, 0.333580, 0.427455],
[0.843484, 0.338062, 0.424013],
[0.846788, 0.342551, 0.420579],
[0.850066, 0.347048, 0.417153],
[0.853319, 0.351553, 0.413734],
[0.856547, 0.356066, 0.410322],
[0.859750, 0.360588, 0.406917],
[0.862927, 0.365119, 0.403519],
[0.866078, 0.369660, 0.400126],
[0.869203, 0.374212, 0.396738],
[0.872303, 0.378774, 0.393355],
[0.875376, 0.383347, 0.389976],
[0.878423, 0.387932, 0.386600],
[0.881443, 0.392529, 0.383229],
[0.884436, 0.397139, 0.379860],
[0.887402, 0.401762, 0.376494],
[0.890340, 0.406398, 0.373130],
[0.893250, 0.411048, 0.369768],
[0.896131, 0.415712, 0.366407],
[0.898984, 0.420392, 0.363047],
[0.901807, 0.425087, 0.359688],
[0.904601, 0.429797, 0.356329],
[0.907365, 0.434524, 0.352970],
[0.910098, 0.439268, 0.349610],
[0.912800, 0.444029, 0.346251],
[0.915471, 0.448807, 0.342890],
[0.918109, 0.453603, 0.339529],
[0.920714, 0.458417, 0.336166],
[0.923287, 0.463251, 0.332801],
[0.925825, 0.468103, 0.329435],
[0.928329, 0.472975, 0.326067],
[0.930798, 0.477867, 0.322697],
[0.933232, 0.482780, 0.319325],
[0.935630, 0.487712, 0.315952],
[0.937990, 0.492667, 0.312575],
[0.940313, 0.497642, 0.309197],
[0.942598, 0.502639, 0.305816],
[0.944844, 0.507658, 0.302433],
[0.947051, 0.512699, 0.299049],
[0.949217, 0.517763, 0.295662],
[0.951344, 0.522850, 0.292275],
[0.953428, 0.527960, 0.288883],
[0.955470, 0.533093, 0.285490],
[0.957469, 0.538250, 0.282096],
[0.959424, 0.543431, 0.278701],
[0.961336, 0.548636, 0.275305],
[0.963203, 0.553865, 0.271909],
[0.965024, 0.559118, 0.268513],
[0.966798, 0.564396, 0.265118],
[0.968526, 0.569700, 0.261721],
[0.970205, 0.575028, 0.258325],
[0.971835, 0.580382, 0.254931],
[0.973416, 0.585761, 0.251540],
[0.974947, 0.591165, 0.248151],
[0.976428, 0.596595, 0.244767],
[0.977856, 0.602051, 0.241387],
[0.979233, 0.607532, 0.238013],
[0.980556, 0.613039, 0.234646],
[0.981826, 0.618572, 0.231287],
[0.983041, 0.624131, 0.227937],
[0.984199, 0.629718, 0.224595],
[0.985301, 0.635330, 0.221265],
[0.986345, 0.640969, 0.217948],
[0.987332, 0.646633, 0.214648],
[0.988260, 0.652325, 0.211364],
[0.989128, 0.658043, 0.208100],
[0.989935, 0.663787, 0.204859],
[0.990681, 0.669558, 0.201642],
[0.991365, 0.675355, 0.198453],
[0.991985, 0.681179, 0.195295],
[0.992541, 0.687030, 0.192170],
[0.993032, 0.692907, 0.189084],
[0.993456, 0.698810, 0.186041],
[0.993814, 0.704741, 0.183043],
[0.994103, 0.710698, 0.180097],
[0.994324, 0.716681, 0.177208],
[0.994474, 0.722691, 0.174381],
[0.994553, 0.728728, 0.171622],
[0.994561, 0.734791, 0.168938],
[0.994495, 0.740880, 0.166335],
[0.994355, 0.746995, 0.163821],
[0.994141, 0.753137, 0.161404],
[0.993851, 0.759304, 0.159092],
[0.993482, 0.765499, 0.156891],
[0.993033, 0.771720, 0.154808],
[0.992505, 0.777967, 0.152855],
[0.991897, 0.784239, 0.151042],
[0.991209, 0.790537, 0.149377],
[0.990439, 0.796859, 0.147870],
[0.989587, 0.803205, 0.146529],
[0.988648, 0.809579, 0.145357],
[0.987621, 0.815978, 0.144363],
[0.986509, 0.822401, 0.143557],
[0.985314, 0.828846, 0.142945],
[0.984031, 0.835315, 0.142528],
[0.982653, 0.841812, 0.142303],
[0.981190, 0.848329, 0.142279],
[0.979644, 0.854866, 0.142453],
[0.977995, 0.861432, 0.142808],
[0.976265, 0.868016, 0.143351],
[0.974443, 0.874622, 0.144061],
[0.972530, 0.881250, 0.144923],
[0.970533, 0.887896, 0.145919],
[0.968443, 0.894564, 0.147014],
[0.966271, 0.901249, 0.148180],
[0.964021, 0.907950, 0.149370],
[0.961681, 0.914672, 0.150520],
[0.959276, 0.921407, 0.151566],
[0.956808, 0.928152, 0.152409],
[0.954287, 0.934908, 0.152921],
[0.951726, 0.941671, 0.152925],
[0.949151, 0.948435, 0.152178],
[0.946602, 0.955190, 0.150328],
[0.944152, 0.961916, 0.146861],
[0.941896, 0.968590, 0.140956],
[0.940015, 0.975158, 0.131326]]
_viridis_data = [[0.267004, 0.004874, 0.329415],
[0.268510, 0.009605, 0.335427],
[0.269944, 0.014625, 0.341379],
[0.271305, 0.019942, 0.347269],
[0.272594, 0.025563, 0.353093],
[0.273809, 0.031497, 0.358853],
[0.274952, 0.037752, 0.364543],
[0.276022, 0.044167, 0.370164],
[0.277018, 0.050344, 0.375715],
[0.277941, 0.056324, 0.381191],
[0.278791, 0.062145, 0.386592],
[0.279566, 0.067836, 0.391917],
[0.280267, 0.073417, 0.397163],
[0.280894, 0.078907, 0.402329],
[0.281446, 0.084320, 0.407414],
[0.281924, 0.089666, 0.412415],
[0.282327, 0.094955, 0.417331],
[0.282656, 0.100196, 0.422160],
[0.282910, 0.105393, 0.426902],
[0.283091, 0.110553, 0.431554],
[0.283197, 0.115680, 0.436115],
[0.283229, 0.120777, 0.440584],
[0.283187, 0.125848, 0.444960],
[0.283072, 0.130895, 0.449241],
[0.282884, 0.135920, 0.453427],
[0.282623, 0.140926, 0.457517],
[0.282290, 0.145912, 0.461510],
[0.281887, 0.150881, 0.465405],
[0.281412, 0.155834, 0.469201],
[0.280868, 0.160771, 0.472899],
[0.280255, 0.165693, 0.476498],
[0.279574, 0.170599, 0.479997],
[0.278826, 0.175490, 0.483397],
[0.278012, 0.180367, 0.486697],
[0.277134, 0.185228, 0.489898],
[0.276194, 0.190074, 0.493001],
[0.275191, 0.194905, 0.496005],
[0.274128, 0.199721, 0.498911],
[0.273006, 0.204520, 0.501721],
[0.271828, 0.209303, 0.504434],
[0.270595, 0.214069, 0.507052],
[0.269308, 0.218818, 0.509577],
[0.267968, 0.223549, 0.512008],
[0.266580, 0.228262, 0.514349],
[0.265145, 0.232956, 0.516599],
[0.263663, 0.237631, 0.518762],
[0.262138, 0.242286, 0.520837],
[0.260571, 0.246922, 0.522828],
[0.258965, 0.251537, 0.524736],
[0.257322, 0.256130, 0.526563],
[0.255645, 0.260703, 0.528312],
[0.253935, 0.265254, 0.529983],
[0.252194, 0.269783, 0.531579],
[0.250425, 0.274290, 0.533103],
[0.248629, 0.278775, 0.534556],
[0.246811, 0.283237, 0.535941],
[0.244972, 0.287675, 0.537260],
[0.243113, 0.292092, 0.538516],
[0.241237, 0.296485, 0.539709],
[0.239346, 0.300855, 0.540844],
[0.237441, 0.305202, 0.541921],
[0.235526, 0.309527, 0.542944],
[0.233603, 0.313828, 0.543914],
[0.231674, 0.318106, 0.544834],
[0.229739, 0.322361, 0.545706],
[0.227802, 0.326594, 0.546532],
[0.225863, 0.330805, 0.547314],
[0.223925, 0.334994, 0.548053],
[0.221989, 0.339161, 0.548752],
[0.220057, 0.343307, 0.549413],
[0.218130, 0.347432, 0.550038],
[0.216210, 0.351535, 0.550627],
[0.214298, 0.355619, 0.551184],
[0.212395, 0.359683, 0.551710],
[0.210503, 0.363727, 0.552206],
[0.208623, 0.367752, 0.552675],
[0.206756, 0.371758, 0.553117],
[0.204903, 0.375746, 0.553533],
[0.203063, 0.379716, 0.553925],
[0.201239, 0.383670, 0.554294],
[0.199430, 0.387607, 0.554642],
[0.197636, 0.391528, 0.554969],
[0.195860, 0.395433, 0.555276],
[0.194100, 0.399323, 0.555565],
[0.192357, 0.403199, 0.555836],
[0.190631, 0.407061, 0.556089],
[0.188923, 0.410910, 0.556326],
[0.187231, 0.414746, 0.556547],
[0.185556, 0.418570, 0.556753],
[0.183898, 0.422383, 0.556944],
[0.182256, 0.426184, 0.557120],
[0.180629, 0.429975, 0.557282],
[0.179019, 0.433756, 0.557430],
[0.177423, 0.437527, 0.557565],
[0.175841, 0.441290, 0.557685],
[0.174274, 0.445044, 0.557792],
[0.172719, 0.448791, 0.557885],
[0.171176, 0.452530, 0.557965],
[0.169646, 0.456262, 0.558030],
[0.168126, 0.459988, 0.558082],
[0.166617, 0.463708, 0.558119],
[0.165117, 0.467423, 0.558141],
[0.163625, 0.471133, 0.558148],
[0.162142, 0.474838, 0.558140],
[0.160665, 0.478540, 0.558115],
[0.159194, 0.482237, 0.558073],
[0.157729, 0.485932, 0.558013],
[0.156270, 0.489624, 0.557936],
[0.154815, 0.493313, 0.557840],
[0.153364, 0.497000, 0.557724],
[0.151918, 0.500685, 0.557587],
[0.150476, 0.504369, 0.557430],
[0.149039, 0.508051, 0.557250],
[0.147607, 0.511733, 0.557049],
[0.146180, 0.515413, 0.556823],
[0.144759, 0.519093, 0.556572],
[0.143343, 0.522773, 0.556295],
[0.141935, 0.526453, 0.555991],
[0.140536, 0.530132, 0.555659],
[0.139147, 0.533812, 0.555298],
[0.137770, 0.537492, 0.554906],
[0.136408, 0.541173, 0.554483],
[0.135066, 0.544853, 0.554029],
[0.133743, 0.548535, 0.553541],
[0.132444, 0.552216, 0.553018],
[0.131172, 0.555899, 0.552459],
[0.129933, 0.559582, 0.551864],
[0.128729, 0.563265, 0.551229],
[0.127568, 0.566949, 0.550556],
[0.126453, 0.570633, 0.549841],
[0.125394, 0.574318, 0.549086],
[0.124395, 0.578002, 0.548287],
[0.123463, 0.581687, 0.547445],
[0.122606, 0.585371, 0.546557],
[0.121831, 0.589055, 0.545623],
[0.121148, 0.592739, 0.544641],
[0.120565, 0.596422, 0.543611],
[0.120092, 0.600104, 0.542530],
[0.119738, 0.603785, 0.541400],
[0.119512, 0.607464, 0.540218],
[0.119423, 0.611141, 0.538982],
[0.119483, 0.614817, 0.537692],
[0.119699, 0.618490, 0.536347],
[0.120081, 0.622161, 0.534946],
[0.120638, 0.625828, 0.533488],
[0.121380, 0.629492, 0.531973],
[0.122312, 0.633153, 0.530398],
[0.123444, 0.636809, 0.528763],
[0.124780, 0.640461, 0.527068],
[0.126326, 0.644107, 0.525311],
[0.128087, 0.647749, 0.523491],
[0.130067, 0.651384, 0.521608],
[0.132268, 0.655014, 0.519661],
[0.134692, 0.658636, 0.517649],
[0.137339, 0.662252, 0.515571],
[0.140210, 0.665859, 0.513427],
[0.143303, 0.669459, 0.511215],
[0.146616, 0.673050, 0.508936],
[0.150148, 0.676631, 0.506589],
[0.153894, 0.680203, 0.504172],
[0.157851, 0.683765, 0.501686],
[0.162016, 0.687316, 0.499129],
[0.166383, 0.690856, 0.496502],
[0.170948, 0.694384, 0.493803],
[0.175707, 0.697900, 0.491033],
[0.180653, 0.701402, 0.488189],
[0.185783, 0.704891, 0.485273],
[0.191090, 0.708366, 0.482284],
[0.196571, 0.711827, 0.479221],
[0.202219, 0.715272, 0.476084],
[0.208030, 0.718701, 0.472873],
[0.214000, 0.722114, 0.469588],
[0.220124, 0.725509, 0.466226],
[0.226397, 0.728888, 0.462789],
[0.232815, 0.732247, 0.459277],
[0.239374, 0.735588, 0.455688],
[0.246070, 0.738910, 0.452024],
[0.252899, 0.742211, 0.448284],
[0.259857, 0.745492, 0.444467],
[0.266941, 0.748751, 0.440573],
[0.274149, 0.751988, 0.436601],
[0.281477, 0.755203, 0.432552],
[0.288921, 0.758394, 0.428426],
[0.296479, 0.761561, 0.424223],
[0.304148, 0.764704, 0.419943],
[0.311925, 0.767822, 0.415586],
[0.319809, 0.770914, 0.411152],
[0.327796, 0.773980, 0.406640],
[0.335885, 0.777018, 0.402049],
[0.344074, 0.780029, 0.397381],
[0.352360, 0.783011, 0.392636],
[0.360741, 0.785964, 0.387814],
[0.369214, 0.788888, 0.382914],
[0.377779, 0.791781, 0.377939],
[0.386433, 0.794644, 0.372886],
[0.395174, 0.797475, 0.367757],
[0.404001, 0.800275, 0.362552],
[0.412913, 0.803041, 0.357269],
[0.421908, 0.805774, 0.351910],
[0.430983, 0.808473, 0.346476],
[0.440137, 0.811138, 0.340967],
[0.449368, 0.813768, 0.335384],
[0.458674, 0.816363, 0.329727],
[0.468053, 0.818921, 0.323998],
[0.477504, 0.821444, 0.318195],
[0.487026, 0.823929, 0.312321],
[0.496615, 0.826376, 0.306377],
[0.506271, 0.828786, 0.300362],
[0.515992, 0.831158, 0.294279],
[0.525776, 0.833491, 0.288127],
[0.535621, 0.835785, 0.281908],
[0.545524, 0.838039, 0.275626],
[0.555484, 0.840254, 0.269281],
[0.565498, 0.842430, 0.262877],
[0.575563, 0.844566, 0.256415],
[0.585678, 0.846661, 0.249897],
[0.595839, 0.848717, 0.243329],
[0.606045, 0.850733, 0.236712],
[0.616293, 0.852709, 0.230052],
[0.626579, 0.854645, 0.223353],
[0.636902, 0.856542, 0.216620],
[0.647257, 0.858400, 0.209861],
[0.657642, 0.860219, 0.203082],
[0.668054, 0.861999, 0.196293],
[0.678489, 0.863742, 0.189503],
[0.688944, 0.865448, 0.182725],
[0.699415, 0.867117, 0.175971],
[0.709898, 0.868751, 0.169257],
[0.720391, 0.870350, 0.162603],
[0.730889, 0.871916, 0.156029],
[0.741388, 0.873449, 0.149561],
[0.751884, 0.874951, 0.143228],
[0.762373, 0.876424, 0.137064],
[0.772852, 0.877868, 0.131109],
[0.783315, 0.879285, 0.125405],
[0.793760, 0.880678, 0.120005],
[0.804182, 0.882046, 0.114965],
[0.814576, 0.883393, 0.110347],
[0.824940, 0.884720, 0.106217],
[0.835270, 0.886029, 0.102646],
[0.845561, 0.887322, 0.099702],
[0.855810, 0.888601, 0.097452],
[0.866013, 0.889868, 0.095953],
[0.876168, 0.891125, 0.095250],
[0.886271, 0.892374, 0.095374],
[0.896320, 0.893616, 0.096335],
[0.906311, 0.894855, 0.098125],
[0.916242, 0.896091, 0.100717],
[0.926106, 0.897330, 0.104071],
[0.935904, 0.898570, 0.108131],
[0.945636, 0.899815, 0.112838],
[0.955300, 0.901065, 0.118128],
[0.964894, 0.902323, 0.123941],
[0.974417, 0.903590, 0.130215],
[0.983868, 0.904867, 0.136897],
[0.993248, 0.906157, 0.143936]]
_cividis_data = [[0.000000, 0.135112, 0.304751],
[0.000000, 0.138068, 0.311105],
[0.000000, 0.141013, 0.317579],
[0.000000, 0.143951, 0.323982],
[0.000000, 0.146877, 0.330479],
[0.000000, 0.149791, 0.337065],
[0.000000, 0.152673, 0.343704],
[0.000000, 0.155377, 0.350500],
[0.000000, 0.157932, 0.357521],
[0.000000, 0.160495, 0.364534],
[0.000000, 0.163058, 0.371608],
[0.000000, 0.165621, 0.378769],
[0.000000, 0.168204, 0.385902],
[0.000000, 0.170800, 0.393100],
[0.000000, 0.173420, 0.400353],
[0.000000, 0.176082, 0.407577],
[0.000000, 0.178802, 0.414764],
[0.000000, 0.181610, 0.421859],
[0.000000, 0.184550, 0.428802],
[0.000000, 0.186915, 0.435532],
[0.000000, 0.188769, 0.439563],
[0.000000, 0.190950, 0.441085],
[0.000000, 0.193366, 0.441561],
[0.003602, 0.195911, 0.441564],
[0.017852, 0.198528, 0.441248],
[0.032110, 0.201199, 0.440785],
[0.046205, 0.203903, 0.440196],
[0.058378, 0.206629, 0.439531],
[0.068968, 0.209372, 0.438863],
[0.078624, 0.212122, 0.438105],
[0.087465, 0.214879, 0.437342],
[0.095645, 0.217643, 0.436593],
[0.103401, 0.220406, 0.435790],
[0.110658, 0.223170, 0.435067],
[0.117612, 0.225935, 0.434308],
[0.124291, 0.228697, 0.433547],
[0.130669, 0.231458, 0.432840],
[0.136830, 0.234216, 0.432148],
[0.142852, 0.236972, 0.431404],
[0.148638, 0.239724, 0.430752],
[0.154261, 0.242475, 0.430120],
[0.159733, 0.245221, 0.429528],
[0.165113, 0.247965, 0.428908],
[0.170362, 0.250707, 0.428325],
[0.175490, 0.253444, 0.427790],
[0.180503, 0.256180, 0.427299],
[0.185453, 0.258914, 0.426788],
[0.190303, 0.261644, 0.426329],
[0.195057, 0.264372, 0.425924],
[0.199764, 0.267099, 0.425497],
[0.204385, 0.269823, 0.425126],
[0.208926, 0.272546, 0.424809],
[0.213431, 0.275266, 0.424480],
[0.217863, 0.277985, 0.424206],
[0.222264, 0.280702, 0.423914],
[0.226598, 0.283419, 0.423678],
[0.230871, 0.286134, 0.423498],
[0.235120, 0.288848, 0.423304],
[0.239312, 0.291562, 0.423167],
[0.243485, 0.294274, 0.423014],
[0.247605, 0.296986, 0.422917],
[0.251675, 0.299698, 0.422873],
[0.255731, 0.302409, 0.422814],
[0.259740, 0.305120, 0.422810],
[0.263738, 0.307831, 0.422789],
[0.267693, 0.310542, 0.422821],
[0.271639, 0.313253, 0.422837],
[0.275513, 0.315965, 0.422979],
[0.279411, 0.318677, 0.423031],
[0.283240, 0.321390, 0.423211],
[0.287065, 0.324103, 0.423373],
[0.290884, 0.326816, 0.423517],
[0.294669, 0.329531, 0.423716],
[0.298421, 0.332247, 0.423973],
[0.302169, 0.334963, 0.424213],
[0.305886, 0.337681, 0.424512],
[0.309601, 0.340399, 0.424790],
[0.313287, 0.343120, 0.425120],
[0.316941, 0.345842, 0.425512],
[0.320595, 0.348565, 0.425889],
[0.324250, 0.351289, 0.426250],
[0.327875, 0.354016, 0.426670],
[0.331474, 0.356744, 0.427144],
[0.335073, 0.359474, 0.427605],
[0.338673, 0.362206, 0.428053],
[0.342246, 0.364939, 0.428559],
[0.345793, 0.367676, 0.429127],
[0.349341, 0.370414, 0.429685],
[0.352892, 0.373153, 0.430226],
[0.356418, 0.375896, 0.430823],
[0.359916, 0.378641, 0.431501],
[0.363446, 0.381388, 0.432075],
[0.366923, 0.384139, 0.432796],
[0.370430, 0.386890, 0.433428],
[0.373884, 0.389646, 0.434209],
[0.377371, 0.392404, 0.434890],
[0.380830, 0.395164, 0.435653],
[0.384268, 0.397928, 0.436475],
[0.387705, 0.400694, 0.437305],
[0.391151, 0.403464, 0.438096],
[0.394568, 0.406236, 0.438986],
[0.397991, 0.409011, 0.439848],
[0.401418, 0.411790, 0.440708],
[0.404820, 0.414572, 0.441642],
[0.408226, 0.417357, 0.442570],
[0.411607, 0.420145, 0.443577],
[0.414992, 0.422937, 0.444578],
[0.418383, 0.425733, 0.445560],
[0.421748, 0.428531, 0.446640],
[0.425120, 0.431334, 0.447692],
[0.428462, 0.434140, 0.448864],
[0.431817, 0.436950, 0.449982],
[0.435168, 0.439763, 0.451134],
[0.438504, 0.442580, 0.452341],
[0.441810, 0.445402, 0.453659],
[0.445148, 0.448226, 0.454885],
[0.448447, 0.451053, 0.456264],
[0.451759, 0.453887, 0.457582],
[0.455072, 0.456718, 0.458976],
[0.458366, 0.459552, 0.460457],
[0.461616, 0.462405, 0.461969],
[0.464947, 0.465241, 0.463395],
[0.468254, 0.468083, 0.464908],
[0.471501, 0.470960, 0.466357],
[0.474812, 0.473832, 0.467681],
[0.478186, 0.476699, 0.468845],
[0.481622, 0.479573, 0.469767],
[0.485141, 0.482451, 0.470384],
[0.488697, 0.485318, 0.471008],
[0.492278, 0.488198, 0.471453],
[0.495913, 0.491076, 0.471751],
[0.499552, 0.493960, 0.472032],
[0.503185, 0.496851, 0.472305],
[0.506866, 0.499743, 0.472432],
[0.510540, 0.502643, 0.472550],
[0.514226, 0.505546, 0.472640],
[0.517920, 0.508454, 0.472707],
[0.521643, 0.511367, 0.472639],
[0.525348, 0.514285, 0.472660],
[0.529086, 0.517207, 0.472543],
[0.532829, 0.520135, 0.472401],
[0.536553, 0.523067, 0.472352],
[0.540307, 0.526005, 0.472163],
[0.544069, 0.528948, 0.471947],
[0.547840, 0.531895, 0.471704],
[0.551612, 0.534849, 0.471439],
[0.555393, 0.537807, 0.471147],
[0.559181, 0.540771, 0.470829],
[0.562972, 0.543741, 0.470488],
[0.566802, 0.546715, 0.469988],
[0.570607, 0.549695, 0.469593],
[0.574417, 0.552682, 0.469172],
[0.578236, 0.555673, 0.468724],
[0.582087, 0.558670, 0.468118],
[0.585916, 0.561674, 0.467618],
[0.589753, 0.564682, 0.467090],
[0.593622, 0.567697, 0.466401],
[0.597469, 0.570718, 0.465821],
[0.601354, 0.573743, 0.465074],
[0.605211, 0.576777, 0.464441],
[0.609105, 0.579816, 0.463638],
[0.612977, 0.582861, 0.462950],
[0.616852, 0.585913, 0.462237],
[0.620765, 0.588970, 0.461351],
[0.624654, 0.592034, 0.460583],
[0.628576, 0.595104, 0.459641],
[0.632506, 0.598180, 0.458668],
[0.636412, 0.601264, 0.457818],
[0.640352, 0.604354, 0.456791],
[0.644270, 0.607450, 0.455886],
[0.648222, 0.610553, 0.454801],
[0.652178, 0.613664, 0.453689],
[0.656114, 0.616780, 0.452702],
[0.660082, 0.619904, 0.451534],
[0.664055, 0.623034, 0.450338],
[0.668008, 0.626171, 0.449270],
[0.671991, 0.629316, 0.448018],
[0.675981, 0.632468, 0.446736],
[0.679979, 0.635626, 0.445424],
[0.683950, 0.638793, 0.444251],
[0.687957, 0.641966, 0.442886],
[0.691971, 0.645145, 0.441491],
[0.695985, 0.648334, 0.440072],
[0.700008, 0.651529, 0.438624],
[0.704037, 0.654731, 0.437147],
[0.708067, 0.657942, 0.435647],
[0.712105, 0.661160, 0.434117],
[0.716177, 0.664384, 0.432386],
[0.720222, 0.667618, 0.430805],
[0.724274, 0.670859, 0.429194],
[0.728334, 0.674107, 0.427554],
[0.732422, 0.677364, 0.425717],
[0.736488, 0.680629, 0.424028],
[0.740589, 0.683900, 0.422131],
[0.744664, 0.687181, 0.420393],
[0.748772, 0.690470, 0.418448],
[0.752886, 0.693766, 0.416472],
[0.756975, 0.697071, 0.414659],
[0.761096, 0.700384, 0.412638],
[0.765223, 0.703705, 0.410587],
[0.769353, 0.707035, 0.408516],
[0.773486, 0.710373, 0.406422],
[0.777651, 0.713719, 0.404112],
[0.781795, 0.717074, 0.401966],
[0.785965, 0.720438, 0.399613],
[0.790116, 0.723810, 0.397423],
[0.794298, 0.727190, 0.395016],
[0.798480, 0.730580, 0.392597],
[0.802667, 0.733978, 0.390153],
[0.806859, 0.737385, 0.387684],
[0.811054, 0.740801, 0.385198],
[0.815274, 0.744226, 0.382504],
[0.819499, 0.747659, 0.379785],
[0.823729, 0.751101, 0.377043],
[0.827959, 0.754553, 0.374292],
[0.832192, 0.758014, 0.371529],
[0.836429, 0.761483, 0.368747],
[0.840693, 0.764962, 0.365746],
[0.844957, 0.768450, 0.362741],
[0.849223, 0.771947, 0.359729],
[0.853515, 0.775454, 0.356500],
[0.857809, 0.778969, 0.353259],
[0.862105, 0.782494, 0.350011],
[0.866421, 0.786028, 0.346571],
[0.870717, 0.789572, 0.343333],
[0.875057, 0.793125, 0.339685],
[0.879378, 0.796687, 0.336241],
[0.883720, 0.800258, 0.332599],
[0.888081, 0.803839, 0.328770],
[0.892440, 0.807430, 0.324968],
[0.896818, 0.811030, 0.320982],
[0.901195, 0.814639, 0.317021],
[0.905589, 0.818257, 0.312889],
[0.910000, 0.821885, 0.308594],
[0.914407, 0.825522, 0.304348],
[0.918828, 0.829168, 0.299960],
[0.923279, 0.832822, 0.295244],
[0.927724, 0.836486, 0.290611],
[0.932180, 0.840159, 0.285880],
[0.936660, 0.843841, 0.280876],
[0.941147, 0.847530, 0.275815],
[0.945654, 0.851228, 0.270532],
[0.950178, 0.854933, 0.265085],
[0.954725, 0.858646, 0.259365],
[0.959284, 0.862365, 0.253563],
[0.963872, 0.866089, 0.247445],
[0.968469, 0.869819, 0.241310],
[0.973114, 0.873550, 0.234677],
[0.977780, 0.877281, 0.227954],
[0.982497, 0.881008, 0.220878],
[0.987293, 0.884718, 0.213336],
[0.992218, 0.888385, 0.205468],
[0.994847, 0.892954, 0.203445],
[0.995249, 0.898384, 0.207561],
[0.995503, 0.903866, 0.212370],
[0.995737, 0.909344, 0.217772]]
_twilight_data = [
[0.88575015840754434, 0.85000924943067835, 0.8879736506427196],
[0.88378520195539056, 0.85072940540310626, 0.88723222096949894],
[0.88172231059285788, 0.85127594077653468, 0.88638056925514819],
[0.8795410528270573, 0.85165675407495722, 0.8854143767924102],
[0.87724880858965482, 0.85187028338870274, 0.88434120381311432],
[0.87485347508575972, 0.85191526123023187, 0.88316926967613829],
[0.87233134085124076, 0.85180165478080894, 0.88189704355001619],
[0.86970474853509816, 0.85152403004797894, 0.88053883390003362],
[0.86696015505333579, 0.8510896085314068, 0.87909766977173343],
[0.86408985081463996, 0.85050391167507788, 0.87757925784892632],
[0.86110245436899846, 0.84976754857001258, 0.87599242923439569],
[0.85798259245670372, 0.84888934810281835, 0.87434038553446281],
[0.85472593189256985, 0.84787488124672816, 0.8726282980930582],
[0.85133714570857189, 0.84672735796116472, 0.87086081657350445],
[0.84780710702577922, 0.8454546229209523, 0.86904036783694438],
[0.8441261828674842, 0.84406482711037389, 0.86716973322690072],
[0.84030420805957784, 0.8425605950855084, 0.865250882410458],
[0.83634031809191178, 0.84094796518951942, 0.86328528001070159],
[0.83222705712934408, 0.83923490627754482, 0.86127563500427884],
[0.82796894316013536, 0.83742600751395202, 0.85922399451306786],
[0.82357429680252847, 0.83552487764795436, 0.85713191328514948],
[0.81904654677937527, 0.8335364929949034, 0.85500206287010105],
[0.81438982121143089, 0.83146558694197847, 0.85283759062147024],
[0.8095999819094809, 0.82931896673505456, 0.85064441601050367],
[0.80469164429814577, 0.82709838780560663, 0.84842449296974021],
[0.79967075421267997, 0.82480781812080928, 0.84618210029578533],
[0.79454305089231114, 0.82245116226304615, 0.84392184786827984],
[0.78931445564608915, 0.82003213188702007, 0.8416486380471222],
[0.78399101042764918, 0.81755426400533426, 0.83936747464036732],
[0.77857892008227592, 0.81502089378742548, 0.8370834463093898],
[0.77308416590170936, 0.81243524735466011, 0.83480172950579679],
[0.76751108504417864, 0.8098007598713145, 0.83252816638059668],
[0.76186907937980286, 0.80711949387647486, 0.830266486168872],
[0.75616443584381976, 0.80439408733477935, 0.82802138994719998],
[0.75040346765406696, 0.80162699008965321, 0.82579737851082424],
[0.74459247771890169, 0.79882047719583249, 0.82359867586156521],
[0.73873771700494939, 0.79597665735031009, 0.82142922780433014],
[0.73284543645523459, 0.79309746468844067, 0.81929263384230377],
[0.72692177512829703, 0.7901846863592763, 0.81719217466726379],
[0.72097280665536778, 0.78723995923452639, 0.81513073920879264],
[0.71500403076252128, 0.78426487091581187, 0.81311116559949914],
[0.70902078134539304, 0.78126088716070907, 0.81113591855117928],
[0.7030297722540817, 0.77822904973358131, 0.80920618848056969],
[0.6970365443886174, 0.77517050008066057, 0.80732335380063447],
[0.69104641009309098, 0.77208629460678091, 0.80548841690679074],
[0.68506446154395928, 0.7689774029354699, 0.80370206267176914],
[0.67909554499882152, 0.76584472131395898, 0.8019646617300199],
[0.67314422559426212, 0.76268908733890484, 0.80027628545809526],
[0.66721479803752815, 0.7595112803730375, 0.79863674654537764],
[0.6613112930078745, 0.75631202708719025, 0.7970456043491897],
[0.65543692326454717, 0.75309208756768431, 0.79550271129031047],
[0.64959573004253479, 0.74985201221941766, 0.79400674021499107],
[0.6437910831099849, 0.7465923800833657, 0.79255653201306053],
[0.63802586828545982, 0.74331376714033193, 0.79115100459573173],
[0.6323027138710603, 0.74001672160131404, 0.78978892762640429],
[0.62662402022604591, 0.73670175403699445, 0.78846901316334561],
[0.62099193064817548, 0.73336934798923203, 0.78718994624696581],
[0.61540846411770478, 0.73001995232739691, 0.78595022706750484],
[0.60987543176093062, 0.72665398759758293, 0.78474835732694714],
[0.60439434200274855, 0.7232718614323369, 0.78358295593535587],
[0.5989665814482068, 0.71987394892246725, 0.78245259899346642],
[0.59359335696837223, 0.7164606049658685, 0.78135588237640097],
[0.58827579780555495, 0.71303214646458135, 0.78029141405636515],
[0.58301487036932409, 0.70958887676997473, 0.77925781820476592],
[0.5778116438998202, 0.70613106157153982, 0.77825345121025524],
[0.5726668948158774, 0.7026589535425779, 0.77727702680911992],
[0.56758117853861967, 0.69917279302646274, 0.77632748534275298],
[0.56255515357219343, 0.69567278381629649, 0.77540359142309845],
[0.55758940419605174, 0.69215911458254054, 0.7745041337932782],
[0.55268450589347129, 0.68863194515166382, 0.7736279426902245],
[0.54784098153018634, 0.68509142218509878, 0.77277386473440868],
[0.54305932424018233, 0.68153767253065878, 0.77194079697835083],
[0.53834015575176275, 0.67797081129095405, 0.77112734439057717],
[0.53368389147728401, 0.67439093705212727, 0.7703325054879735],
[0.529090861832473, 0.67079812302806219, 0.76955552292313134],
[0.52456151470593582, 0.66719242996142225, 0.76879541714230948],
[0.52009627392235558, 0.66357391434030388, 0.76805119403344102],
[0.5156955988596057, 0.65994260812897998, 0.76732191489596169],
[0.51135992541601927, 0.65629853981831865, 0.76660663780645333],
[0.50708969576451657, 0.65264172403146448, 0.76590445660835849],
[0.5028853540415561, 0.64897216734095264, 0.76521446718174913],
[0.49874733661356069, 0.6452898684900934, 0.76453578734180083],
[0.4946761847863938, 0.64159484119504429, 0.76386719002130909],
[0.49067224938561221, 0.63788704858847078, 0.76320812763163837],
[0.4867359599430568, 0.63416646251100506, 0.76255780085924041],
[0.4828677867260272, 0.6304330455306234, 0.76191537149895305],
[0.47906816236197386, 0.62668676251860134, 0.76128000375662419],
[0.47533752394906287, 0.62292757283835809, 0.76065085571817748],
[0.47167629518877091, 0.61915543242884641, 0.76002709227883047],
[0.46808490970531597, 0.61537028695790286, 0.75940789891092741],
[0.46456376716303932, 0.61157208822864151, 0.75879242623025811],
[0.46111326647023881, 0.607760777169989, 0.75817986436807139],
[0.45773377230160567, 0.60393630046586455, 0.75756936901859162],
[0.45442563977552913, 0.60009859503858665, 0.75696013660606487],
[0.45118918687617743, 0.59624762051353541, 0.75635120643246645],
[0.44802470933589172, 0.59238331452146575, 0.75574176474107924],
[0.44493246854215379, 0.5885055998308617, 0.7551311041857901],
[0.44191271766696399, 0.58461441100175571, 0.75451838884410671],
[0.43896563958048396, 0.58070969241098491, 0.75390276208285945],
[0.43609138958356369, 0.57679137998186081, 0.7532834105961016],
[0.43329008867358393, 0.57285941625606673, 0.75265946532566674],
[0.43056179073057571, 0.56891374572457176, 0.75203008099312696],
[0.42790652284925834, 0.5649543060909209, 0.75139443521914839],
[0.42532423665011354, 0.56098104959950301, 0.75075164989005116],
[0.42281485675772662, 0.55699392126996583, 0.75010086988227642],
[0.42037822361396326, 0.55299287158108168, 0.7494412559451894],
[0.41801414079233629, 0.54897785421888889, 0.74877193167001121],
[0.4157223260454232, 0.54494882715350401, 0.74809204459000522],
[0.41350245743314729, 0.54090574771098476, 0.74740073297543086],
[0.41135414697304568, 0.53684857765005933, 0.74669712855065784],
[0.4092768899914751, 0.53277730177130322, 0.74598030635707824],
[0.40727018694219069, 0.52869188011057411, 0.74524942637581271],
[0.40533343789303178, 0.52459228174983119, 0.74450365836708132],
[0.40346600333905397, 0.52047847653840029, 0.74374215223567086],
[0.40166714010896104, 0.51635044969688759, 0.7429640345324835],
[0.39993606933454834, 0.51220818143218516, 0.74216844571317986],
[0.3982719152586337, 0.50805166539276136, 0.74135450918099721],
[0.39667374905665609, 0.50388089053847973, 0.74052138580516735],
[0.39514058808207631, 0.49969585326377758, 0.73966820211715711],
[0.39367135736822567, 0.49549655777451179, 0.738794102296364],
[0.39226494876209317, 0.49128300332899261, 0.73789824784475078],
[0.39092017571994903, 0.48705520251223039, 0.73697977133881254],
[0.38963580160340855, 0.48281316715123496, 0.73603782546932739],
[0.38841053300842432, 0.47855691131792805, 0.73507157641157261],
[0.38724301459330251, 0.47428645933635388, 0.73408016787854391],
[0.38613184178892102, 0.4700018340988123, 0.7330627749243106],
[0.38507556793651387, 0.46570306719930193, 0.73201854033690505],
[0.38407269378943537, 0.46139018782416635, 0.73094665432902683],
[0.38312168084402748, 0.45706323581407199, 0.72984626791353258],
[0.38222094988570376, 0.45272225034283325, 0.72871656144003782],
[0.38136887930454161, 0.44836727669277859, 0.72755671317141346],
[0.38056380696565623, 0.44399837208633719, 0.72636587045135315],
[0.37980403744848751, 0.43961558821222629, 0.72514323778761092],
[0.37908789283110761, 0.43521897612544935, 0.72388798691323131],
[0.378413635091359, 0.43080859411413064, 0.72259931993061044],
[0.37777949753513729, 0.4263845142616835, 0.72127639993530235],
[0.37718371844251231, 0.42194680223454828, 0.71991841524475775],
[0.37662448930806297, 0.41749553747893614, 0.71852454736176108],
[0.37610001286385814, 0.41303079952477062, 0.71709396919920232],
[0.37560846919442398, 0.40855267638072096, 0.71562585091587549],
[0.37514802505380473, 0.4040612609993941, 0.7141193695725726],
[0.37471686019302231, 0.3995566498711684, 0.71257368516500463],
[0.37431313199312338, 0.39503894828283309, 0.71098796522377461],
[0.37393499330475782, 0.39050827529375831, 0.70936134293478448],
[0.3735806215098284, 0.38596474386057539, 0.70769297607310577],
[0.37324816143326384, 0.38140848555753937, 0.70598200974806036],
[0.37293578646665032, 0.37683963835219841, 0.70422755780589941],
[0.37264166757849604, 0.37225835004836849, 0.7024287314570723],
[0.37236397858465387, 0.36766477862108266, 0.70058463496520773],
[0.37210089702443822, 0.36305909736982378, 0.69869434615073722],
[0.3718506155898596, 0.35844148285875221, 0.69675695810256544],
[0.37161133234400479, 0.3538121372967869, 0.69477149919380887],
[0.37138124223736607, 0.34917126878479027, 0.69273703471928827],
[0.37115856636209105, 0.34451911410230168, 0.69065253586464992],
[0.37094151551337329, 0.33985591488818123, 0.68851703379505125],
[0.37072833279422668, 0.33518193808489577, 0.68632948169606767],
[0.37051738634484427, 0.33049741244307851, 0.68408888788857214],
[0.37030682071842685, 0.32580269697872455, 0.68179411684486679],
[0.37009487130772695, 0.3210981375964933, 0.67944405399056851],
[0.36987980329025361, 0.31638410101153364, 0.67703755438090574],
[0.36965987626565955, 0.31166098762951971, 0.67457344743419545],
[0.36943334591276228, 0.30692923551862339, 0.67205052849120617],
[0.36919847837592484, 0.30218932176507068, 0.66946754331614522],
[0.36895355306596778, 0.29744175492366276, 0.66682322089824264],
[0.36869682231895268, 0.29268709856150099, 0.66411625298236909],
[0.36842655638020444, 0.28792596437778462, 0.66134526910944602],
[0.36814101479899719, 0.28315901221182987, 0.65850888806972308],
[0.36783843696531082, 0.27838697181297761, 0.65560566838453704],
[0.36751707094367697, 0.27361063317090978, 0.65263411711618635],
[0.36717513650699446, 0.26883085667326956, 0.64959272297892245],
[0.36681085540107988, 0.26404857724525643, 0.64647991652908243],
[0.36642243251550632, 0.25926481158628106, 0.64329409140765537],
[0.36600853966739794, 0.25448043878086224, 0.64003361803368586],
[0.36556698373538982, 0.24969683475296395, 0.63669675187488584],
[0.36509579845886808, 0.24491536803550484, 0.63328173520055586],
[0.36459308890125008, 0.24013747024823828, 0.62978680155026101],
[0.36405693022088509, 0.23536470386204195, 0.62621013451953023],
[0.36348537610385145, 0.23059876218396419, 0.62254988622392882],
[0.36287643560041027, 0.22584149293287031, 0.61880417410823019],
[0.36222809558295926, 0.22109488427338303, 0.61497112346096128],
[0.36153829010998356, 0.21636111429594002, 0.61104880679640927],
[0.36080493826624654, 0.21164251793458128, 0.60703532172064711],
[0.36002681809096376, 0.20694122817889948, 0.60292845431916875],
[0.35920088560930186, 0.20226037920758122, 0.5987265295935138],
[0.35832489966617809, 0.197602942459778, 0.59442768517501066],
[0.35739663292915563, 0.19297208197842461, 0.59003011251063131],
[0.35641381143126327, 0.18837119869242164, 0.5855320765920552],
[0.35537415306906722, 0.18380392577704466, 0.58093191431832802],
[0.35427534960663759, 0.17927413271618647, 0.57622809660668717],
[0.35311574421123737, 0.17478570377561287, 0.57141871523555288],
[0.35189248608873791, 0.17034320478524959, 0.56650284911216653],
[0.35060304441931012, 0.16595129984720861, 0.56147964703993225],
[0.34924513554955644, 0.16161477763045118, 0.55634837474163779],
[0.34781653238777782, 0.15733863511152979, 0.55110853452703257],
[0.34631507175793091, 0.15312802296627787, 0.5457599924248665],
[0.34473901574536375, 0.14898820589826409, 0.54030245920406539],
[0.34308600291572294, 0.14492465359918028, 0.53473704282067103],
[0.34135411074506483, 0.1409427920655632, 0.52906500940336754],
[0.33954168752669694, 0.13704801896718169, 0.52328797535085236],
[0.33764732090671112, 0.13324562282438077, 0.51740807573979475],
[0.33566978565015315, 0.12954074251271822, 0.51142807215168951],
[0.33360804901486002, 0.12593818301005921, 0.50535164796654897],
[0.33146154891145124, 0.12244245263391232, 0.49918274588431072],
[0.32923005203231409, 0.11905764321981127, 0.49292595612342666],
[0.3269137124539796, 0.1157873496841953, 0.48658646495697461],
[0.32451307931207785, 0.11263459791730848, 0.48017007211645196],
[0.32202882276069322, 0.10960114111258401, 0.47368494725726878],
[0.31946262395497965, 0.10668879882392659, 0.46713728801395243],
[0.31681648089023501, 0.10389861387653518, 0.46053414662739794],
[0.31409278414755532, 0.10123077676403242, 0.45388335612058467],
[0.31129434479712365, 0.098684771934052201, 0.44719313715161618],
[0.30842444457210105, 0.096259385340577736, 0.44047194882050544],
[0.30548675819945936, 0.093952764840823738, 0.43372849999361113],
[0.30248536364574252, 0.091761187397303601, 0.42697404043749887],
[0.29942483960214772, 0.089682253716750038, 0.42021619665853854],
[0.29631000388905288, 0.087713250960463951, 0.41346259134143476],
[0.29314593096985248, 0.085850656889620708, 0.40672178082365834],
[0.28993792445176608, 0.08409078829085731, 0.40000214725256295],
[0.28669151388283165, 0.082429873848480689, 0.39331182532243375],
[0.28341239797185225, 0.080864153365499375, 0.38665868550105914],
[0.28010638576975472, 0.079389994802261526, 0.38005028528138707],
[0.27677939615815589, 0.078003941033788216, 0.37349382846504675],
[0.27343739342450812, 0.076702800237496066, 0.36699616136347685],
[0.27008637749114051, 0.075483675584275545, 0.36056376228111864],
[0.26673233211995284, 0.074344018028546205, 0.35420276066240958],
[0.26338121807151404, 0.073281657939897077, 0.34791888996380105],
[0.26003895187439957, 0.072294781043362205, 0.3417175669546984],
[0.25671191651083902, 0.071380106242082242, 0.33560648984600089],
[0.25340685873736807, 0.070533582926851829, 0.3295945757321303],
[0.25012845306199383, 0.069758206429106989, 0.32368100685760637],
[0.24688226237958999, 0.069053639449204451, 0.31786993834254956],
[0.24367372557466271, 0.068419855150922693, 0.31216524050888372],
[0.24050813332295939, 0.067857103814855602, 0.30657054493678321],
[0.23739062429054825, 0.067365888050555517, 0.30108922184065873],
[0.23433055727563878, 0.066935599661639394, 0.29574009929867601],
[0.23132955273021344, 0.066576186939090592, 0.29051361067988485],
[0.2283917709422868, 0.06628997924139618, 0.28541074411068496],
[0.22552164337737857, 0.066078173119395595, 0.28043398847505197],
[0.22272706739121817, 0.065933790675651943, 0.27559714652053702],
[0.22001251100779617, 0.065857918918907604, 0.27090279994325861],
[0.21737845072382705, 0.065859661233562045, 0.26634209349669508],
[0.21482843531473683, 0.065940385613778491, 0.26191675992376573],
[0.21237411048541005, 0.066085024661758446, 0.25765165093569542],
[0.21001214221188125, 0.066308573918947178, 0.2535289048041211],
[0.2077442377448806, 0.06661453200418091, 0.24954644291943817],
[0.20558051999470117, 0.066990462397868739, 0.24572497420147632],
[0.20352007949514977, 0.067444179612424215, 0.24205576625191821],
[0.20156133764129841, 0.067983271026200248, 0.23852974228695395],
[0.19971571438603364, 0.068592710553704722, 0.23517094067076993],
[0.19794834061899208, 0.069314066071660657, 0.23194647381302336],
[0.1960826032659409, 0.070321227242423623, 0.22874673279569585],
[0.19410351363791453, 0.071608304856891569, 0.22558727307410353],
[0.19199449184606268, 0.073182830649273306, 0.22243385243433622],
[0.18975853639094634, 0.075019861862143766, 0.2193005075652994],
[0.18739228342697645, 0.077102096899588329, 0.21618875376309582],
[0.18488035509396164, 0.079425730279723883, 0.21307651648984993],
[0.18774482037046955, 0.077251588468039312, 0.21387448578597812],
[0.19049578401722037, 0.075311278416787641, 0.2146562337112265],
[0.1931548636579131, 0.073606819040117955, 0.21542362939081539],
[0.19571853588267552, 0.072157781039602742, 0.21617499187076789],
[0.19819343656336558, 0.070974625252738788, 0.21690975060032436],
[0.20058760685133747, 0.070064576149984209, 0.21762721310371608],
[0.20290365333558247, 0.069435248580458964, 0.21833167885096033],
[0.20531725273301316, 0.068919592266397572, 0.21911516689288835],
[0.20785704662965598, 0.068484398797025281, 0.22000133917653536],
[0.21052882914958676, 0.06812195249816172, 0.22098759107715404],
[0.2133313859647627, 0.067830148426026665, 0.22207043213024291],
[0.21625279838647882, 0.067616330270516389, 0.22324568672294431],
[0.21930503925136402, 0.067465786362940039, 0.22451023616807558],
[0.22247308588973624, 0.067388214053092838, 0.22585960379408354],
[0.2257539681670791, 0.067382132300147474, 0.22728984778098055],
[0.22915620278592841, 0.067434730871152565, 0.22879681433956656],
[0.23266299920501882, 0.067557104388479783, 0.23037617493752832],
[0.23627495835774248, 0.06774359820987802, 0.23202360805926608],
[0.23999586188690308, 0.067985029964779953, 0.23373434258507808],
[0.24381149720247919, 0.068289851529011875, 0.23550427698321885],
[0.24772092990501099, 0.068653337909486523, 0.2373288009471749],
[0.25172899728289466, 0.069064630826035506, 0.23920260612763083],
[0.25582135547481771, 0.06953231029187984, 0.24112190491594204],
[0.25999463887892144, 0.070053855603861875, 0.24308218808684579],
[0.26425512207060942, 0.070616595622995437, 0.24507758869355967],
[0.26859095948172862, 0.071226716277922458, 0.24710443563450618],
[0.27299701518897301, 0.071883555446163511, 0.24915847093232929],
[0.27747150809142801, 0.072582969899254779, 0.25123493995942769],
[0.28201746297366942, 0.073315693214040967, 0.25332800295084507],
[0.28662309235899847, 0.074088460826808866, 0.25543478673717029],
[0.29128515387578635, 0.074899049847466703, 0.25755101595750435],
[0.2960004726065818, 0.075745336000958424, 0.25967245030364566],
[0.30077276812918691, 0.076617824336164764, 0.26179294097819672],
[0.30559226007249934, 0.077521963107537312, 0.26391006692119662],
[0.31045520848595526, 0.078456871676182177, 0.2660200572779356],
[0.31535870009205808, 0.079420997315243186, 0.26811904076941961],
[0.32029986557994061, 0.080412994737554838, 0.27020322893039511],
[0.32527888860401261, 0.081428390076546092, 0.27226772884656186],
[0.33029174471181438, 0.08246763389003825, 0.27430929404579435],
[0.33533353224455448, 0.083532434119003962, 0.27632534356790039],
[0.34040164359597463, 0.084622236191702671, 0.27831254595259397],
[0.34549355713871799, 0.085736654965126335, 0.28026769921081435],
[0.35060678246032478, 0.08687555176033529, 0.28218770540182386],
[0.35573889947341125, 0.088038974350243354, 0.2840695897279818],
[0.36088752387578377, 0.089227194362745205, 0.28591050458531014],
[0.36605031412464006, 0.090440685427697898, 0.2877077458811747],
[0.37122508431309342, 0.091679997480262732, 0.28945865397633169],
[0.3764103053221462, 0.092945198093777909, 0.29116024157313919],
[0.38160247377467543, 0.094238731263712183, 0.29281107506269488],
[0.38679939079544168, 0.09556181960083443, 0.29440901248173756],
[0.39199887556812907, 0.09691583650296684, 0.29595212005509081],
[0.39719876876325577, 0.098302320968278623, 0.29743856476285779],
[0.40239692379737496, 0.099722930314950553, 0.29886674369733968],
[0.40759120392688708, 0.10117945586419633, 0.30023519507728602],
[0.41277985630360303, 0.1026734006932461, 0.30154226437468967],
[0.41796105205173684, 0.10420644885760968, 0.30278652039631843],
[0.42313214269556043, 0.10578120994917611, 0.3039675809469457],
[0.42829101315789753, 0.1073997763055258, 0.30508479060294547],
[0.4334355841041439, 0.1090642347484701, 0.30613767928289148],
[0.43856378187931538, 0.11077667828375456, 0.30712600062348083],
[0.44367358645071275, 0.11253912421257944, 0.30804973095465449],
[0.44876299173174822, 0.11435355574622549, 0.30890905921943196],
[0.45383005086999889, 0.11622183788331528, 0.30970441249844921],
[0.45887288947308297, 0.11814571137706886, 0.31043636979038808],
[0.46389102840284874, 0.12012561256850712, 0.31110343446582983],
[0.46888111384598413, 0.12216445576414045, 0.31170911458932665],
[0.473841437035254, 0.12426354237989065, 0.31225470169927194],
[0.47877034239726296, 0.12642401401409453, 0.31274172735821959],
[0.48366628618847957, 0.12864679022013889, 0.31317188565991266],
[0.48852847371852987, 0.13093210934893723, 0.31354553695453014],
[0.49335504375145617, 0.13328091630401023, 0.31386561956734976],
[0.49814435462074153, 0.13569380302451714, 0.314135190862664],
[0.50289524974970612, 0.13817086581280427, 0.31435662153833671],
[0.50760681181053691, 0.14071192654913128, 0.31453200120082569],
[0.51227835105321762, 0.14331656120063752, 0.3146630922831542],
[0.51690848800544464, 0.14598463068714407, 0.31475407592280041],
[0.52149652863229956, 0.14871544765633712, 0.31480767954534428],
[0.52604189625477482, 0.15150818660835483, 0.31482653406646727],
[0.53054420489856446, 0.15436183633886777, 0.31481299789187128],
[0.5350027976174474, 0.15727540775107324, 0.31477085207396532],
[0.53941736649199057, 0.16024769309971934, 0.31470295028655965],
[0.54378771313608565, 0.16327738551419116, 0.31461204226295625],
[0.54811370033467621, 0.1663630904279047, 0.31450102990914708],
[0.55239521572711914, 0.16950338809328983, 0.31437291554615371],
[0.55663229034969341, 0.17269677158182117, 0.31423043195101424],
[0.56082499039117173, 0.17594170887918095, 0.31407639883970623],
[0.56497343529017696, 0.17923664950367169, 0.3139136046337036],
[0.56907784784011428, 0.18258004462335425, 0.31374440956796529],
[0.57313845754107873, 0.18597036007065024, 0.31357126868520002],
[0.57715550812992045, 0.18940601489760422, 0.31339704333572083],
[0.58112932761586555, 0.19288548904692518, 0.31322399394183942],
[0.58506024396466882, 0.19640737049066315, 0.31305401163732732],
[0.58894861935544707, 0.19997020971775276, 0.31288922211590126],
[0.59279480536520257, 0.20357251410079796, 0.31273234839304942],
[0.59659918109122367, 0.207212956082026, 0.31258523031121233],
[0.60036213010411577, 0.21089030138947745, 0.31244934410414688],
[0.60408401696732739, 0.21460331490206347, 0.31232652641170694],
[0.60776523994818654, 0.21835070166659282, 0.31221903291870201],
[0.6114062072731884, 0.22213124697023234, 0.31212881396435238],
[0.61500723236391375, 0.22594402043981826, 0.31205680685765741],
[0.61856865258877192, 0.22978799249179921, 0.31200463838728931],
[0.62209079821082613, 0.2336621873300741, 0.31197383273627388],
[0.62557416500434959, 0.23756535071152696, 0.31196698314912269],
[0.62901892016985872, 0.24149689191922535, 0.31198447195645718],
[0.63242534854210275, 0.24545598775548677, 0.31202765974624452],
[0.6357937104834237, 0.24944185818822678, 0.31209793953300591],
[0.6391243387840212, 0.25345365461983138, 0.31219689612063978],
[0.642417577481186, 0.257490519876798, 0.31232631707560987],
[0.64567349382645434, 0.26155203161615281, 0.31248673753935263],
[0.64889230169458245, 0.26563755336209077, 0.31267941819570189],
[0.65207417290277303, 0.26974650525236699, 0.31290560605819168],
[0.65521932609327127, 0.27387826652410152, 0.3131666792687211],
[0.6583280801134499, 0.27803210957665631, 0.3134643447952643],
[0.66140037532601781, 0.28220778870555907, 0.31379912926498488],
[0.66443632469878844, 0.28640483614256179, 0.31417223403606975],
[0.66743603766369131, 0.29062280081258873, 0.31458483752056837],
[0.67039959547676198, 0.29486126309253047, 0.31503813956872212],
[0.67332725564817331, 0.29911962764489264, 0.31553372323982209],
[0.67621897924409746, 0.30339762792450425, 0.3160724937230589],
[0.67907474028157344, 0.30769497879760166, 0.31665545668946665],
[0.68189457150944521, 0.31201133280550686, 0.31728380489244951],
[0.68467850942494535, 0.31634634821222207, 0.31795870784057567],
[0.68742656435169625, 0.32069970535138104, 0.31868137622277692],
[0.6901389321505248, 0.32507091815606004, 0.31945332332898302],
[0.69281544846764931, 0.32945984647042675, 0.3202754315314667],
[0.69545608346891119, 0.33386622163232865, 0.32114884306985791],
[0.6980608153581771, 0.33828976326048621, 0.32207478855218091],
[0.70062962477242097, 0.34273019305341756, 0.32305449047765694],
[0.70316249458814151, 0.34718723719597999, 0.32408913679491225],
[0.70565951122610093, 0.35166052978120937, 0.32518014084085567],
[0.70812059568420482, 0.35614985523380299, 0.32632861885644465],
[0.7105456546582587, 0.36065500290840113, 0.32753574162788762],
[0.71293466839773467, 0.36517570519856757, 0.3288027427038317],
[0.71528760614847287, 0.36971170225223449, 0.3301308728723546],
[0.71760444908133847, 0.37426272710686193, 0.33152138620958932],
[0.71988521490549851, 0.37882848839337313, 0.33297555200245399],
[0.7221299918421461, 0.38340864508963057, 0.33449469983585844],
[0.72433865647781592, 0.38800301593162145, 0.33607995965691828],
[0.72651122900227549, 0.3926113126792577, 0.3377325942005665],
[0.72864773856716547, 0.39723324476747235, 0.33945384341064017],
[0.73074820754845171, 0.401868526884681, 0.3412449533046818],
[0.73281270506268747, 0.4065168468778026, 0.34310715173410822],
[0.73484133598564938, 0.41117787004519513, 0.34504169470809071],
[0.73683422173585866, 0.41585125850290111, 0.34704978520758401],
[0.73879140024599266, 0.42053672992315327, 0.34913260148542435],
[0.74071301619506091, 0.4252339389526239, 0.35129130890802607],
[0.7425992159973317, 0.42994254036133867, 0.35352709245374592],
[0.74445018676570673, 0.43466217184617112, 0.35584108091122535],
[0.74626615789163442, 0.43939245044973502, 0.35823439142300639],
[0.74804739275559562, 0.44413297780351974, 0.36070813602540136],
[0.74979420547170472, 0.44888333481548809, 0.36326337558360278],
[0.75150685045891663, 0.45364314496866825, 0.36590112443835765],
[0.75318566369046569, 0.45841199172949604, 0.36862236642234769],
[0.75483105066959544, 0.46318942799460555, 0.3714280448394211],
[0.75644341577140706, 0.46797501437948458, 0.37431909037543515],
[0.75802325538455839, 0.4727682731566229, 0.37729635531096678],
[0.75957111105340058, 0.47756871222057079, 0.380360657784311],
[0.7610876378057071, 0.48237579130289127, 0.38351275723852291],
[0.76257333554052609, 0.48718906673415824, 0.38675335037837993],
[0.76402885609288662, 0.49200802533379656, 0.39008308392311997],
[0.76545492593330511, 0.49683212909727231, 0.39350254000115381],
[0.76685228950643891, 0.5016608471009063, 0.39701221751773474],
[0.76822176599735303, 0.50649362371287909, 0.40061257089416885],
[0.7695642334401418, 0.5113298901696085, 0.40430398069682483],
[0.77088091962302474, 0.51616892643469103, 0.40808667584648967],
[0.77217257229605551, 0.5210102658711383, 0.41196089987122869],
[0.77344021829889886, 0.52585332093451564, 0.41592679539764366],
[0.77468494746063199, 0.53069749384776732, 0.41998440356963762],
[0.77590790730685699, 0.53554217882461186, 0.42413367909988375],
[0.7771103295521099, 0.54038674910561235, 0.42837450371258479],
[0.77829345807633121, 0.54523059488426595, 0.432706647838971],
[0.77945862731506643, 0.55007308413977274, 0.43712979856444761],
[0.78060774749483774, 0.55491335744890613, 0.44164332426364639],
[0.78174180478981836, 0.55975098052594863, 0.44624687186865436],
[0.78286225264440912, 0.56458533111166875, 0.45093985823706345],
[0.78397060836414478, 0.56941578326710418, 0.45572154742892063],
[0.78506845019606841, 0.5742417003617839, 0.46059116206904965],
[0.78615737132332963, 0.5790624629815756, 0.46554778281918402],
[0.78723904108188347, 0.58387743744557208, 0.47059039582133383],
[0.78831514045623963, 0.58868600173562435, 0.47571791879076081],
[0.78938737766251943, 0.5934875421745599, 0.48092913815357724],
[0.79045776847727878, 0.59828134277062461, 0.48622257801969754],
[0.79152832843475607, 0.60306670593147205, 0.49159667021646397],
[0.79260034304237448, 0.60784322087037024, 0.49705020621532009],
[0.79367559698664958, 0.61261029334072192, 0.50258161291269432],
[0.79475585972654039, 0.61736734400220705, 0.50818921213102985],
[0.79584292379583765, 0.62211378808451145, 0.51387124091909786],
[0.79693854719951607, 0.62684905679296699, 0.5196258425240281],
[0.79804447815136637, 0.63157258225089552, 0.52545108144834785],
[0.7991624518501963, 0.63628379372029187, 0.53134495942561433],
[0.80029415389753977, 0.64098213306749863, 0.53730535185141037],
[0.80144124292560048, 0.64566703459218766, 0.5433300863249918],
[0.80260531146112946, 0.65033793748103852, 0.54941691584603647],
[0.80378792531077625, 0.65499426549472628, 0.55556350867083815],
[0.80499054790810298, 0.65963545027564163, 0.56176745110546977],
[0.80621460526927058, 0.66426089585282289, 0.56802629178649788],
[0.8074614045096935, 0.6688700095398864, 0.57433746373459582],
[0.80873219170089694, 0.67346216702194517, 0.58069834805576737],
[0.81002809466520687, 0.67803672673971815, 0.58710626908082753],
[0.81135014011763329, 0.68259301546243389, 0.59355848909050757],
[0.81269922039881493, 0.68713033714618876, 0.60005214820435104],
[0.81407611046993344, 0.69164794791482131, 0.6065843782630862],
[0.81548146627279483, 0.69614505508308089, 0.61315221209322646],
[0.81691575775055891, 0.70062083014783982, 0.61975260637257923],
[0.81837931164498223, 0.70507438189635097, 0.62638245478933297],
[0.81987230650455289, 0.70950474978787481, 0.63303857040067113],
[0.8213947205565636, 0.7139109141951604, 0.63971766697672761],
[0.82294635110428427, 0.71829177331290062, 0.6464164243818421],
[0.8245268129450285, 0.72264614312088882, 0.65313137915422603],
[0.82613549710580259, 0.72697275518238258, 0.65985900156216504],
[0.8277716072353446, 0.73127023324078089, 0.66659570204682972],
[0.82943407816481474, 0.7355371221572935, 0.67333772009301907],
[0.83112163529096306, 0.73977184647638616, 0.68008125203631464],
[0.83283277185777982, 0.74397271817459876, 0.68682235874648545],
[0.8345656905566583, 0.7481379479992134, 0.69355697649863846],
[0.83631898844737929, 0.75226548952875261, 0.70027999028864962],
[0.83809123476131964, 0.75635314860808633, 0.70698561390212977],
[0.83987839884120874, 0.76039907199779677, 0.71367147811129228],
[0.84167750766845151, 0.76440101200982946, 0.72033299387284622],
[0.84348529222933699, 0.76835660399870176, 0.72696536998972039],
[0.84529810731955113, 0.77226338601044719, 0.73356368240541492],
[0.84711195507965098, 0.77611880236047159, 0.74012275762807056],
[0.84892245563117641, 0.77992021407650147, 0.74663719293664366],
[0.85072697023178789, 0.78366457342383888, 0.7530974636118285],
[0.85251907207708444, 0.78734936133548439, 0.7594994148789691],
[0.85429219611470464, 0.79097196777091994, 0.76583801477914104],
[0.85604022314725403, 0.79452963601550608, 0.77210610037674143],
[0.85775662943504905, 0.79801963142713928, 0.77829571667247499],
[0.8594346370300241, 0.8014392309950078, 0.78439788751383921],
[0.86107117027565516, 0.80478517909812231, 0.79039529663736285],
[0.86265601051127572, 0.80805523804261525, 0.796282666437655],
[0.86418343723941027, 0.81124644224653542, 0.80204612696863953],
[0.86564934325605325, 0.81435544067514909, 0.80766972324164554],
[0.86705314907048503, 0.81737804041911244, 0.81313419626911398],
[0.86839954695818633, 0.82030875512181523, 0.81841638963128993],
[0.86969131502613806, 0.82314158859569164, 0.82350476683173168],
[0.87093846717297507, 0.82586857889438514, 0.82838497261149613],
[0.87215331978454325, 0.82848052823709672, 0.8330486712880828],
[0.87335171360916275, 0.83096715251272624, 0.83748851001197089],
[0.87453793320260187, 0.83331972948645461, 0.84171925358069011],
[0.87571458709961403, 0.8355302318472394, 0.84575537519027078],
[0.87687848451614692, 0.83759238071186537, 0.84961373549150254],
[0.87802298436649007, 0.83950165618540074, 0.85330645352458923],
[0.87913244240792765, 0.84125554884475906, 0.85685572291039636],
[0.88019293315695812, 0.84285224824778615, 0.86027399927156634],
[0.88119169871341951, 0.84429066717717349, 0.86356595168669881],
[0.88211542489401606, 0.84557007254559347, 0.86673765046233331],
[0.88295168595448525, 0.84668970275699273, 0.86979617048190971],
[0.88369127145898041, 0.84764891761519268, 0.87274147101441557],
[0.88432713054113543, 0.84844741572055415, 0.87556785228242973],
[0.88485138159908572, 0.84908426422893801, 0.87828235285372469],
[0.88525897972630474, 0.84955892810989209, 0.88088414794024839],
[0.88554714811952384, 0.84987174283631584, 0.88336206121170946],
[0.88571155122845646, 0.85002186115856315, 0.88572538990087124]]
_twilight_shifted_data = (_twilight_data[len(_twilight_data)//2:] +
_twilight_data[:len(_twilight_data)//2])
_twilight_shifted_data.reverse()
cmaps = {}
for (name, data) in (('magma', _magma_data),
('inferno', _inferno_data),
('plasma', _plasma_data),
('viridis', _viridis_data),
('cividis', _cividis_data),
('twilight', _twilight_data),
('twilight_shifted', _twilight_shifted_data)):
cmaps[name] = ListedColormap(data, name=name)
# generate reversed colormap
name = name + '_r'
cmaps[name] = ListedColormap(list(reversed(data)), name=name)
|
3c7d6f3bcdfd71943afa63cd95a1cb24c8d35d11b7babcbffb36f69c73176269
|
# This file helps to compute a version number in source trees obtained from
# git-archive tarball (such as those provided by githubs download-from-tag
# feature). Distribution tarballs (built by setup.py sdist) and build
# directories (produced by setup.py build) will contain a much shorter file
# that just contains the computed version number.
# This file is released into the public domain. Generated by
# versioneer-0.15 (https://github.com/warner/python-versioneer)
import errno
import os
import re
import subprocess
import sys
def get_keywords():
# these strings will be replaced by git during git-archive.
# setup.py/versioneer.py will grep for the variable names, so they must
# each be defined on a line of their own. _version.py will just call
# get_keywords().
git_refnames = "$Format:%d$"
git_full = "$Format:%H$"
keywords = {"refnames": git_refnames, "full": git_full}
return keywords
class VersioneerConfig:
pass
def get_config():
# these strings are filled in when 'setup.py versioneer' creates
# _version.py
cfg = VersioneerConfig()
cfg.VCS = "git"
cfg.style = "pep440-post"
cfg.tag_prefix = "v"
cfg.parentdir_prefix = "matplotlib-"
cfg.versionfile_source = "lib/matplotlib/_version.py"
cfg.verbose = False
return cfg
class NotThisMethod(Exception):
pass
LONG_VERSION_PY = {}
HANDLERS = {}
def register_vcs_handler(vcs, method): # decorator
def decorate(f):
if vcs not in HANDLERS:
HANDLERS[vcs] = {}
HANDLERS[vcs][method] = f
return f
return decorate
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False):
assert isinstance(commands, list)
p = None
for c in commands:
try:
dispcmd = str([c] + args)
# remember shell=False, so use git.cmd on windows, not just git
p = subprocess.Popen([c] + args, cwd=cwd, stdout=subprocess.PIPE,
stderr=(subprocess.PIPE if hide_stderr
else None))
break
except EnvironmentError:
e = sys.exc_info()[1]
if e.errno == errno.ENOENT:
continue
if verbose:
print("unable to run %s" % dispcmd)
print(e)
return None
else:
if verbose:
print("unable to find command, tried %s" % (commands,))
return None
stdout = p.communicate()[0].strip()
if sys.version_info[0] >= 3:
stdout = stdout.decode()
if p.returncode != 0:
if verbose:
print("unable to run %s (error)" % dispcmd)
return None
return stdout
def versions_from_parentdir(parentdir_prefix, root, verbose):
# Source tarballs conventionally unpack into a directory that includes
# both the project name and a version string.
dirname = os.path.basename(root)
if not dirname.startswith(parentdir_prefix):
if verbose:
print("guessing rootdir is '%s', but '%s' doesn't start with "
"prefix '%s'" % (root, dirname, parentdir_prefix))
raise NotThisMethod("rootdir doesn't start with parentdir_prefix")
return {"version": dirname[len(parentdir_prefix):],
"full-revisionid": None,
"dirty": False, "error": None}
@register_vcs_handler("git", "get_keywords")
def git_get_keywords(versionfile_abs):
# the code embedded in _version.py can just fetch the value of these
# keywords. When used from setup.py, we don't want to import _version.py,
# so we do it with a regexp instead. This function is not used from
# _version.py.
keywords = {}
try:
f = open(versionfile_abs, "r")
for line in f.readlines():
if line.strip().startswith("git_refnames ="):
mo = re.search(r'=\s*"(.*)"', line)
if mo:
keywords["refnames"] = mo.group(1)
if line.strip().startswith("git_full ="):
mo = re.search(r'=\s*"(.*)"', line)
if mo:
keywords["full"] = mo.group(1)
f.close()
except EnvironmentError:
pass
return keywords
@register_vcs_handler("git", "keywords")
def git_versions_from_keywords(keywords, tag_prefix, verbose):
if not keywords:
raise NotThisMethod("no keywords at all, weird")
refnames = keywords["refnames"].strip()
if refnames.startswith("$Format"):
if verbose:
print("keywords are unexpanded, not using")
raise NotThisMethod("unexpanded keywords, not a git-archive tarball")
refs = set([r.strip() for r in refnames.strip("()").split(",")])
# starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
# just "foo-1.0". If we see a "tag: " prefix, prefer those.
TAG = "tag: "
tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)])
if not tags:
# Either we're using git < 1.8.3, or there really are no tags. We use
# a heuristic: assume all version tags have a digit. The old git %d
# expansion behaves like git log --decorate=short and strips out the
# refs/heads/ and refs/tags/ prefixes that would let us distinguish
# between branches and tags. By ignoring refnames without digits, we
# filter out many common branch names like "release" and
# "stabilization", as well as "HEAD" and "master".
tags = set([r for r in refs if re.search(r'\d', r)])
if verbose:
print("discarding '%s', no digits" % ",".join(refs-tags))
if verbose:
print("likely tags: %s" % ",".join(sorted(tags)))
for ref in sorted(tags):
# sorting will prefer e.g. "2.0" over "2.0rc1"
if ref.startswith(tag_prefix):
r = ref[len(tag_prefix):]
if verbose:
print("picking %s" % r)
return {"version": r,
"full-revisionid": keywords["full"].strip(),
"dirty": False, "error": None
}
# no suitable tags, so version is "0+unknown", but full hex is still there
if verbose:
print("no suitable tags, using unknown + full revision id")
return {"version": "0+unknown",
"full-revisionid": keywords["full"].strip(),
"dirty": False, "error": "no suitable tags"}
@register_vcs_handler("git", "pieces_from_vcs")
def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
# this runs 'git' from the root of the source tree. This only gets called
# if the git-archive 'subst' keywords were *not* expanded, and
# _version.py hasn't already been rewritten with a short version string,
# meaning we're inside a checked out source tree.
if not os.path.exists(os.path.join(root, ".git")):
if verbose:
print("no .git in %s" % root)
raise NotThisMethod("no .git directory")
GITS = ["git"]
if sys.platform == "win32":
GITS = ["git.cmd", "git.exe"]
# if there is a tag, this yields TAG-NUM-gHEX[-dirty]
# if there are no tags, this yields HEX[-dirty] (no NUM)
describe_out = run_command(GITS, ["describe", "--tags", "--dirty",
"--always", "--long"],
cwd=root)
# --long was added in git-1.5.5
if describe_out is None:
raise NotThisMethod("'git describe' failed")
describe_out = describe_out.strip()
full_out = run_command(GITS, ["rev-parse", "HEAD"], cwd=root)
if full_out is None:
raise NotThisMethod("'git rev-parse' failed")
full_out = full_out.strip()
pieces = {}
pieces["long"] = full_out
pieces["short"] = full_out[:7] # maybe improved later
pieces["error"] = None
# parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty]
# TAG might have hyphens.
git_describe = describe_out
# look for -dirty suffix
dirty = git_describe.endswith("-dirty")
pieces["dirty"] = dirty
if dirty:
git_describe = git_describe[:git_describe.rindex("-dirty")]
# now we have TAG-NUM-gHEX or HEX
if "-" in git_describe:
# TAG-NUM-gHEX
mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe)
if not mo:
# unparseable. Maybe git-describe is misbehaving?
pieces["error"] = ("unable to parse git-describe output: '%s'"
% describe_out)
return pieces
# tag
full_tag = mo.group(1)
if not full_tag.startswith(tag_prefix):
if verbose:
fmt = "tag '%s' doesn't start with prefix '%s'"
print(fmt % (full_tag, tag_prefix))
pieces["error"] = ("tag '%s' doesn't start with prefix '%s'"
% (full_tag, tag_prefix))
return pieces
pieces["closest-tag"] = full_tag[len(tag_prefix):]
# distance: number of commits since tag
pieces["distance"] = int(mo.group(2))
# commit: short hex revision ID
pieces["short"] = mo.group(3)
else:
# HEX: no tags
pieces["closest-tag"] = None
count_out = run_command(GITS, ["rev-list", "HEAD", "--count"],
cwd=root)
pieces["distance"] = int(count_out) # total number of commits
return pieces
def plus_or_dot(pieces):
if "+" in pieces.get("closest-tag", ""):
return "."
return "+"
def render_pep440(pieces):
# now build up version string, with post-release "local version
# identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you
# get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty
# exceptions:
# 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
if pieces["distance"] or pieces["dirty"]:
rendered += plus_or_dot(pieces)
rendered += "%d.g%s" % (pieces["distance"], pieces["short"])
if pieces["dirty"]:
rendered += ".dirty"
else:
# exception #1
rendered = "0+untagged.%d.g%s" % (pieces["distance"],
pieces["short"])
if pieces["dirty"]:
rendered += ".dirty"
return rendered
def render_pep440_pre(pieces):
# TAG[.post.devDISTANCE] . No -dirty
# exceptions:
# 1: no tags. 0.post.devDISTANCE
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
if pieces["distance"]:
rendered += ".post.dev%d" % pieces["distance"]
else:
# exception #1
rendered = "0.post.dev%d" % pieces["distance"]
return rendered
def render_pep440_post(pieces):
# TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that
# .dev0 sorts backwards (a dirty tree will appear "older" than the
# corresponding clean one), but you shouldn't be releasing software with
# -dirty anyways.
# exceptions:
# 1: no tags. 0.postDISTANCE[.dev0]
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
if pieces["distance"] or pieces["dirty"]:
rendered += ".post%d" % pieces["distance"]
if pieces["dirty"]:
rendered += ".dev0"
rendered += plus_or_dot(pieces)
rendered += "g%s" % pieces["short"]
else:
# exception #1
rendered = "0.post%d" % pieces["distance"]
if pieces["dirty"]:
rendered += ".dev0"
rendered += "+g%s" % pieces["short"]
return rendered
def render_pep440_old(pieces):
# TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty.
# exceptions:
# 1: no tags. 0.postDISTANCE[.dev0]
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
if pieces["distance"] or pieces["dirty"]:
rendered += ".post%d" % pieces["distance"]
if pieces["dirty"]:
rendered += ".dev0"
else:
# exception #1
rendered = "0.post%d" % pieces["distance"]
if pieces["dirty"]:
rendered += ".dev0"
return rendered
def render_git_describe(pieces):
# TAG[-DISTANCE-gHEX][-dirty], like 'git describe --tags --dirty
# --always'
# exceptions:
# 1: no tags. HEX[-dirty] (note: no 'g' prefix)
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
if pieces["distance"]:
rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])
else:
# exception #1
rendered = pieces["short"]
if pieces["dirty"]:
rendered += "-dirty"
return rendered
def render_git_describe_long(pieces):
# TAG-DISTANCE-gHEX[-dirty], like 'git describe --tags --dirty
# --always -long'. The distance/hash is unconditional.
# exceptions:
# 1: no tags. HEX[-dirty] (note: no 'g' prefix)
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])
else:
# exception #1
rendered = pieces["short"]
if pieces["dirty"]:
rendered += "-dirty"
return rendered
def render(pieces, style):
if pieces["error"]:
return {"version": "unknown",
"full-revisionid": pieces.get("long"),
"dirty": None,
"error": pieces["error"]}
if not style or style == "default":
style = "pep440" # the default
if style == "pep440":
rendered = render_pep440(pieces)
elif style == "pep440-pre":
rendered = render_pep440_pre(pieces)
elif style == "pep440-post":
rendered = render_pep440_post(pieces)
elif style == "pep440-old":
rendered = render_pep440_old(pieces)
elif style == "git-describe":
rendered = render_git_describe(pieces)
elif style == "git-describe-long":
rendered = render_git_describe_long(pieces)
else:
raise ValueError("unknown style '%s'" % style)
return {"version": rendered, "full-revisionid": pieces["long"],
"dirty": pieces["dirty"], "error": None}
def get_versions():
# I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have
# __file__, we can work backwards from there to the root. Some
# py2exe/bbfreeze/non-CPython implementations don't do __file__, in which
# case we can only use expanded keywords.
cfg = get_config()
verbose = cfg.verbose
try:
return git_versions_from_keywords(get_keywords(), cfg.tag_prefix,
verbose)
except NotThisMethod:
pass
try:
root = os.path.realpath(__file__)
# versionfile_source is the relative path from the top of the source
# tree (where the .git directory might live) to this file. Invert
# this to find the root from __file__.
for _ in cfg.versionfile_source.split('/'):
root = os.path.dirname(root)
except NameError:
return {"version": "0+unknown", "full-revisionid": None,
"dirty": None,
"error": "unable to find root of source tree"}
try:
pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose)
return render(pieces, cfg.style)
except NotThisMethod:
pass
try:
if cfg.parentdir_prefix:
return versions_from_parentdir(cfg.parentdir_prefix, root, verbose)
except NotThisMethod:
pass
return {"version": "0+unknown", "full-revisionid": None,
"dirty": None,
"error": "unable to compute version"}
|
b3a899571acc204a69f209f8ac40b4c760f2216c56a6694fd33314b693b23675
|
# TODO:
# * Documentation -- this will need a new section of the User's Guide.
# Both for Animations and just timers.
# - Also need to update http://www.scipy.org/Cookbook/Matplotlib/Animations
# * Blit
# * Currently broken with Qt4 for widgets that don't start on screen
# * Still a few edge cases that aren't working correctly
# * Can this integrate better with existing matplotlib animation artist flag?
# - If animated removes from default draw(), perhaps we could use this to
# simplify initial draw.
# * Example
# * Frameless animation - pure procedural with no loop
# * Need example that uses something like inotify or subprocess
# * Complex syncing examples
# * Movies
# * Can blit be enabled for movies?
# * Need to consider event sources to allow clicking through multiple figures
import abc
import base64
import contextlib
from io import BytesIO, TextIOWrapper
import itertools
import logging
import os
from pathlib import Path
import platform
import shutil
import subprocess
import sys
from tempfile import TemporaryDirectory
import uuid
import numpy as np
import matplotlib as mpl
from matplotlib._animation_data import (
DISPLAY_TEMPLATE, INCLUDED_FRAMES, JS_INCLUDE, STYLE_INCLUDE)
from matplotlib import cbook, rcParams, rcParamsDefault, rc_context
_log = logging.getLogger(__name__)
# Process creation flag for subprocess to prevent it raising a terminal
# window. See for example:
# https://stackoverflow.com/questions/24130623/using-python-subprocess-popen-cant-prevent-exe-stopped-working-prompt
if platform.system() == 'Windows':
subprocess_creation_flags = CREATE_NO_WINDOW = 0x08000000
else:
# Apparently None won't work here
subprocess_creation_flags = 0
# Other potential writing methods:
# * http://pymedia.org/
# * libming (produces swf) python wrappers: https://github.com/libming/libming
# * Wrap x264 API:
# (http://stackoverflow.com/questions/2940671/
# how-to-encode-series-of-images-into-h264-using-x264-api-c-c )
def adjusted_figsize(w, h, dpi, n):
'''Compute figure size so that pixels are a multiple of n
Parameters
----------
w, h : float
Size in inches
dpi : float
The dpi
n : int
The target multiple
Returns
-------
wnew, hnew : float
The new figure size in inches.
'''
# this maybe simplified if / when we adopt consistent rounding for
# pixel size across the whole library
def correct_roundoff(x, dpi, n):
if int(x*dpi) % n != 0:
if int(np.nextafter(x, np.inf)*dpi) % n == 0:
x = np.nextafter(x, np.inf)
elif int(np.nextafter(x, -np.inf)*dpi) % n == 0:
x = np.nextafter(x, -np.inf)
return x
wnew = int(w * dpi / n) * n / dpi
hnew = int(h * dpi / n) * n / dpi
return (correct_roundoff(wnew, dpi, n), correct_roundoff(hnew, dpi, n))
# A registry for available MovieWriter classes
class MovieWriterRegistry(object):
'''Registry of available writer classes by human readable name.'''
def __init__(self):
self.avail = dict()
self._registered = dict()
self._dirty = False
def set_dirty(self):
"""Sets a flag to re-setup the writers."""
self._dirty = True
def register(self, name):
"""Decorator for registering a class under a name.
Example use::
@registry.register(name)
class Foo:
pass
"""
def wrapper(writerClass):
self._registered[name] = writerClass
if writerClass.isAvailable():
self.avail[name] = writerClass
return writerClass
return wrapper
def ensure_not_dirty(self):
"""If dirty, reasks the writers if they are available"""
if self._dirty:
self.reset_available_writers()
def reset_available_writers(self):
"""Reset the available state of all registered writers"""
self.avail = {name: writerClass
for name, writerClass in self._registered.items()
if writerClass.isAvailable()}
self._dirty = False
def list(self):
'''Get a list of available MovieWriters.'''
self.ensure_not_dirty()
return list(self.avail)
def is_available(self, name):
'''Check if given writer is available by name.
Parameters
----------
name : str
Returns
-------
available : bool
'''
self.ensure_not_dirty()
return name in self.avail
def __getitem__(self, name):
self.ensure_not_dirty()
if not self.avail:
raise RuntimeError("No MovieWriters available!")
try:
return self.avail[name]
except KeyError:
raise RuntimeError(
'Requested MovieWriter ({}) not available'.format(name))
writers = MovieWriterRegistry()
class AbstractMovieWriter(abc.ABC):
'''
Abstract base class for writing movies. Fundamentally, what a MovieWriter
does is provide is a way to grab frames by calling grab_frame().
setup() is called to start the process and finish() is called afterwards.
This class is set up to provide for writing movie frame data to a pipe.
saving() is provided as a context manager to facilitate this process as::
with moviewriter.saving(fig, outfile='myfile.mp4', dpi=100):
# Iterate over frames
moviewriter.grab_frame(**savefig_kwargs)
The use of the context manager ensures that setup() and finish() are
performed as necessary.
An instance of a concrete subclass of this class can be given as the
``writer`` argument of `Animation.save()`.
'''
@abc.abstractmethod
def setup(self, fig, outfile, dpi=None):
'''
Perform setup for writing the movie file.
Parameters
----------
fig : `matplotlib.figure.Figure` instance
The figure object that contains the information for frames
outfile : string
The filename of the resulting movie file
dpi : int, optional
The DPI (or resolution) for the file. This controls the size
in pixels of the resulting movie file. Default is ``fig.dpi``.
'''
@abc.abstractmethod
def grab_frame(self, **savefig_kwargs):
'''
Grab the image information from the figure and save as a movie frame.
All keyword arguments in savefig_kwargs are passed on to the `savefig`
command that saves the figure.
'''
@abc.abstractmethod
def finish(self):
'''Finish any processing for writing the movie.'''
@contextlib.contextmanager
def saving(self, fig, outfile, dpi, *args, **kwargs):
'''
Context manager to facilitate writing the movie file.
``*args, **kw`` are any parameters that should be passed to `setup`.
'''
# This particular sequence is what contextlib.contextmanager wants
self.setup(fig, outfile, dpi, *args, **kwargs)
try:
yield self
finally:
self.finish()
class MovieWriter(AbstractMovieWriter):
'''Base class for writing movies.
This is a base class for MovieWriter subclasses that write a movie frame
data to a pipe. You cannot instantiate this class directly.
See examples for how to use its subclasses.
Attributes
----------
frame_format : str
The format used in writing frame data, defaults to 'rgba'
fig : `~matplotlib.figure.Figure`
The figure to capture data from.
This must be provided by the sub-classes.
'''
def __init__(self, fps=5, codec=None, bitrate=None, extra_args=None,
metadata=None):
'''MovieWriter
Parameters
----------
fps : int
Framerate for movie.
codec : string or None, optional
The codec to use. If ``None`` (the default) the ``animation.codec``
rcParam is used.
bitrate : int or None, optional
The bitrate for the saved movie file, which is one way to control
the output file size and quality. The default value is ``None``,
which uses the ``animation.bitrate`` rcParam. A value of -1
implies that the bitrate should be determined automatically by the
underlying utility.
extra_args : list of strings or None, optional
A list of extra string arguments to be passed to the underlying
movie utility. The default is ``None``, which passes the additional
arguments in the ``animation.extra_args`` rcParam.
metadata : Dict[str, str] or None
A dictionary of keys and values for metadata to include in the
output file. Some keys that may be of use include:
title, artist, genre, subject, copyright, srcform, comment.
'''
if self.__class__ is MovieWriter:
# TODO MovieWriter is still an abstract class and needs to be
# extended with a mixin. This should be clearer in naming
# and description. For now, just give a reasonable error
# message to users.
raise TypeError(
'MovieWriter cannot be instantiated directly. Please use one '
'of its subclasses.')
self.fps = fps
self.frame_format = 'rgba'
if codec is None:
self.codec = rcParams['animation.codec']
else:
self.codec = codec
if bitrate is None:
self.bitrate = rcParams['animation.bitrate']
else:
self.bitrate = bitrate
if extra_args is None:
self.extra_args = list(rcParams[self.args_key])
else:
self.extra_args = extra_args
if metadata is None:
self.metadata = dict()
else:
self.metadata = metadata
@property
def frame_size(self):
'''A tuple ``(width, height)`` in pixels of a movie frame.'''
w, h = self.fig.get_size_inches()
return int(w * self.dpi), int(h * self.dpi)
def _adjust_frame_size(self):
if self.codec == 'h264':
wo, ho = self.fig.get_size_inches()
w, h = adjusted_figsize(wo, ho, self.dpi, 2)
if not (wo, ho) == (w, h):
self.fig.set_size_inches(w, h, forward=True)
_log.info('figure size (inches) has been adjusted '
'from %s x %s to %s x %s', wo, ho, w, h)
else:
w, h = self.fig.get_size_inches()
_log.debug('frame size in pixels is %s x %s', *self.frame_size)
return w, h
def setup(self, fig, outfile, dpi=None):
'''
Perform setup for writing the movie file.
Parameters
----------
fig : matplotlib.figure.Figure
The figure object that contains the information for frames
outfile : string
The filename of the resulting movie file
dpi : int, optional
The DPI (or resolution) for the file. This controls the size
in pixels of the resulting movie file. Default is fig.dpi.
'''
self.outfile = outfile
self.fig = fig
if dpi is None:
dpi = self.fig.dpi
self.dpi = dpi
self._w, self._h = self._adjust_frame_size()
# Run here so that grab_frame() can write the data to a pipe. This
# eliminates the need for temp files.
self._run()
def _run(self):
# Uses subprocess to call the program for assembling frames into a
# movie file. *args* returns the sequence of command line arguments
# from a few configuration options.
command = self._args()
_log.info('MovieWriter.run: running command: %s', command)
PIPE = subprocess.PIPE
self._proc = subprocess.Popen(
command, stdin=PIPE, stdout=PIPE, stderr=PIPE,
creationflags=subprocess_creation_flags)
def finish(self):
'''Finish any processing for writing the movie.'''
self.cleanup()
def grab_frame(self, **savefig_kwargs):
'''
Grab the image information from the figure and save as a movie frame.
All keyword arguments in savefig_kwargs are passed on to the `savefig`
command that saves the figure.
'''
_log.debug('MovieWriter.grab_frame: Grabbing frame.')
# re-adjust the figure size in case it has been changed by the
# user. We must ensure that every frame is the same size or
# the movie will not save correctly.
self.fig.set_size_inches(self._w, self._h)
# Tell the figure to save its data to the sink, using the
# frame format and dpi.
self.fig.savefig(self._frame_sink(), format=self.frame_format,
dpi=self.dpi, **savefig_kwargs)
def _frame_sink(self):
'''Return the place to which frames should be written.'''
return self._proc.stdin
def _args(self):
'''Assemble list of utility-specific command-line arguments.'''
return NotImplementedError("args needs to be implemented by subclass.")
def cleanup(self):
'''Clean-up and collect the process used to write the movie file.'''
out, err = self._proc.communicate()
self._frame_sink().close()
# Use the encoding/errors that universal_newlines would use.
out = TextIOWrapper(BytesIO(out)).read()
err = TextIOWrapper(BytesIO(err)).read()
if out:
_log.log(
logging.WARNING if self._proc.returncode else logging.DEBUG,
"MovieWriter stdout:\n%s", out)
if err:
_log.log(
logging.WARNING if self._proc.returncode else logging.DEBUG,
"MovieWriter stderr:\n%s", err)
if self._proc.returncode:
raise subprocess.CalledProcessError(
self._proc.returncode, self._proc.args, out, err)
@classmethod
def bin_path(cls):
'''
Return the binary path to the commandline tool used by a specific
subclass. This is a class method so that the tool can be looked for
before making a particular MovieWriter subclass available.
'''
return str(rcParams[cls.exec_key])
@classmethod
def isAvailable(cls):
'''
Check to see if a MovieWriter subclass is actually available.
'''
return shutil.which(cls.bin_path()) is not None
class FileMovieWriter(MovieWriter):
'''`MovieWriter` for writing to individual files and stitching at the end.
This must be sub-classed to be useful.
'''
def __init__(self, *args, **kwargs):
MovieWriter.__init__(self, *args, **kwargs)
self.frame_format = rcParams['animation.frame_format']
def setup(self, fig, outfile, dpi=None, frame_prefix='_tmp',
clear_temp=True):
'''Perform setup for writing the movie file.
Parameters
----------
fig : matplotlib.figure.Figure
The figure to grab the rendered frames from.
outfile : str
The filename of the resulting movie file.
dpi : number, optional
The dpi of the output file. This, with the figure size,
controls the size in pixels of the resulting movie file.
Default is fig.dpi.
frame_prefix : str, optional
The filename prefix to use for temporary files. Defaults to
``'_tmp'``.
clear_temp : bool, optional
If the temporary files should be deleted after stitching
the final result. Setting this to ``False`` can be useful for
debugging. Defaults to ``True``.
'''
self.fig = fig
self.outfile = outfile
if dpi is None:
dpi = self.fig.dpi
self.dpi = dpi
self._adjust_frame_size()
self.clear_temp = clear_temp
self.temp_prefix = frame_prefix
self._frame_counter = 0 # used for generating sequential file names
self._temp_names = list()
self.fname_format_str = '%s%%07d.%s'
@property
def frame_format(self):
'''
Format (png, jpeg, etc.) to use for saving the frames, which can be
decided by the individual subclasses.
'''
return self._frame_format
@frame_format.setter
def frame_format(self, frame_format):
if frame_format in self.supported_formats:
self._frame_format = frame_format
else:
self._frame_format = self.supported_formats[0]
def _base_temp_name(self):
# Generates a template name (without number) given the frame format
# for extension and the prefix.
return self.fname_format_str % (self.temp_prefix, self.frame_format)
def _frame_sink(self):
# Creates a filename for saving using the basename and the current
# counter.
fname = self._base_temp_name() % self._frame_counter
# Save the filename so we can delete it later if necessary
self._temp_names.append(fname)
_log.debug('FileMovieWriter.frame_sink: saving frame %d to fname=%s',
self._frame_counter, fname)
self._frame_counter += 1 # Ensures each created name is 'unique'
# This file returned here will be closed once it's used by savefig()
# because it will no longer be referenced and will be gc-ed.
return open(fname, 'wb')
def grab_frame(self, **savefig_kwargs):
'''
Grab the image information from the figure and save as a movie frame.
All keyword arguments in savefig_kwargs are passed on to the `savefig`
command that saves the figure.
'''
# Overloaded to explicitly close temp file.
_log.debug('MovieWriter.grab_frame: Grabbing frame.')
# Tell the figure to save its data to the sink, using the
# frame format and dpi.
with self._frame_sink() as myframesink:
self.fig.savefig(myframesink, format=self.frame_format,
dpi=self.dpi, **savefig_kwargs)
def finish(self):
# Call run here now that all frame grabbing is done. All temp files
# are available to be assembled.
self._run()
MovieWriter.finish(self) # Will call clean-up
def cleanup(self):
MovieWriter.cleanup(self)
# Delete temporary files
if self.clear_temp:
_log.debug('MovieWriter: clearing temporary fnames=%s',
self._temp_names)
for fname in self._temp_names:
os.remove(fname)
@writers.register('pillow')
class PillowWriter(MovieWriter):
@classmethod
def isAvailable(cls):
try:
import PIL
except ImportError:
return False
return True
def __init__(self, *args, **kwargs):
if kwargs.get("extra_args") is None:
kwargs["extra_args"] = ()
super().__init__(*args, **kwargs)
def setup(self, fig, outfile, dpi=None):
self._frames = []
self._outfile = outfile
self._dpi = dpi
self._fig = fig
def grab_frame(self, **savefig_kwargs):
from PIL import Image
buf = BytesIO()
self._fig.savefig(buf, **dict(savefig_kwargs, format="rgba"))
renderer = self._fig.canvas.get_renderer()
# Using frombuffer / getbuffer may be slightly more efficient, but
# Py3-only.
self._frames.append(Image.frombytes(
"RGBA",
(int(renderer.width), int(renderer.height)),
buf.getvalue()))
def finish(self):
self._frames[0].save(
self._outfile, save_all=True, append_images=self._frames[1:],
duration=int(1000 / self.fps), loop=0)
# Base class of ffmpeg information. Has the config keys and the common set
# of arguments that controls the *output* side of things.
class FFMpegBase(object):
'''Mixin class for FFMpeg output.
To be useful this must be multiply-inherited from with a
`MovieWriterBase` sub-class.
'''
exec_key = 'animation.ffmpeg_path'
args_key = 'animation.ffmpeg_args'
@property
def output_args(self):
args = ['-vcodec', self.codec]
# For h264, the default format is yuv444p, which is not compatible
# with quicktime (and others). Specifying yuv420p fixes playback on
# iOS,as well as HTML5 video in firefox and safari (on both Win and
# OSX). Also fixes internet explorer. This is as of 2015/10/29.
if self.codec == 'h264' and '-pix_fmt' not in self.extra_args:
args.extend(['-pix_fmt', 'yuv420p'])
# The %dk adds 'k' as a suffix so that ffmpeg treats our bitrate as in
# kbps
if self.bitrate > 0:
args.extend(['-b', '%dk' % self.bitrate])
if self.extra_args:
args.extend(self.extra_args)
for k, v in self.metadata.items():
args.extend(['-metadata', '%s=%s' % (k, v)])
return args + ['-y', self.outfile]
@classmethod
def isAvailable(cls):
return (
super().isAvailable()
# Ubuntu 12.04 ships a broken ffmpeg binary which we shouldn't use.
# NOTE: when removed, remove the same method in AVConvBase.
and b'LibAv' not in subprocess.run(
[cls.bin_path()], creationflags=subprocess_creation_flags,
stdout=subprocess.DEVNULL, stderr=subprocess.PIPE).stderr)
# Combine FFMpeg options with pipe-based writing
@writers.register('ffmpeg')
class FFMpegWriter(FFMpegBase, MovieWriter):
'''Pipe-based ffmpeg writer.
Frames are streamed directly to ffmpeg via a pipe and written in a single
pass.
'''
def _args(self):
# Returns the command line parameters for subprocess to use
# ffmpeg to create a movie using a pipe.
args = [self.bin_path(), '-f', 'rawvideo', '-vcodec', 'rawvideo',
'-s', '%dx%d' % self.frame_size, '-pix_fmt', self.frame_format,
'-r', str(self.fps)]
# Logging is quieted because subprocess.PIPE has limited buffer size.
# If you have a lot of frames in your animation and set logging to
# DEBUG, you will have a buffer overrun.
if _log.getEffectiveLevel() > logging.DEBUG:
args += ['-loglevel', 'error']
args += ['-i', 'pipe:'] + self.output_args
return args
# Combine FFMpeg options with temp file-based writing
@writers.register('ffmpeg_file')
class FFMpegFileWriter(FFMpegBase, FileMovieWriter):
'''File-based ffmpeg writer.
Frames are written to temporary files on disk and then stitched
together at the end.
'''
supported_formats = ['png', 'jpeg', 'ppm', 'tiff', 'sgi', 'bmp',
'pbm', 'raw', 'rgba']
def _args(self):
# Returns the command line parameters for subprocess to use
# ffmpeg to create a movie using a collection of temp images
return [self.bin_path(), '-r', str(self.fps),
'-i', self._base_temp_name(),
'-vframes', str(self._frame_counter)] + self.output_args
# Base class of avconv information. AVConv has identical arguments to FFMpeg.
class AVConvBase(FFMpegBase):
'''Mixin class for avconv output.
To be useful this must be multiply-inherited from with a
`MovieWriterBase` sub-class.
'''
exec_key = 'animation.avconv_path'
args_key = 'animation.avconv_args'
# NOTE : should be removed when the same method is removed in FFMpegBase.
isAvailable = classmethod(MovieWriter.isAvailable.__func__)
# Combine AVConv options with pipe-based writing
@writers.register('avconv')
class AVConvWriter(AVConvBase, FFMpegWriter):
'''Pipe-based avconv writer.
Frames are streamed directly to avconv via a pipe and written in a single
pass.
'''
# Combine AVConv options with file-based writing
@writers.register('avconv_file')
class AVConvFileWriter(AVConvBase, FFMpegFileWriter):
'''File-based avconv writer.
Frames are written to temporary files on disk and then stitched
together at the end.
'''
# Base class for animated GIFs with ImageMagick
class ImageMagickBase(object):
'''Mixin class for ImageMagick output.
To be useful this must be multiply-inherited from with a
`MovieWriterBase` sub-class.
'''
exec_key = 'animation.convert_path'
args_key = 'animation.convert_args'
@property
def delay(self):
return 100. / self.fps
@property
def output_args(self):
return [self.outfile]
@classmethod
def bin_path(cls):
binpath = super().bin_path()
if binpath == 'convert':
binpath = mpl._get_executable_info('magick').executable
return binpath
@classmethod
def isAvailable(cls):
try:
return super().isAvailable()
except FileNotFoundError: # May be raised by get_executable_info.
return False
# Combine ImageMagick options with pipe-based writing
@writers.register('imagemagick')
class ImageMagickWriter(ImageMagickBase, MovieWriter):
'''Pipe-based animated gif.
Frames are streamed directly to ImageMagick via a pipe and written
in a single pass.
'''
def _args(self):
return ([self.bin_path(),
'-size', '%ix%i' % self.frame_size, '-depth', '8',
'-delay', str(self.delay), '-loop', '0',
'%s:-' % self.frame_format]
+ self.output_args)
# Combine ImageMagick options with temp file-based writing
@writers.register('imagemagick_file')
class ImageMagickFileWriter(ImageMagickBase, FileMovieWriter):
'''File-based animated gif writer.
Frames are written to temporary files on disk and then stitched
together at the end.
'''
supported_formats = ['png', 'jpeg', 'ppm', 'tiff', 'sgi', 'bmp',
'pbm', 'raw', 'rgba']
def _args(self):
return ([self.bin_path(), '-delay', str(self.delay), '-loop', '0',
'%s*.%s' % (self.temp_prefix, self.frame_format)]
+ self.output_args)
# Taken directly from jakevdp's JSAnimation package at
# http://github.com/jakevdp/JSAnimation
def _included_frames(frame_list, frame_format):
"""frame_list should be a list of filenames"""
return INCLUDED_FRAMES.format(Nframes=len(frame_list),
frame_dir=os.path.dirname(frame_list[0]),
frame_format=frame_format)
def _embedded_frames(frame_list, frame_format):
"""frame_list should be a list of base64-encoded png files"""
template = ' frames[{0}] = "data:image/{1};base64,{2}"\n'
return "\n" + "".join(
template.format(i, frame_format, frame_data.replace('\n', '\\\n'))
for i, frame_data in enumerate(frame_list))
@writers.register('html')
class HTMLWriter(FileMovieWriter):
supported_formats = ['png', 'jpeg', 'tiff', 'svg']
args_key = 'animation.html_args'
@classmethod
def isAvailable(cls):
return True
def __init__(self, fps=30, codec=None, bitrate=None, extra_args=None,
metadata=None, embed_frames=False, default_mode='loop',
embed_limit=None):
self.embed_frames = embed_frames
self.default_mode = default_mode.lower()
# Save embed limit, which is given in MB
if embed_limit is None:
self._bytes_limit = rcParams['animation.embed_limit']
else:
self._bytes_limit = embed_limit
# Convert from MB to bytes
self._bytes_limit *= 1024 * 1024
if self.default_mode not in ['loop', 'once', 'reflect']:
raise ValueError(
"unrecognized default_mode {!r}".format(self.default_mode))
super().__init__(fps, codec, bitrate, extra_args, metadata)
def setup(self, fig, outfile, dpi, frame_dir=None):
root, ext = os.path.splitext(outfile)
if ext not in ['.html', '.htm']:
raise ValueError("outfile must be *.htm or *.html")
self._saved_frames = []
self._total_bytes = 0
self._hit_limit = False
if not self.embed_frames:
if frame_dir is None:
frame_dir = root + '_frames'
if not os.path.exists(frame_dir):
os.makedirs(frame_dir)
frame_prefix = os.path.join(frame_dir, 'frame')
else:
frame_prefix = None
super().setup(fig, outfile, dpi, frame_prefix, clear_temp=False)
def grab_frame(self, **savefig_kwargs):
if self.embed_frames:
# Just stop processing if we hit the limit
if self._hit_limit:
return
f = BytesIO()
self.fig.savefig(f, format=self.frame_format,
dpi=self.dpi, **savefig_kwargs)
imgdata64 = base64.encodebytes(f.getvalue()).decode('ascii')
self._total_bytes += len(imgdata64)
if self._total_bytes >= self._bytes_limit:
_log.warning(
"Animation size has reached %s bytes, exceeding the limit "
"of %s. If you're sure you want a larger animation "
"embedded, set the animation.embed_limit rc parameter to "
"a larger value (in MB). This and further frames will be "
"dropped.", self._total_bytes, self._bytes_limit)
self._hit_limit = True
else:
self._saved_frames.append(imgdata64)
else:
return super().grab_frame(**savefig_kwargs)
def finish(self):
# save the frames to an html file
if self.embed_frames:
fill_frames = _embedded_frames(self._saved_frames,
self.frame_format)
Nframes = len(self._saved_frames)
else:
# temp names is filled by FileMovieWriter
fill_frames = _included_frames(self._temp_names,
self.frame_format)
Nframes = len(self._temp_names)
mode_dict = dict(once_checked='',
loop_checked='',
reflect_checked='')
mode_dict[self.default_mode + '_checked'] = 'checked'
interval = 1000 // self.fps
with open(self.outfile, 'w') as of:
of.write(JS_INCLUDE + STYLE_INCLUDE)
of.write(DISPLAY_TEMPLATE.format(id=uuid.uuid4().hex,
Nframes=Nframes,
fill_frames=fill_frames,
interval=interval,
**mode_dict))
class Animation(object):
'''This class wraps the creation of an animation using matplotlib.
It is only a base class which should be subclassed to provide
needed behavior.
This class is not typically used directly.
Parameters
----------
fig : matplotlib.figure.Figure
The figure object that is used to get draw, resize, and any
other needed events.
event_source : object, optional
A class that can run a callback when desired events
are generated, as well as be stopped and started.
Examples include timers (see :class:`TimedAnimation`) and file
system notifications.
blit : bool, optional
controls whether blitting is used to optimize drawing. Defaults
to ``False``.
See Also
--------
FuncAnimation, ArtistAnimation
'''
def __init__(self, fig, event_source=None, blit=False):
self._fig = fig
# Disables blitting for backends that don't support it. This
# allows users to request it if available, but still have a
# fallback that works if it is not.
self._blit = blit and fig.canvas.supports_blit
# These are the basics of the animation. The frame sequence represents
# information for each frame of the animation and depends on how the
# drawing is handled by the subclasses. The event source fires events
# that cause the frame sequence to be iterated.
self.frame_seq = self.new_frame_seq()
self.event_source = event_source
# Instead of starting the event source now, we connect to the figure's
# draw_event, so that we only start once the figure has been drawn.
self._first_draw_id = fig.canvas.mpl_connect('draw_event', self._start)
# Connect to the figure's close_event so that we don't continue to
# fire events and try to draw to a deleted figure.
self._close_id = self._fig.canvas.mpl_connect('close_event',
self._stop)
if self._blit:
self._setup_blit()
def _start(self, *args):
'''
Starts interactive animation. Adds the draw frame command to the GUI
handler, calls show to start the event loop.
'''
# First disconnect our draw event handler
self._fig.canvas.mpl_disconnect(self._first_draw_id)
self._first_draw_id = None # So we can check on save
# Now do any initial draw
self._init_draw()
# Add our callback for stepping the animation and
# actually start the event_source.
self.event_source.add_callback(self._step)
self.event_source.start()
def _stop(self, *args):
# On stop we disconnect all of our events.
if self._blit:
self._fig.canvas.mpl_disconnect(self._resize_id)
self._fig.canvas.mpl_disconnect(self._close_id)
self.event_source.remove_callback(self._step)
self.event_source = None
def save(self, filename, writer=None, fps=None, dpi=None, codec=None,
bitrate=None, extra_args=None, metadata=None, extra_anim=None,
savefig_kwargs=None, *, progress_callback=None):
"""
Save the animation as a movie file by drawing every frame.
Parameters
----------
filename : str
The output filename, e.g., :file:`mymovie.mp4`.
writer : :class:`MovieWriter` or str, optional
A `MovieWriter` instance to use or a key that identifies a
class to use, such as 'ffmpeg'. If ``None``, defaults to
:rc:`animation.writer` = 'ffmpeg'.
fps : number, optional
Frames per second in the movie. Defaults to ``None``, which will use
the animation's specified interval to set the frames per second.
dpi : number, optional
Controls the dots per inch for the movie frames. This combined with
the figure's size in inches controls the size of the movie. If
``None``, defaults to :rc:`savefig.dpi`.
codec : str, optional
The video codec to be used. Not all codecs are supported
by a given :class:`MovieWriter`. If ``None``, default to
:rc:`animation.codec` = 'h264'.
bitrate : number, optional
Specifies the number of bits used per second in the compressed
movie, in kilobits per second. A higher number means a higher
quality movie, but at the cost of increased file size. If ``None``,
defaults to :rc:`animation.bitrate` = -1.
extra_args : list, optional
List of extra string arguments to be passed to the underlying movie
utility. If ``None``, defaults to :rc:`animation.extra_args`.
metadata : Dict[str, str], optional
Dictionary of keys and values for metadata to include in
the output file. Some keys that may be of use include:
title, artist, genre, subject, copyright, srcform, comment.
extra_anim : list, optional
Additional `Animation` objects that should be included
in the saved movie file. These need to be from the same
`matplotlib.figure.Figure` instance. Also, animation frames will
just be simply combined, so there should be a 1:1 correspondence
between the frames from the different animations.
savefig_kwargs : dict, optional
Is a dictionary containing keyword arguments to be passed
on to the `savefig` command which is called repeatedly to
save the individual frames.
progress_callback : function, optional
A callback function that will be called for every frame to notify
the saving progress. It must have the signature ::
def func(current_frame: int, total_frames: int) -> Any
where *current_frame* is the current frame number and
*total_frames* is the total number of frames to be saved.
*total_frames* is set to None, if the total number of frames can
not be determined. Return values may exist but are ignored.
Example code to write the progress to stdout::
progress_callback =\
lambda i, n: print(f'Saving frame {i} of {n}')
Notes
-----
*fps*, *codec*, *bitrate*, *extra_args* and *metadata* are used to
construct a `.MovieWriter` instance and can only be passed if
*writer* is a string. If they are passed as non-*None* and *writer*
is a `.MovieWriter`, a `RuntimeError` will be raised.
"""
# If the writer is None, use the rc param to find the name of the one
# to use
if writer is None:
writer = rcParams['animation.writer']
elif (not isinstance(writer, str) and
any(arg is not None
for arg in (fps, codec, bitrate, extra_args, metadata))):
raise RuntimeError('Passing in values for arguments '
'fps, codec, bitrate, extra_args, or metadata '
'is not supported when writer is an existing '
'MovieWriter instance. These should instead be '
'passed as arguments when creating the '
'MovieWriter instance.')
if savefig_kwargs is None:
savefig_kwargs = {}
# Need to disconnect the first draw callback, since we'll be doing
# draws. Otherwise, we'll end up starting the animation.
if self._first_draw_id is not None:
self._fig.canvas.mpl_disconnect(self._first_draw_id)
reconnect_first_draw = True
else:
reconnect_first_draw = False
if fps is None and hasattr(self, '_interval'):
# Convert interval in ms to frames per second
fps = 1000. / self._interval
# Re-use the savefig DPI for ours if none is given
if dpi is None:
dpi = rcParams['savefig.dpi']
if dpi == 'figure':
dpi = self._fig.dpi
if codec is None:
codec = rcParams['animation.codec']
if bitrate is None:
bitrate = rcParams['animation.bitrate']
all_anim = [self]
if extra_anim is not None:
all_anim.extend(anim
for anim
in extra_anim if anim._fig is self._fig)
# If we have the name of a writer, instantiate an instance of the
# registered class.
if isinstance(writer, str):
if writer in writers.avail:
writer = writers[writer](fps, codec, bitrate,
extra_args=extra_args,
metadata=metadata)
else:
if writers.list():
alt_writer = writers[writers.list()[0]]
_log.warning("MovieWriter %s unavailable; trying to use "
"%s instead.", writer, alt_writer)
writer = alt_writer(
fps, codec, bitrate,
extra_args=extra_args, metadata=metadata)
else:
raise ValueError("Cannot save animation: no writers are "
"available. Please install ffmpeg to "
"save animations.")
_log.info('Animation.save using %s', type(writer))
if 'bbox_inches' in savefig_kwargs:
_log.warning("Warning: discarding the 'bbox_inches' argument in "
"'savefig_kwargs' as it may cause frame size "
"to vary, which is inappropriate for animation.")
savefig_kwargs.pop('bbox_inches')
# Create a new sequence of frames for saved data. This is different
# from new_frame_seq() to give the ability to save 'live' generated
# frame information to be saved later.
# TODO: Right now, after closing the figure, saving a movie won't work
# since GUI widgets are gone. Either need to remove extra code to
# allow for this non-existent use case or find a way to make it work.
with rc_context():
if rcParams['savefig.bbox'] == 'tight':
_log.info("Disabling savefig.bbox = 'tight', as it may cause "
"frame size to vary, which is inappropriate for "
"animation.")
rcParams['savefig.bbox'] = None
with writer.saving(self._fig, filename, dpi):
for anim in all_anim:
# Clear the initial frame
anim._init_draw()
frame_number = 0
save_count_list = [a.save_count for a in all_anim]
if None in save_count_list:
total_frames = None
else:
total_frames = sum(save_count_list)
for data in zip(*[a.new_saved_frame_seq() for a in all_anim]):
for anim, d in zip(all_anim, data):
# TODO: See if turning off blit is really necessary
anim._draw_next_frame(d, blit=False)
if progress_callback is not None:
progress_callback(frame_number, total_frames)
frame_number += 1
writer.grab_frame(**savefig_kwargs)
# Reconnect signal for first draw if necessary
if reconnect_first_draw:
self._first_draw_id = self._fig.canvas.mpl_connect('draw_event',
self._start)
def _step(self, *args):
'''
Handler for getting events. By default, gets the next frame in the
sequence and hands the data off to be drawn.
'''
# Returns True to indicate that the event source should continue to
# call _step, until the frame sequence reaches the end of iteration,
# at which point False will be returned.
try:
framedata = next(self.frame_seq)
self._draw_next_frame(framedata, self._blit)
return True
except StopIteration:
return False
def new_frame_seq(self):
"""Return a new sequence of frame information."""
# Default implementation is just an iterator over self._framedata
return iter(self._framedata)
def new_saved_frame_seq(self):
"""Return a new sequence of saved/cached frame information."""
# Default is the same as the regular frame sequence
return self.new_frame_seq()
def _draw_next_frame(self, framedata, blit):
# Breaks down the drawing of the next frame into steps of pre- and
# post- draw, as well as the drawing of the frame itself.
self._pre_draw(framedata, blit)
self._draw_frame(framedata)
self._post_draw(framedata, blit)
def _init_draw(self):
# Initial draw to clear the frame. Also used by the blitting code
# when a clean base is required.
pass
def _pre_draw(self, framedata, blit):
# Perform any cleaning or whatnot before the drawing of the frame.
# This default implementation allows blit to clear the frame.
if blit:
self._blit_clear(self._drawn_artists, self._blit_cache)
def _draw_frame(self, framedata):
# Performs actual drawing of the frame.
raise NotImplementedError('Needs to be implemented by subclasses to'
' actually make an animation.')
def _post_draw(self, framedata, blit):
# After the frame is rendered, this handles the actual flushing of
# the draw, which can be a direct draw_idle() or make use of the
# blitting.
if blit and self._drawn_artists:
self._blit_draw(self._drawn_artists, self._blit_cache)
else:
self._fig.canvas.draw_idle()
# The rest of the code in this class is to facilitate easy blitting
def _blit_draw(self, artists, bg_cache):
# Handles blitted drawing, which renders only the artists given instead
# of the entire figure.
updated_ax = []
for a in artists:
# If we haven't cached the background for this axes object, do
# so now. This might not always be reliable, but it's an attempt
# to automate the process.
if a.axes not in bg_cache:
bg_cache[a.axes] = a.figure.canvas.copy_from_bbox(a.axes.bbox)
a.axes.draw_artist(a)
updated_ax.append(a.axes)
# After rendering all the needed artists, blit each axes individually.
for ax in set(updated_ax):
ax.figure.canvas.blit(ax.bbox)
def _blit_clear(self, artists, bg_cache):
# Get a list of the axes that need clearing from the artists that
# have been drawn. Grab the appropriate saved background from the
# cache and restore.
axes = {a.axes for a in artists}
for a in axes:
if a in bg_cache:
a.figure.canvas.restore_region(bg_cache[a])
def _setup_blit(self):
# Setting up the blit requires: a cache of the background for the
# axes
self._blit_cache = dict()
self._drawn_artists = []
for ax in self._fig.axes:
ax.callbacks.connect('xlim_changed',
lambda ax: self._blit_cache.pop(ax, None))
ax.callbacks.connect('ylim_changed',
lambda ax: self._blit_cache.pop(ax, None))
self._resize_id = self._fig.canvas.mpl_connect('resize_event',
self._handle_resize)
self._post_draw(None, self._blit)
def _handle_resize(self, *args):
# On resize, we need to disable the resize event handling so we don't
# get too many events. Also stop the animation events, so that
# we're paused. Reset the cache and re-init. Set up an event handler
# to catch once the draw has actually taken place.
self._fig.canvas.mpl_disconnect(self._resize_id)
self.event_source.stop()
self._blit_cache.clear()
self._init_draw()
self._resize_id = self._fig.canvas.mpl_connect('draw_event',
self._end_redraw)
def _end_redraw(self, evt):
# Now that the redraw has happened, do the post draw flushing and
# blit handling. Then re-enable all of the original events.
self._post_draw(None, False)
self.event_source.start()
self._fig.canvas.mpl_disconnect(self._resize_id)
self._resize_id = self._fig.canvas.mpl_connect('resize_event',
self._handle_resize)
def to_html5_video(self, embed_limit=None):
"""
Convert the animation to an HTML5 ``<video>`` tag.
This saves the animation as an h264 video, encoded in base64
directly into the HTML5 video tag. This respects the rc parameters
for the writer as well as the bitrate. This also makes use of the
``interval`` to control the speed, and uses the ``repeat``
parameter to decide whether to loop.
Parameters
----------
embed_limit : float, optional
Limit, in MB, of the returned animation. No animation is created
if the limit is exceeded.
Defaults to :rc:`animation.embed_limit` = 20.0.
Returns
-------
video_tag : str
An HTML5 video tag with the animation embedded as base64 encoded
h264 video.
If the *embed_limit* is exceeded, this returns the string
"Video too large to embed."
"""
VIDEO_TAG = r'''<video {size} {options}>
<source type="video/mp4" src="data:video/mp4;base64,{video}">
Your browser does not support the video tag.
</video>'''
# Cache the rendering of the video as HTML
if not hasattr(self, '_base64_video'):
# Save embed limit, which is given in MB
if embed_limit is None:
embed_limit = rcParams['animation.embed_limit']
# Convert from MB to bytes
embed_limit *= 1024 * 1024
# Can't open a NamedTemporaryFile twice on Windows, so use a
# TemporaryDirectory instead.
with TemporaryDirectory() as tmpdir:
path = Path(tmpdir, "temp.m4v")
# We create a writer manually so that we can get the
# appropriate size for the tag
Writer = writers[rcParams['animation.writer']]
writer = Writer(codec='h264',
bitrate=rcParams['animation.bitrate'],
fps=1000. / self._interval)
self.save(str(path), writer=writer)
# Now open and base64 encode.
vid64 = base64.encodebytes(path.read_bytes())
vid_len = len(vid64)
if vid_len >= embed_limit:
_log.warning(
"Animation movie is %s bytes, exceeding the limit of %s. "
"If you're sure you want a large animation embedded, set "
"the animation.embed_limit rc parameter to a larger value "
"(in MB).", vid_len, embed_limit)
else:
self._base64_video = vid64.decode('ascii')
self._video_size = 'width="{}" height="{}"'.format(
*writer.frame_size)
# If we exceeded the size, this attribute won't exist
if hasattr(self, '_base64_video'):
# Default HTML5 options are to autoplay and display video controls
options = ['controls', 'autoplay']
# If we're set to repeat, make it loop
if hasattr(self, 'repeat') and self.repeat:
options.append('loop')
return VIDEO_TAG.format(video=self._base64_video,
size=self._video_size,
options=' '.join(options))
else:
return 'Video too large to embed.'
def to_jshtml(self, fps=None, embed_frames=True, default_mode=None):
"""Generate HTML representation of the animation"""
if fps is None and hasattr(self, '_interval'):
# Convert interval in ms to frames per second
fps = 1000 / self._interval
# If we're not given a default mode, choose one base on the value of
# the repeat attribute
if default_mode is None:
default_mode = 'loop' if self.repeat else 'once'
if not hasattr(self, "_html_representation"):
# Can't open a NamedTemporaryFile twice on Windows, so use a
# TemporaryDirectory instead.
with TemporaryDirectory() as tmpdir:
path = Path(tmpdir, "temp.html")
writer = HTMLWriter(fps=fps,
embed_frames=embed_frames,
default_mode=default_mode)
self.save(str(path), writer=writer)
self._html_representation = path.read_text()
return self._html_representation
def _repr_html_(self):
'''IPython display hook for rendering.'''
fmt = rcParams['animation.html']
if fmt == 'html5':
return self.to_html5_video()
elif fmt == 'jshtml':
return self.to_jshtml()
class TimedAnimation(Animation):
''':class:`Animation` subclass for time-based animation.
A new frame is drawn every *interval* milliseconds.
Parameters
----------
fig : matplotlib.figure.Figure
The figure object that is used to get draw, resize, and any
other needed events.
interval : number, optional
Delay between frames in milliseconds. Defaults to 200.
repeat_delay : number, optional
If the animation in repeated, adds a delay in milliseconds
before repeating the animation. Defaults to ``None``.
repeat : bool, optional
Controls whether the animation should repeat when the sequence
of frames is completed. Defaults to ``True``.
blit : bool, optional
Controls whether blitting is used to optimize drawing. Defaults
to ``False``.
'''
def __init__(self, fig, interval=200, repeat_delay=None, repeat=True,
event_source=None, *args, **kwargs):
# Store the timing information
self._interval = interval
self._repeat_delay = repeat_delay
self.repeat = repeat
# If we're not given an event source, create a new timer. This permits
# sharing timers between animation objects for syncing animations.
if event_source is None:
event_source = fig.canvas.new_timer()
event_source.interval = self._interval
Animation.__init__(self, fig, event_source=event_source,
*args, **kwargs)
def _step(self, *args):
'''
Handler for getting events.
'''
# Extends the _step() method for the Animation class. If
# Animation._step signals that it reached the end and we want to
# repeat, we refresh the frame sequence and return True. If
# _repeat_delay is set, change the event_source's interval to our loop
# delay and set the callback to one which will then set the interval
# back.
still_going = Animation._step(self, *args)
if not still_going and self.repeat:
self._init_draw()
self.frame_seq = self.new_frame_seq()
if self._repeat_delay:
self.event_source.remove_callback(self._step)
self.event_source.add_callback(self._loop_delay)
self.event_source.interval = self._repeat_delay
return True
else:
return Animation._step(self, *args)
else:
return still_going
def _stop(self, *args):
# If we stop in the middle of a loop delay (which is relatively likely
# given the potential pause here, remove the loop_delay callback as
# well.
self.event_source.remove_callback(self._loop_delay)
Animation._stop(self)
def _loop_delay(self, *args):
# Reset the interval and change callbacks after the delay.
self.event_source.remove_callback(self._loop_delay)
self.event_source.interval = self._interval
self.event_source.add_callback(self._step)
Animation._step(self)
class ArtistAnimation(TimedAnimation):
'''Animation using a fixed set of `Artist` objects.
Before creating an instance, all plotting should have taken place
and the relevant artists saved.
Parameters
----------
fig : matplotlib.figure.Figure
The figure object that is used to get draw, resize, and any
other needed events.
artists : list
Each list entry a collection of artists that represent what
needs to be enabled on each frame. These will be disabled for
other frames.
interval : number, optional
Delay between frames in milliseconds. Defaults to 200.
repeat_delay : number, optional
If the animation in repeated, adds a delay in milliseconds
before repeating the animation. Defaults to ``None``.
repeat : bool, optional
Controls whether the animation should repeat when the sequence
of frames is completed. Defaults to ``True``.
blit : bool, optional
Controls whether blitting is used to optimize drawing. Defaults
to ``False``.
'''
def __init__(self, fig, artists, *args, **kwargs):
# Internal list of artists drawn in the most recent frame.
self._drawn_artists = []
# Use the list of artists as the framedata, which will be iterated
# over by the machinery.
self._framedata = artists
TimedAnimation.__init__(self, fig, *args, **kwargs)
def _init_draw(self):
# Make all the artists involved in *any* frame invisible
figs = set()
for f in self.new_frame_seq():
for artist in f:
artist.set_visible(False)
artist.set_animated(self._blit)
# Assemble a list of unique figures that need flushing
if artist.get_figure() not in figs:
figs.add(artist.get_figure())
# Flush the needed figures
for fig in figs:
fig.canvas.draw_idle()
def _pre_draw(self, framedata, blit):
'''
Clears artists from the last frame.
'''
if blit:
# Let blit handle clearing
self._blit_clear(self._drawn_artists, self._blit_cache)
else:
# Otherwise, make all the artists from the previous frame invisible
for artist in self._drawn_artists:
artist.set_visible(False)
def _draw_frame(self, artists):
# Save the artists that were passed in as framedata for the other
# steps (esp. blitting) to use.
self._drawn_artists = artists
# Make all the artists from the current frame visible
for artist in artists:
artist.set_visible(True)
class FuncAnimation(TimedAnimation):
"""
Makes an animation by repeatedly calling a function *func*.
Parameters
----------
fig : matplotlib.figure.Figure
The figure object that is used to get draw, resize, and any
other needed events.
func : callable
The function to call at each frame. The first argument will
be the next value in *frames*. Any additional positional
arguments can be supplied via the *fargs* parameter.
The required signature is::
def func(frame, *fargs) -> iterable_of_artists
If ``blit == True``, *func* must return an iterable of all artists
that were modified or created. This information is used by the blitting
algorithm to determine which parts of the figure have to be updated.
The return value is unused if ``blit == False`` and may be omitted in
that case.
frames : iterable, int, generator function, or None, optional
Source of data to pass *func* and each frame of the animation
- If an iterable, then simply use the values provided. If the
iterable has a length, it will override the *save_count* kwarg.
- If an integer, then equivalent to passing ``range(frames)``
- If a generator function, then must have the signature::
def gen_function() -> obj
- If *None*, then equivalent to passing ``itertools.count``.
In all of these cases, the values in *frames* is simply passed through
to the user-supplied *func* and thus can be of any type.
init_func : callable, optional
A function used to draw a clear frame. If not given, the
results of drawing from the first item in the frames sequence
will be used. This function will be called once before the
first frame.
The required signature is::
def init_func() -> iterable_of_artists
If ``blit == True``, *init_func* must return an iterable of artists
to be re-drawn. This information is used by the blitting
algorithm to determine which parts of the figure have to be updated.
The return value is unused if ``blit == False`` and may be omitted in
that case.
fargs : tuple or None, optional
Additional arguments to pass to each call to *func*.
save_count : int, optional
The number of values from *frames* to cache.
interval : number, optional
Delay between frames in milliseconds. Defaults to 200.
repeat_delay : number, optional
If the animation in repeated, adds a delay in milliseconds
before repeating the animation. Defaults to *None*.
repeat : bool, optional
Controls whether the animation should repeat when the sequence
of frames is completed. Defaults to *True*.
blit : bool, optional
Controls whether blitting is used to optimize drawing. Note: when using
blitting any animated artists will be drawn according to their zorder.
However, they will be drawn on top of any previous artists, regardless
of their zorder. Defaults to *False*.
cache_frame_data : bool, optional
Controls whether frame data is cached. Defaults to *True*.
Disabling cache might be helpful when frames contain large objects.
"""
def __init__(self, fig, func, frames=None, init_func=None, fargs=None,
save_count=None, *, cache_frame_data=True, **kwargs):
if fargs:
self._args = fargs
else:
self._args = ()
self._func = func
self._init_func = init_func
# Amount of framedata to keep around for saving movies. This is only
# used if we don't know how many frames there will be: in the case
# of no generator or in the case of a callable.
self.save_count = save_count
# Set up a function that creates a new iterable when needed. If nothing
# is passed in for frames, just use itertools.count, which will just
# keep counting from 0. A callable passed in for frames is assumed to
# be a generator. An iterable will be used as is, and anything else
# will be treated as a number of frames.
if frames is None:
self._iter_gen = itertools.count
elif callable(frames):
self._iter_gen = frames
elif np.iterable(frames):
self._iter_gen = lambda: iter(frames)
if hasattr(frames, '__len__'):
self.save_count = len(frames)
else:
self._iter_gen = lambda: iter(range(frames))
self.save_count = frames
if self.save_count is None:
# If we're passed in and using the default, set save_count to 100.
self.save_count = 100
else:
# itertools.islice returns an error when passed a numpy int instead
# of a native python int (http://bugs.python.org/issue30537).
# As a workaround, convert save_count to a native python int.
self.save_count = int(self.save_count)
self._cache_frame_data = cache_frame_data
# Needs to be initialized so the draw functions work without checking
self._save_seq = []
TimedAnimation.__init__(self, fig, **kwargs)
# Need to reset the saved seq, since right now it will contain data
# for a single frame from init, which is not what we want.
self._save_seq = []
def new_frame_seq(self):
# Use the generating function to generate a new frame sequence
return self._iter_gen()
def new_saved_frame_seq(self):
# Generate an iterator for the sequence of saved data. If there are
# no saved frames, generate a new frame sequence and take the first
# save_count entries in it.
if self._save_seq:
# While iterating we are going to update _save_seq
# so make a copy to safely iterate over
self._old_saved_seq = list(self._save_seq)
return iter(self._old_saved_seq)
else:
if self.save_count is not None:
return itertools.islice(self.new_frame_seq(), self.save_count)
else:
frame_seq = self.new_frame_seq()
def gen():
try:
for _ in range(100):
yield next(frame_seq)
except StopIteration:
pass
else:
cbook.warn_deprecated(
"2.2", message="FuncAnimation.save has truncated "
"your animation to 100 frames. In the future, no "
"such truncation will occur; please pass "
"'save_count' accordingly.")
return gen()
def _init_draw(self):
# Initialize the drawing either using the given init_func or by
# calling the draw function with the first item of the frame sequence.
# For blitting, the init_func should return a sequence of modified
# artists.
if self._init_func is None:
self._draw_frame(next(self.new_frame_seq()))
else:
self._drawn_artists = self._init_func()
if self._blit:
if self._drawn_artists is None:
raise RuntimeError('The init_func must return a '
'sequence of Artist objects.')
for a in self._drawn_artists:
a.set_animated(self._blit)
self._save_seq = []
def _draw_frame(self, framedata):
if self._cache_frame_data:
# Save the data for potential saving of movies.
self._save_seq.append(framedata)
# Make sure to respect save_count (keep only the last save_count
# around)
self._save_seq = self._save_seq[-self.save_count:]
# Call the func with framedata and args. If blitting is desired,
# func needs to return a sequence of any artists that were modified.
self._drawn_artists = self._func(framedata, *self._args)
if self._blit:
if self._drawn_artists is None:
raise RuntimeError('The animation function must return a '
'sequence of Artist objects.')
self._drawn_artists = sorted(self._drawn_artists,
key=lambda x: x.get_zorder())
for a in self._drawn_artists:
a.set_animated(self._blit)
|
2bda8bc9a7a2598a7ff749b1e320f2f598f842c322ba85ad039d7ba56ada4028
|
"""
GUI neutral widgets
===================
Widgets that are designed to work for any of the GUI backends.
All of these widgets require you to predefine a :class:`matplotlib.axes.Axes`
instance and pass that as the first arg. matplotlib doesn't try to
be too smart with respect to layout -- you will have to figure out how
wide and tall you want your Axes to be to accommodate your widget.
"""
import copy
from numbers import Integral
import numpy as np
from . import cbook, rcParams
from .lines import Line2D
from .patches import Circle, Rectangle, Ellipse
from .transforms import blended_transform_factory
class LockDraw(object):
"""
Some widgets, like the cursor, draw onto the canvas, and this is not
desirable under all circumstances, like when the toolbar is in zoom-to-rect
mode and drawing a rectangle. To avoid this, a widget can acquire a
canvas' lock with ``canvas.widgetlock(widget)`` before drawing on the
canvas; this will prevent other widgets from doing so at the same time (if
they also try to acquire the lock first).
"""
def __init__(self):
self._owner = None
def __call__(self, o):
"""Reserve the lock for *o*."""
if not self.available(o):
raise ValueError('already locked')
self._owner = o
def release(self, o):
"""Release the lock from *o*."""
if not self.available(o):
raise ValueError('you do not own this lock')
self._owner = None
def available(self, o):
"""Return whether drawing is available to *o*."""
return not self.locked() or self.isowner(o)
def isowner(self, o):
"""Return whether *o* owns this lock."""
return self._owner is o
def locked(self):
"""Return whether the lock is currently held by an owner."""
return self._owner is not None
class Widget(object):
"""
Abstract base class for GUI neutral widgets
"""
drawon = True
eventson = True
_active = True
def set_active(self, active):
"""Set whether the widget is active.
"""
self._active = active
def get_active(self):
"""Get whether the widget is active.
"""
return self._active
# set_active is overridden by SelectorWidgets.
active = property(get_active, lambda self, active: self.set_active(active),
doc="Is the widget active?")
def ignore(self, event):
"""Return True if event should be ignored.
This method (or a version of it) should be called at the beginning
of any event callback.
"""
return not self.active
class AxesWidget(Widget):
"""Widget that is connected to a single
:class:`~matplotlib.axes.Axes`.
To guarantee that the widget remains responsive and not garbage-collected,
a reference to the object should be maintained by the user.
This is necessary because the callback registry
maintains only weak-refs to the functions, which are member
functions of the widget. If there are no references to the widget
object it may be garbage collected which will disconnect the
callbacks.
Attributes:
*ax* : :class:`~matplotlib.axes.Axes`
The parent axes for the widget
*canvas* : :class:`~matplotlib.backend_bases.FigureCanvasBase` subclass
The parent figure canvas for the widget.
*active* : bool
If False, the widget does not respond to events.
"""
def __init__(self, ax):
self.ax = ax
self.canvas = ax.figure.canvas
self.cids = []
def connect_event(self, event, callback):
"""Connect callback with an event.
This should be used in lieu of `figure.canvas.mpl_connect` since this
function stores callback ids for later clean up.
"""
cid = self.canvas.mpl_connect(event, callback)
self.cids.append(cid)
def disconnect_events(self):
"""Disconnect all events created by this widget."""
for c in self.cids:
self.canvas.mpl_disconnect(c)
class Button(AxesWidget):
"""
A GUI neutral button.
For the button to remain responsive you must keep a reference to it.
Call :meth:`on_clicked` to connect to the button.
Attributes
----------
ax
The :class:`matplotlib.axes.Axes` the button renders into.
label
A :class:`matplotlib.text.Text` instance.
color
The color of the button when not hovering.
hovercolor
The color of the button when hovering.
"""
def __init__(self, ax, label, image=None,
color='0.85', hovercolor='0.95'):
"""
Parameters
----------
ax : matplotlib.axes.Axes
The :class:`matplotlib.axes.Axes` instance the button
will be placed into.
label : str
The button text. Accepts string.
image : array, mpl image, Pillow Image
The image to place in the button, if not *None*.
Can be any legal arg to imshow (numpy array,
matplotlib Image instance, or Pillow Image).
color : color
The color of the button when not activated
hovercolor : color
The color of the button when the mouse is over it
"""
AxesWidget.__init__(self, ax)
if image is not None:
ax.imshow(image)
self.label = ax.text(0.5, 0.5, label,
verticalalignment='center',
horizontalalignment='center',
transform=ax.transAxes)
self.cnt = 0
self.observers = {}
self.connect_event('button_press_event', self._click)
self.connect_event('button_release_event', self._release)
self.connect_event('motion_notify_event', self._motion)
ax.set_navigate(False)
ax.set_facecolor(color)
ax.set_xticks([])
ax.set_yticks([])
self.color = color
self.hovercolor = hovercolor
self._lastcolor = color
def _click(self, event):
if self.ignore(event):
return
if event.inaxes != self.ax:
return
if not self.eventson:
return
if event.canvas.mouse_grabber != self.ax:
event.canvas.grab_mouse(self.ax)
def _release(self, event):
if self.ignore(event):
return
if event.canvas.mouse_grabber != self.ax:
return
event.canvas.release_mouse(self.ax)
if not self.eventson:
return
if event.inaxes != self.ax:
return
for cid, func in self.observers.items():
func(event)
def _motion(self, event):
if self.ignore(event):
return
if event.inaxes == self.ax:
c = self.hovercolor
else:
c = self.color
if c != self._lastcolor:
self.ax.set_facecolor(c)
self._lastcolor = c
if self.drawon:
self.ax.figure.canvas.draw()
def on_clicked(self, func):
"""
Connect the callback function *func* to button click events.
Returns a connection id, which can be used to disconnect the callback.
"""
cid = self.cnt
self.observers[cid] = func
self.cnt += 1
return cid
def disconnect(self, cid):
"""Remove the callback function with connection id *cid*."""
try:
del self.observers[cid]
except KeyError:
pass
class Slider(AxesWidget):
"""
A slider representing a floating point range.
Create a slider from *valmin* to *valmax* in axes *ax*. For the slider to
remain responsive you must maintain a reference to it. Call
:meth:`on_changed` to connect to the slider event.
Attributes
----------
val : float
Slider value.
"""
def __init__(self, ax, label, valmin, valmax, valinit=0.5, valfmt='%1.2f',
closedmin=True, closedmax=True, slidermin=None,
slidermax=None, dragging=True, valstep=None,
orientation='horizontal', **kwargs):
"""
Parameters
----------
ax : Axes
The Axes to put the slider in.
label : str
Slider label.
valmin : float
The minimum value of the slider.
valmax : float
The maximum value of the slider.
valinit : float, optional, default: 0.5
The slider initial position.
valfmt : str, optional, default: "%1.2f"
Used to format the slider value, fprint format string.
closedmin : bool, optional, default: True
Indicate whether the slider interval is closed on the bottom.
closedmax : bool, optional, default: True
Indicate whether the slider interval is closed on the top.
slidermin : Slider, optional, default: None
Do not allow the current slider to have a value less than
the value of the Slider `slidermin`.
slidermax : Slider, optional, default: None
Do not allow the current slider to have a value greater than
the value of the Slider `slidermax`.
dragging : bool, optional, default: True
If True the slider can be dragged by the mouse.
valstep : float, optional, default: None
If given, the slider will snap to multiples of `valstep`.
orientation : str, 'horizontal' or 'vertical', default: 'horizontal'
The orientation of the slider.
Notes
-----
Additional kwargs are passed on to ``self.poly`` which is the
:class:`~matplotlib.patches.Rectangle` that draws the slider
knob. See the :class:`~matplotlib.patches.Rectangle` documentation for
valid property names (e.g., `facecolor`, `edgecolor`, `alpha`).
"""
AxesWidget.__init__(self, ax)
if slidermin is not None and not hasattr(slidermin, 'val'):
raise ValueError("Argument slidermin ({}) has no 'val'"
.format(type(slidermin)))
if slidermax is not None and not hasattr(slidermax, 'val'):
raise ValueError("Argument slidermax ({}) has no 'val'"
.format(type(slidermax)))
if orientation not in ['horizontal', 'vertical']:
raise ValueError("Argument orientation ({}) must be either"
"'horizontal' or 'vertical'".format(orientation))
self.orientation = orientation
self.closedmin = closedmin
self.closedmax = closedmax
self.slidermin = slidermin
self.slidermax = slidermax
self.drag_active = False
self.valmin = valmin
self.valmax = valmax
self.valstep = valstep
valinit = self._value_in_bounds(valinit)
if valinit is None:
valinit = valmin
self.val = valinit
self.valinit = valinit
if orientation == 'vertical':
self.poly = ax.axhspan(valmin, valinit, 0, 1, **kwargs)
self.hline = ax.axhline(valinit, 0, 1, color='r', lw=1)
else:
self.poly = ax.axvspan(valmin, valinit, 0, 1, **kwargs)
self.vline = ax.axvline(valinit, 0, 1, color='r', lw=1)
self.valfmt = valfmt
ax.set_yticks([])
if orientation == 'vertical':
ax.set_ylim((valmin, valmax))
else:
ax.set_xlim((valmin, valmax))
ax.set_xticks([])
ax.set_navigate(False)
self.connect_event('button_press_event', self._update)
self.connect_event('button_release_event', self._update)
if dragging:
self.connect_event('motion_notify_event', self._update)
if orientation == 'vertical':
self.label = ax.text(0.5, 1.02, label, transform=ax.transAxes,
verticalalignment='bottom',
horizontalalignment='center')
self.valtext = ax.text(0.5, -0.02, valfmt % valinit,
transform=ax.transAxes,
verticalalignment='top',
horizontalalignment='center')
else:
self.label = ax.text(-0.02, 0.5, label, transform=ax.transAxes,
verticalalignment='center',
horizontalalignment='right')
self.valtext = ax.text(1.02, 0.5, valfmt % valinit,
transform=ax.transAxes,
verticalalignment='center',
horizontalalignment='left')
self.cnt = 0
self.observers = {}
self.set_val(valinit)
def _value_in_bounds(self, val):
"""Makes sure *val* is with given bounds."""
if self.valstep:
val = np.round((val - self.valmin)/self.valstep)*self.valstep
val += self.valmin
if val <= self.valmin:
if not self.closedmin:
return
val = self.valmin
elif val >= self.valmax:
if not self.closedmax:
return
val = self.valmax
if self.slidermin is not None and val <= self.slidermin.val:
if not self.closedmin:
return
val = self.slidermin.val
if self.slidermax is not None and val >= self.slidermax.val:
if not self.closedmax:
return
val = self.slidermax.val
return val
def _update(self, event):
"""Update the slider position."""
if self.ignore(event) or event.button != 1:
return
if event.name == 'button_press_event' and event.inaxes == self.ax:
self.drag_active = True
event.canvas.grab_mouse(self.ax)
if not self.drag_active:
return
elif ((event.name == 'button_release_event') or
(event.name == 'button_press_event' and
event.inaxes != self.ax)):
self.drag_active = False
event.canvas.release_mouse(self.ax)
return
if self.orientation == 'vertical':
val = self._value_in_bounds(event.ydata)
else:
val = self._value_in_bounds(event.xdata)
if val not in [None, self.val]:
self.set_val(val)
def set_val(self, val):
"""
Set slider value to *val*
Parameters
----------
val : float
"""
xy = self.poly.xy
if self.orientation == 'vertical':
xy[1] = 0, val
xy[2] = 1, val
else:
xy[2] = val, 1
xy[3] = val, 0
self.poly.xy = xy
self.valtext.set_text(self.valfmt % val)
if self.drawon:
self.ax.figure.canvas.draw_idle()
self.val = val
if not self.eventson:
return
for cid, func in self.observers.items():
func(val)
def on_changed(self, func):
"""
When the slider value is changed call *func* with the new
slider value
Parameters
----------
func : callable
Function to call when slider is changed.
The function must accept a single float as its arguments.
Returns
-------
cid : int
Connection id (which can be used to disconnect *func*)
"""
cid = self.cnt
self.observers[cid] = func
self.cnt += 1
return cid
def disconnect(self, cid):
"""
Remove the observer with connection id *cid*
Parameters
----------
cid : int
Connection id of the observer to be removed
"""
try:
del self.observers[cid]
except KeyError:
pass
def reset(self):
"""Reset the slider to the initial value"""
if self.val != self.valinit:
self.set_val(self.valinit)
class CheckButtons(AxesWidget):
"""
A GUI neutral set of check buttons.
For the check buttons to remain responsive you must keep a
reference to this object.
The following attributes are exposed
*ax*
The :class:`matplotlib.axes.Axes` instance the buttons are
located in
*labels*
List of :class:`matplotlib.text.Text` instances
*lines*
List of (line1, line2) tuples for the x's in the check boxes.
These lines exist for each box, but have ``set_visible(False)``
when its box is not checked.
*rectangles*
List of :class:`matplotlib.patches.Rectangle` instances
Connect to the CheckButtons with the :meth:`on_clicked` method
"""
def __init__(self, ax, labels, actives=None):
"""
Add check buttons to :class:`matplotlib.axes.Axes` instance *ax*
Parameters
----------
ax : `~matplotlib.axes.Axes`
The parent axes for the widget.
labels : List[str]
The labels of the check buttons.
actives : List[bool], optional
The initial check states of the buttons. The list must have the
same length as *labels*. If not given, all buttons are unchecked.
"""
AxesWidget.__init__(self, ax)
ax.set_xticks([])
ax.set_yticks([])
ax.set_navigate(False)
if actives is None:
actives = [False] * len(labels)
if len(labels) > 1:
dy = 1. / (len(labels) + 1)
ys = np.linspace(1 - dy, dy, len(labels))
else:
dy = 0.25
ys = [0.5]
axcolor = ax.get_facecolor()
self.labels = []
self.lines = []
self.rectangles = []
lineparams = {'color': 'k', 'linewidth': 1.25,
'transform': ax.transAxes, 'solid_capstyle': 'butt'}
for y, label, active in zip(ys, labels, actives):
t = ax.text(0.25, y, label, transform=ax.transAxes,
horizontalalignment='left',
verticalalignment='center')
w, h = dy / 2, dy / 2
x, y = 0.05, y - h / 2
p = Rectangle(xy=(x, y), width=w, height=h, edgecolor='black',
facecolor=axcolor, transform=ax.transAxes)
l1 = Line2D([x, x + w], [y + h, y], **lineparams)
l2 = Line2D([x, x + w], [y, y + h], **lineparams)
l1.set_visible(active)
l2.set_visible(active)
self.labels.append(t)
self.rectangles.append(p)
self.lines.append((l1, l2))
ax.add_patch(p)
ax.add_line(l1)
ax.add_line(l2)
self.connect_event('button_press_event', self._clicked)
self.cnt = 0
self.observers = {}
def _clicked(self, event):
if self.ignore(event) or event.button != 1 or event.inaxes != self.ax:
return
for i, (p, t) in enumerate(zip(self.rectangles, self.labels)):
if (t.get_window_extent().contains(event.x, event.y) or
p.get_window_extent().contains(event.x, event.y)):
self.set_active(i)
break
def set_active(self, index):
"""
Directly (de)activate a check button by index.
*index* is an index into the original label list
that this object was constructed with.
Raises ValueError if *index* is invalid.
Callbacks will be triggered if :attr:`eventson` is True.
"""
if 0 > index >= len(self.labels):
raise ValueError("Invalid CheckButton index: %d" % index)
l1, l2 = self.lines[index]
l1.set_visible(not l1.get_visible())
l2.set_visible(not l2.get_visible())
if self.drawon:
self.ax.figure.canvas.draw()
if not self.eventson:
return
for cid, func in self.observers.items():
func(self.labels[index].get_text())
def get_status(self):
"""
returns a tuple of the status (True/False) of all of the check buttons
"""
return [l1.get_visible() for (l1, l2) in self.lines]
def on_clicked(self, func):
"""
Connect the callback function *func* to button click events.
Returns a connection id, which can be used to disconnect the callback.
"""
cid = self.cnt
self.observers[cid] = func
self.cnt += 1
return cid
def disconnect(self, cid):
"""remove the observer with connection id *cid*"""
try:
del self.observers[cid]
except KeyError:
pass
class TextBox(AxesWidget):
"""
A GUI neutral text input box.
For the text box to remain responsive you must keep a reference to it.
The following attributes are accessible:
*ax*
The :class:`matplotlib.axes.Axes` the button renders into.
*label*
A :class:`matplotlib.text.Text` instance.
*color*
The color of the text box when not hovering.
*hovercolor*
The color of the text box when hovering.
Call :meth:`on_text_change` to be updated whenever the text changes.
Call :meth:`on_submit` to be updated whenever the user hits enter or
leaves the text entry field.
"""
def __init__(self, ax, label, initial='',
color='.95', hovercolor='1', label_pad=.01):
"""
Parameters
----------
ax : matplotlib.axes.Axes
The :class:`matplotlib.axes.Axes` instance the button
will be placed into.
label : str
Label for this text box. Accepts string.
initial : str
Initial value in the text box
color : color
The color of the box
hovercolor : color
The color of the box when the mouse is over it
label_pad : float
the distance between the label and the right side of the textbox
"""
AxesWidget.__init__(self, ax)
self.DIST_FROM_LEFT = .05
self.params_to_disable = [key for key in rcParams if 'keymap' in key]
self.text = initial
self.label = ax.text(-label_pad, 0.5, label,
verticalalignment='center',
horizontalalignment='right',
transform=ax.transAxes)
self.text_disp = self._make_text_disp(self.text)
self.cnt = 0
self.change_observers = {}
self.submit_observers = {}
# If these lines are removed, the cursor won't appear the first
# time the box is clicked:
self.ax.set_xlim(0, 1)
self.ax.set_ylim(0, 1)
self.cursor_index = 0
# Because this is initialized, _render_cursor
# can assume that cursor exists.
self.cursor = self.ax.vlines(0, 0, 0)
self.cursor.set_visible(False)
self.connect_event('button_press_event', self._click)
self.connect_event('button_release_event', self._release)
self.connect_event('motion_notify_event', self._motion)
self.connect_event('key_press_event', self._keypress)
self.connect_event('resize_event', self._resize)
ax.set_navigate(False)
ax.set_facecolor(color)
ax.set_xticks([])
ax.set_yticks([])
self.color = color
self.hovercolor = hovercolor
self._lastcolor = color
self.capturekeystrokes = False
def _make_text_disp(self, string):
return self.ax.text(self.DIST_FROM_LEFT, 0.5, string,
verticalalignment='center',
horizontalalignment='left',
transform=self.ax.transAxes)
def _rendercursor(self):
# this is a hack to figure out where the cursor should go.
# we draw the text up to where the cursor should go, measure
# and save its dimensions, draw the real text, then put the cursor
# at the saved dimensions
widthtext = self.text[:self.cursor_index]
no_text = False
if(widthtext == "" or widthtext == " " or widthtext == " "):
no_text = widthtext == ""
widthtext = ","
wt_disp = self._make_text_disp(widthtext)
self.ax.figure.canvas.draw()
bb = wt_disp.get_window_extent()
inv = self.ax.transData.inverted()
bb = inv.transform(bb)
wt_disp.set_visible(False)
if no_text:
bb[1, 0] = bb[0, 0]
# hack done
self.cursor.set_visible(False)
self.cursor = self.ax.vlines(bb[1, 0], bb[0, 1], bb[1, 1])
self.ax.figure.canvas.draw()
def _notify_submit_observers(self):
for cid, func in self.submit_observers.items():
func(self.text)
def _release(self, event):
if self.ignore(event):
return
if event.canvas.mouse_grabber != self.ax:
return
event.canvas.release_mouse(self.ax)
def _keypress(self, event):
if self.ignore(event):
return
if self.capturekeystrokes:
key = event.key
if(len(key) == 1):
self.text = (self.text[:self.cursor_index] + key +
self.text[self.cursor_index:])
self.cursor_index += 1
elif key == "right":
if self.cursor_index != len(self.text):
self.cursor_index += 1
elif key == "left":
if self.cursor_index != 0:
self.cursor_index -= 1
elif key == "home":
self.cursor_index = 0
elif key == "end":
self.cursor_index = len(self.text)
elif(key == "backspace"):
if self.cursor_index != 0:
self.text = (self.text[:self.cursor_index - 1] +
self.text[self.cursor_index:])
self.cursor_index -= 1
elif(key == "delete"):
if self.cursor_index != len(self.text):
self.text = (self.text[:self.cursor_index] +
self.text[self.cursor_index + 1:])
self.text_disp.remove()
self.text_disp = self._make_text_disp(self.text)
self._rendercursor()
self._notify_change_observers()
if key == "enter":
self._notify_submit_observers()
def set_val(self, val):
newval = str(val)
if self.text == newval:
return
self.text = newval
self.text_disp.remove()
self.text_disp = self._make_text_disp(self.text)
self._rendercursor()
self._notify_change_observers()
self._notify_submit_observers()
def _notify_change_observers(self):
for cid, func in self.change_observers.items():
func(self.text)
def begin_typing(self, x):
self.capturekeystrokes = True
# disable command keys so that the user can type without
# command keys causing figure to be saved, etc
self.reset_params = {}
for key in self.params_to_disable:
self.reset_params[key] = rcParams[key]
rcParams[key] = []
def stop_typing(self):
notifysubmit = False
# because _notify_submit_users might throw an error in the
# user's code, we only want to call it once we've already done
# our cleanup.
if self.capturekeystrokes:
# since the user is no longer typing,
# reactivate the standard command keys
for key in self.params_to_disable:
rcParams[key] = self.reset_params[key]
notifysubmit = True
self.capturekeystrokes = False
self.cursor.set_visible(False)
self.ax.figure.canvas.draw()
if notifysubmit:
self._notify_submit_observers()
def position_cursor(self, x):
# now, we have to figure out where the cursor goes.
# approximate it based on assuming all characters the same length
if len(self.text) == 0:
self.cursor_index = 0
else:
bb = self.text_disp.get_window_extent()
trans = self.ax.transData
inv = self.ax.transData.inverted()
bb = trans.transform(inv.transform(bb))
text_start = bb[0, 0]
text_end = bb[1, 0]
ratio = (x - text_start) / (text_end - text_start)
if ratio < 0:
ratio = 0
if ratio > 1:
ratio = 1
self.cursor_index = int(len(self.text) * ratio)
self._rendercursor()
def _click(self, event):
if self.ignore(event):
return
if event.inaxes != self.ax:
self.stop_typing()
return
if not self.eventson:
return
if event.canvas.mouse_grabber != self.ax:
event.canvas.grab_mouse(self.ax)
if not self.capturekeystrokes:
self.begin_typing(event.x)
self.position_cursor(event.x)
def _resize(self, event):
self.stop_typing()
def _motion(self, event):
if self.ignore(event):
return
if event.inaxes == self.ax:
c = self.hovercolor
else:
c = self.color
if c != self._lastcolor:
self.ax.set_facecolor(c)
self._lastcolor = c
if self.drawon:
self.ax.figure.canvas.draw()
def on_text_change(self, func):
"""
When the text changes, call this *func* with event.
A connection id is returned which can be used to disconnect.
"""
cid = self.cnt
self.change_observers[cid] = func
self.cnt += 1
return cid
def on_submit(self, func):
"""
When the user hits enter or leaves the submission box, call this
*func* with event.
A connection id is returned which can be used to disconnect.
"""
cid = self.cnt
self.submit_observers[cid] = func
self.cnt += 1
return cid
def disconnect(self, cid):
"""Remove the observer with connection id *cid*."""
for reg in [self.change_observers, self.submit_observers]:
try:
del reg[cid]
except KeyError:
pass
class RadioButtons(AxesWidget):
"""
A GUI neutral radio button.
For the buttons to remain responsive you must keep a reference to this
object.
Connect to the RadioButtons with the :meth:`on_clicked` method.
Attributes
----------
ax
The containing `~.axes.Axes` instance.
activecolor
The color of the selected button.
labels
A list of `~.text.Text` instances containing the button labels.
circles
A list of `~.patches.Circle` instances defining the buttons.
value_selected : str
The label text of the currently selected button.
"""
def __init__(self, ax, labels, active=0, activecolor='blue'):
"""
Add radio buttons to an `~.axes.Axes`.
Parameters
----------
ax : `~matplotlib.axes.Axes`
The axes to add the buttons to.
labels : list of str
The button labels.
active : int
The index of the initially selected button.
activecolor : color
The color of the selected button.
"""
AxesWidget.__init__(self, ax)
self.activecolor = activecolor
self.value_selected = None
ax.set_xticks([])
ax.set_yticks([])
ax.set_navigate(False)
dy = 1. / (len(labels) + 1)
ys = np.linspace(1 - dy, dy, len(labels))
cnt = 0
axcolor = ax.get_facecolor()
# scale the radius of the circle with the spacing between each one
circle_radius = (dy / 2) - 0.01
# defaul to hard-coded value if the radius becomes too large
if(circle_radius > 0.05):
circle_radius = 0.05
self.labels = []
self.circles = []
for y, label in zip(ys, labels):
t = ax.text(0.25, y, label, transform=ax.transAxes,
horizontalalignment='left',
verticalalignment='center')
if cnt == active:
self.value_selected = label
facecolor = activecolor
else:
facecolor = axcolor
p = Circle(xy=(0.15, y), radius=circle_radius, edgecolor='black',
facecolor=facecolor, transform=ax.transAxes)
self.labels.append(t)
self.circles.append(p)
ax.add_patch(p)
cnt += 1
self.connect_event('button_press_event', self._clicked)
self.cnt = 0
self.observers = {}
def _clicked(self, event):
if self.ignore(event) or event.button != 1 or event.inaxes != self.ax:
return
xy = self.ax.transAxes.inverted().transform_point((event.x, event.y))
pclicked = np.array([xy[0], xy[1]])
distances = {}
for i, (p, t) in enumerate(zip(self.circles, self.labels)):
if (t.get_window_extent().contains(event.x, event.y)
or np.linalg.norm(pclicked - p.center) < p.radius):
distances[i] = np.linalg.norm(pclicked - p.center)
if len(distances) > 0:
closest = min(distances, key=distances.get)
self.set_active(closest)
def set_active(self, index):
"""
Select button with number *index*.
Callbacks will be triggered if :attr:`eventson` is True.
"""
if 0 > index >= len(self.labels):
raise ValueError("Invalid RadioButton index: %d" % index)
self.value_selected = self.labels[index].get_text()
for i, p in enumerate(self.circles):
if i == index:
color = self.activecolor
else:
color = self.ax.get_facecolor()
p.set_facecolor(color)
if self.drawon:
self.ax.figure.canvas.draw()
if not self.eventson:
return
for cid, func in self.observers.items():
func(self.labels[index].get_text())
def on_clicked(self, func):
"""
Connect the callback function *func* to button click events.
Returns a connection id, which can be used to disconnect the callback.
"""
cid = self.cnt
self.observers[cid] = func
self.cnt += 1
return cid
def disconnect(self, cid):
"""Remove the observer with connection id *cid*."""
try:
del self.observers[cid]
except KeyError:
pass
class SubplotTool(Widget):
"""
A tool to adjust the subplot params of a :class:`matplotlib.figure.Figure`.
"""
def __init__(self, targetfig, toolfig):
"""
*targetfig*
The figure instance to adjust.
*toolfig*
The figure instance to embed the subplot tool into. If
*None*, a default figure will be created. If you are using
this from the GUI
"""
# FIXME: The docstring seems to just abruptly end without...
self.targetfig = targetfig
toolfig.subplots_adjust(left=0.2, right=0.9)
self.axleft = toolfig.add_subplot(711)
self.axleft.set_title('Click on slider to adjust subplot param')
self.axleft.set_navigate(False)
self.sliderleft = Slider(self.axleft, 'left',
0, 1, targetfig.subplotpars.left,
closedmax=False)
self.sliderleft.on_changed(self.funcleft)
self.axbottom = toolfig.add_subplot(712)
self.axbottom.set_navigate(False)
self.sliderbottom = Slider(self.axbottom,
'bottom', 0, 1,
targetfig.subplotpars.bottom,
closedmax=False)
self.sliderbottom.on_changed(self.funcbottom)
self.axright = toolfig.add_subplot(713)
self.axright.set_navigate(False)
self.sliderright = Slider(self.axright, 'right', 0, 1,
targetfig.subplotpars.right,
closedmin=False)
self.sliderright.on_changed(self.funcright)
self.axtop = toolfig.add_subplot(714)
self.axtop.set_navigate(False)
self.slidertop = Slider(self.axtop, 'top', 0, 1,
targetfig.subplotpars.top,
closedmin=False)
self.slidertop.on_changed(self.functop)
self.axwspace = toolfig.add_subplot(715)
self.axwspace.set_navigate(False)
self.sliderwspace = Slider(self.axwspace, 'wspace',
0, 1, targetfig.subplotpars.wspace,
closedmax=False)
self.sliderwspace.on_changed(self.funcwspace)
self.axhspace = toolfig.add_subplot(716)
self.axhspace.set_navigate(False)
self.sliderhspace = Slider(self.axhspace, 'hspace',
0, 1, targetfig.subplotpars.hspace,
closedmax=False)
self.sliderhspace.on_changed(self.funchspace)
# constraints
self.sliderleft.slidermax = self.sliderright
self.sliderright.slidermin = self.sliderleft
self.sliderbottom.slidermax = self.slidertop
self.slidertop.slidermin = self.sliderbottom
bax = toolfig.add_axes([0.8, 0.05, 0.15, 0.075])
self.buttonreset = Button(bax, 'Reset')
sliders = (self.sliderleft, self.sliderbottom, self.sliderright,
self.slidertop, self.sliderwspace, self.sliderhspace,)
def func(event):
thisdrawon = self.drawon
self.drawon = False
# store the drawon state of each slider
bs = []
for slider in sliders:
bs.append(slider.drawon)
slider.drawon = False
# reset the slider to the initial position
for slider in sliders:
slider.reset()
# reset drawon
for slider, b in zip(sliders, bs):
slider.drawon = b
# draw the canvas
self.drawon = thisdrawon
if self.drawon:
toolfig.canvas.draw()
self.targetfig.canvas.draw()
# during reset there can be a temporary invalid state
# depending on the order of the reset so we turn off
# validation for the resetting
validate = toolfig.subplotpars.validate
toolfig.subplotpars.validate = False
self.buttonreset.on_clicked(func)
toolfig.subplotpars.validate = validate
def funcleft(self, val):
self.targetfig.subplots_adjust(left=val)
if self.drawon:
self.targetfig.canvas.draw()
def funcright(self, val):
self.targetfig.subplots_adjust(right=val)
if self.drawon:
self.targetfig.canvas.draw()
def funcbottom(self, val):
self.targetfig.subplots_adjust(bottom=val)
if self.drawon:
self.targetfig.canvas.draw()
def functop(self, val):
self.targetfig.subplots_adjust(top=val)
if self.drawon:
self.targetfig.canvas.draw()
def funcwspace(self, val):
self.targetfig.subplots_adjust(wspace=val)
if self.drawon:
self.targetfig.canvas.draw()
def funchspace(self, val):
self.targetfig.subplots_adjust(hspace=val)
if self.drawon:
self.targetfig.canvas.draw()
class Cursor(AxesWidget):
"""
A crosshair cursor that spans the axes and moves with mouse cursor.
For the cursor to remain responsive you must keep a reference to it.
Parameters
----------
ax : `matplotlib.axes.Axes`
The `~.axes.Axes` to attach the cursor to.
horizOn : bool, optional, default: True
Whether to draw the horizontal line.
vertOn : bool, optional, default: True
Whether to draw the vertical line.
useblit : bool, optional, default: False
Use blitting for faster drawing if supported by the backend.
Other Parameters
----------------
**lineprops
`.Line2D` properties that control the appearance of the lines.
See also `~.Axes.axhline`.
Examples
--------
See :doc:`/gallery/widgets/cursor`.
"""
def __init__(self, ax, horizOn=True, vertOn=True, useblit=False,
**lineprops):
AxesWidget.__init__(self, ax)
self.connect_event('motion_notify_event', self.onmove)
self.connect_event('draw_event', self.clear)
self.visible = True
self.horizOn = horizOn
self.vertOn = vertOn
self.useblit = useblit and self.canvas.supports_blit
if self.useblit:
lineprops['animated'] = True
self.lineh = ax.axhline(ax.get_ybound()[0], visible=False, **lineprops)
self.linev = ax.axvline(ax.get_xbound()[0], visible=False, **lineprops)
self.background = None
self.needclear = False
def clear(self, event):
"""Internal event handler to clear the cursor."""
if self.ignore(event):
return
if self.useblit:
self.background = self.canvas.copy_from_bbox(self.ax.bbox)
self.linev.set_visible(False)
self.lineh.set_visible(False)
def onmove(self, event):
"""Internal event handler to draw the cursor when the mouse moves."""
if self.ignore(event):
return
if not self.canvas.widgetlock.available(self):
return
if event.inaxes != self.ax:
self.linev.set_visible(False)
self.lineh.set_visible(False)
if self.needclear:
self.canvas.draw()
self.needclear = False
return
self.needclear = True
if not self.visible:
return
self.linev.set_xdata((event.xdata, event.xdata))
self.lineh.set_ydata((event.ydata, event.ydata))
self.linev.set_visible(self.visible and self.vertOn)
self.lineh.set_visible(self.visible and self.horizOn)
self._update()
def _update(self):
if self.useblit:
if self.background is not None:
self.canvas.restore_region(self.background)
self.ax.draw_artist(self.linev)
self.ax.draw_artist(self.lineh)
self.canvas.blit(self.ax.bbox)
else:
self.canvas.draw_idle()
return False
class MultiCursor(Widget):
"""
Provide a vertical (default) and/or horizontal line cursor shared between
multiple axes.
For the cursor to remain responsive you must keep a reference to
it.
Example usage::
from matplotlib.widgets import MultiCursor
import matplotlib.pyplot as plt
import numpy as np
fig, (ax1, ax2) = plt.subplots(nrows=2, sharex=True)
t = np.arange(0.0, 2.0, 0.01)
ax1.plot(t, np.sin(2*np.pi*t))
ax2.plot(t, np.sin(4*np.pi*t))
multi = MultiCursor(fig.canvas, (ax1, ax2), color='r', lw=1,
horizOn=False, vertOn=True)
plt.show()
"""
def __init__(self, canvas, axes, useblit=True, horizOn=False, vertOn=True,
**lineprops):
self.canvas = canvas
self.axes = axes
self.horizOn = horizOn
self.vertOn = vertOn
xmin, xmax = axes[-1].get_xlim()
ymin, ymax = axes[-1].get_ylim()
xmid = 0.5 * (xmin + xmax)
ymid = 0.5 * (ymin + ymax)
self.visible = True
self.useblit = useblit and self.canvas.supports_blit
self.background = None
self.needclear = False
if self.useblit:
lineprops['animated'] = True
if vertOn:
self.vlines = [ax.axvline(xmid, visible=False, **lineprops)
for ax in axes]
else:
self.vlines = []
if horizOn:
self.hlines = [ax.axhline(ymid, visible=False, **lineprops)
for ax in axes]
else:
self.hlines = []
self.connect()
def connect(self):
"""connect events"""
self._cidmotion = self.canvas.mpl_connect('motion_notify_event',
self.onmove)
self._ciddraw = self.canvas.mpl_connect('draw_event', self.clear)
def disconnect(self):
"""disconnect events"""
self.canvas.mpl_disconnect(self._cidmotion)
self.canvas.mpl_disconnect(self._ciddraw)
def clear(self, event):
"""clear the cursor"""
if self.ignore(event):
return
if self.useblit:
self.background = (
self.canvas.copy_from_bbox(self.canvas.figure.bbox))
for line in self.vlines + self.hlines:
line.set_visible(False)
def onmove(self, event):
if self.ignore(event):
return
if event.inaxes is None:
return
if not self.canvas.widgetlock.available(self):
return
self.needclear = True
if not self.visible:
return
if self.vertOn:
for line in self.vlines:
line.set_xdata((event.xdata, event.xdata))
line.set_visible(self.visible)
if self.horizOn:
for line in self.hlines:
line.set_ydata((event.ydata, event.ydata))
line.set_visible(self.visible)
self._update()
def _update(self):
if self.useblit:
if self.background is not None:
self.canvas.restore_region(self.background)
if self.vertOn:
for ax, line in zip(self.axes, self.vlines):
ax.draw_artist(line)
if self.horizOn:
for ax, line in zip(self.axes, self.hlines):
ax.draw_artist(line)
self.canvas.blit(self.canvas.figure.bbox)
else:
self.canvas.draw_idle()
class _SelectorWidget(AxesWidget):
def __init__(self, ax, onselect, useblit=False, button=None,
state_modifier_keys=None):
AxesWidget.__init__(self, ax)
self.visible = True
self.onselect = onselect
self.useblit = useblit and self.canvas.supports_blit
self.connect_default_events()
self.state_modifier_keys = dict(move=' ', clear='escape',
square='shift', center='control')
self.state_modifier_keys.update(state_modifier_keys or {})
self.background = None
self.artists = []
if isinstance(button, Integral):
self.validButtons = [button]
else:
self.validButtons = button
# will save the data (position at mouseclick)
self.eventpress = None
# will save the data (pos. at mouserelease)
self.eventrelease = None
self._prev_event = None
self.state = set()
def set_active(self, active):
AxesWidget.set_active(self, active)
if active:
self.update_background(None)
def update_background(self, event):
"""force an update of the background"""
# If you add a call to `ignore` here, you'll want to check edge case:
# `release` can call a draw event even when `ignore` is True.
if self.useblit:
self.background = self.canvas.copy_from_bbox(self.ax.bbox)
def connect_default_events(self):
"""Connect the major canvas events to methods."""
self.connect_event('motion_notify_event', self.onmove)
self.connect_event('button_press_event', self.press)
self.connect_event('button_release_event', self.release)
self.connect_event('draw_event', self.update_background)
self.connect_event('key_press_event', self.on_key_press)
self.connect_event('key_release_event', self.on_key_release)
self.connect_event('scroll_event', self.on_scroll)
def ignore(self, event):
"""return *True* if *event* should be ignored"""
if not self.active or not self.ax.get_visible():
return True
# If canvas was locked
if not self.canvas.widgetlock.available(self):
return True
if not hasattr(event, 'button'):
event.button = None
# Only do rectangle selection if event was triggered
# with a desired button
if self.validButtons is not None:
if event.button not in self.validButtons:
return True
# If no button was pressed yet ignore the event if it was out
# of the axes
if self.eventpress is None:
return event.inaxes != self.ax
# If a button was pressed, check if the release-button is the
# same.
if event.button == self.eventpress.button:
return False
# If a button was pressed, check if the release-button is the
# same.
return (event.inaxes != self.ax or
event.button != self.eventpress.button)
def update(self):
"""draw using newfangled blit or oldfangled draw depending on
useblit
"""
if not self.ax.get_visible():
return False
if self.useblit:
if self.background is not None:
self.canvas.restore_region(self.background)
for artist in self.artists:
self.ax.draw_artist(artist)
self.canvas.blit(self.ax.bbox)
else:
self.canvas.draw_idle()
return False
def _get_data(self, event):
"""Get the xdata and ydata for event, with limits"""
if event.xdata is None:
return None, None
x0, x1 = self.ax.get_xbound()
y0, y1 = self.ax.get_ybound()
xdata = max(x0, event.xdata)
xdata = min(x1, xdata)
ydata = max(y0, event.ydata)
ydata = min(y1, ydata)
return xdata, ydata
def _clean_event(self, event):
"""Clean up an event
Use prev event if there is no xdata
Limit the xdata and ydata to the axes limits
Set the prev event
"""
if event.xdata is None:
event = self._prev_event
else:
event = copy.copy(event)
event.xdata, event.ydata = self._get_data(event)
self._prev_event = event
return event
def press(self, event):
"""Button press handler and validator"""
if not self.ignore(event):
event = self._clean_event(event)
self.eventpress = event
self._prev_event = event
key = event.key or ''
key = key.replace('ctrl', 'control')
# move state is locked in on a button press
if key == self.state_modifier_keys['move']:
self.state.add('move')
self._press(event)
return True
return False
def _press(self, event):
"""Button press handler"""
pass
def release(self, event):
"""Button release event handler and validator"""
if not self.ignore(event) and self.eventpress:
event = self._clean_event(event)
self.eventrelease = event
self._release(event)
self.eventpress = None
self.eventrelease = None
self.state.discard('move')
return True
return False
def _release(self, event):
"""Button release event handler"""
pass
def onmove(self, event):
"""Cursor move event handler and validator"""
if not self.ignore(event) and self.eventpress:
event = self._clean_event(event)
self._onmove(event)
return True
return False
def _onmove(self, event):
"""Cursor move event handler"""
pass
def on_scroll(self, event):
"""Mouse scroll event handler and validator"""
if not self.ignore(event):
self._on_scroll(event)
def _on_scroll(self, event):
"""Mouse scroll event handler"""
pass
def on_key_press(self, event):
"""Key press event handler and validator for all selection widgets"""
if self.active:
key = event.key or ''
key = key.replace('ctrl', 'control')
if key == self.state_modifier_keys['clear']:
for artist in self.artists:
artist.set_visible(False)
self.update()
return
for (state, modifier) in self.state_modifier_keys.items():
if modifier in key:
self.state.add(state)
self._on_key_press(event)
def _on_key_press(self, event):
"""Key press event handler - use for widget-specific key press actions.
"""
pass
def on_key_release(self, event):
"""Key release event handler and validator."""
if self.active:
key = event.key or ''
for (state, modifier) in self.state_modifier_keys.items():
if modifier in key:
self.state.discard(state)
self._on_key_release(event)
def _on_key_release(self, event):
"""Key release event handler."""
def set_visible(self, visible):
"""Set the visibility of our artists."""
self.visible = visible
for artist in self.artists:
artist.set_visible(visible)
class SpanSelector(_SelectorWidget):
"""
Visually select a min/max range on a single axis and call a function with
those values.
To guarantee that the selector remains responsive, keep a reference to it.
In order to turn off the SpanSelector, set `span_selector.active=False`. To
turn it back on, set `span_selector.active=True`.
Parameters
----------
ax : :class:`matplotlib.axes.Axes` object
onselect : func(min, max), min/max are floats
direction : "horizontal" or "vertical"
The axis along which to draw the span selector
minspan : float, default is None
If selection is less than *minspan*, do not call *onselect*
useblit : bool, default is False
If True, use the backend-dependent blitting features for faster
canvas updates.
rectprops : dict, default is None
Dictionary of :class:`matplotlib.patches.Patch` properties
onmove_callback : func(min, max), min/max are floats, default is None
Called on mouse move while the span is being selected
span_stays : bool, default is False
If True, the span stays visible after the mouse is released
button : int or list of ints
Determines which mouse buttons activate the span selector
1 = left mouse button\n
2 = center mouse button (scroll wheel)\n
3 = right mouse button\n
Examples
--------
>>> import matplotlib.pyplot as plt
>>> import matplotlib.widgets as mwidgets
>>> fig, ax = plt.subplots()
>>> ax.plot([1, 2, 3], [10, 50, 100])
>>> def onselect(vmin, vmax):
... print(vmin, vmax)
>>> rectprops = dict(facecolor='blue', alpha=0.5)
>>> span = mwidgets.SpanSelector(ax, onselect, 'horizontal',
... rectprops=rectprops)
>>> fig.show()
See also: :doc:`/gallery/widgets/span_selector`
"""
def __init__(self, ax, onselect, direction, minspan=None, useblit=False,
rectprops=None, onmove_callback=None, span_stays=False,
button=None):
_SelectorWidget.__init__(self, ax, onselect, useblit=useblit,
button=button)
if rectprops is None:
rectprops = dict(facecolor='red', alpha=0.5)
rectprops['animated'] = self.useblit
cbook._check_in_list(['horizontal', 'vertical'], direction=direction)
self.direction = direction
self.rect = None
self.pressv = None
self.rectprops = rectprops
self.onmove_callback = onmove_callback
self.minspan = minspan
self.span_stays = span_stays
# Needed when dragging out of axes
self.prev = (0, 0)
# Reset canvas so that `new_axes` connects events.
self.canvas = None
self.new_axes(ax)
def new_axes(self, ax):
"""Set SpanSelector to operate on a new Axes"""
self.ax = ax
if self.canvas is not ax.figure.canvas:
if self.canvas is not None:
self.disconnect_events()
self.canvas = ax.figure.canvas
self.connect_default_events()
if self.direction == 'horizontal':
trans = blended_transform_factory(self.ax.transData,
self.ax.transAxes)
w, h = 0, 1
else:
trans = blended_transform_factory(self.ax.transAxes,
self.ax.transData)
w, h = 1, 0
self.rect = Rectangle((0, 0), w, h,
transform=trans,
visible=False,
**self.rectprops)
if self.span_stays:
self.stay_rect = Rectangle((0, 0), w, h,
transform=trans,
visible=False,
**self.rectprops)
self.stay_rect.set_animated(False)
self.ax.add_patch(self.stay_rect)
self.ax.add_patch(self.rect)
self.artists = [self.rect]
def ignore(self, event):
"""return *True* if *event* should be ignored"""
return _SelectorWidget.ignore(self, event) or not self.visible
def _press(self, event):
"""on button press event"""
self.rect.set_visible(self.visible)
if self.span_stays:
self.stay_rect.set_visible(False)
# really force a draw so that the stay rect is not in
# the blit background
if self.useblit:
self.canvas.draw()
xdata, ydata = self._get_data(event)
if self.direction == 'horizontal':
self.pressv = xdata
else:
self.pressv = ydata
self._set_span_xy(event)
return False
def _release(self, event):
"""on button release event"""
if self.pressv is None:
return
self.rect.set_visible(False)
if self.span_stays:
self.stay_rect.set_x(self.rect.get_x())
self.stay_rect.set_y(self.rect.get_y())
self.stay_rect.set_width(self.rect.get_width())
self.stay_rect.set_height(self.rect.get_height())
self.stay_rect.set_visible(True)
self.canvas.draw_idle()
vmin = self.pressv
xdata, ydata = self._get_data(event)
if self.direction == 'horizontal':
vmax = xdata or self.prev[0]
else:
vmax = ydata or self.prev[1]
if vmin > vmax:
vmin, vmax = vmax, vmin
span = vmax - vmin
if self.minspan is not None and span < self.minspan:
return
self.onselect(vmin, vmax)
self.pressv = None
return False
@cbook.deprecated("3.1")
@property
def buttonDown(self):
return False
def _onmove(self, event):
"""on motion notify event"""
if self.pressv is None:
return
self._set_span_xy(event)
if self.onmove_callback is not None:
vmin = self.pressv
xdata, ydata = self._get_data(event)
if self.direction == 'horizontal':
vmax = xdata or self.prev[0]
else:
vmax = ydata or self.prev[1]
if vmin > vmax:
vmin, vmax = vmax, vmin
self.onmove_callback(vmin, vmax)
self.update()
return False
def _set_span_xy(self, event):
"""Setting the span coordinates"""
x, y = self._get_data(event)
if x is None:
return
self.prev = x, y
if self.direction == 'horizontal':
v = x
else:
v = y
minv, maxv = v, self.pressv
if minv > maxv:
minv, maxv = maxv, minv
if self.direction == 'horizontal':
self.rect.set_x(minv)
self.rect.set_width(maxv - minv)
else:
self.rect.set_y(minv)
self.rect.set_height(maxv - minv)
class ToolHandles(object):
"""Control handles for canvas tools.
Parameters
----------
ax : :class:`matplotlib.axes.Axes`
Matplotlib axes where tool handles are displayed.
x, y : 1D arrays
Coordinates of control handles.
marker : str
Shape of marker used to display handle. See `matplotlib.pyplot.plot`.
marker_props : dict
Additional marker properties. See :class:`matplotlib.lines.Line2D`.
"""
def __init__(self, ax, x, y, marker='o', marker_props=None, useblit=True):
self.ax = ax
props = dict(marker=marker, markersize=7, mfc='w', ls='none',
alpha=0.5, visible=False, label='_nolegend_')
props.update(marker_props if marker_props is not None else {})
self._markers = Line2D(x, y, animated=useblit, **props)
self.ax.add_line(self._markers)
self.artist = self._markers
@property
def x(self):
return self._markers.get_xdata()
@property
def y(self):
return self._markers.get_ydata()
def set_data(self, pts, y=None):
"""Set x and y positions of handles"""
if y is not None:
x = pts
pts = np.array([x, y])
self._markers.set_data(pts)
def set_visible(self, val):
self._markers.set_visible(val)
def set_animated(self, val):
self._markers.set_animated(val)
def closest(self, x, y):
"""Return index and pixel distance to closest index."""
pts = np.transpose((self.x, self.y))
# Transform data coordinates to pixel coordinates.
pts = self.ax.transData.transform(pts)
diff = pts - ((x, y))
if diff.ndim == 2:
dist = np.sqrt(np.sum(diff ** 2, axis=1))
return np.argmin(dist), np.min(dist)
else:
return 0, np.sqrt(np.sum(diff ** 2))
class RectangleSelector(_SelectorWidget):
"""
Select a rectangular region of an axes.
For the cursor to remain responsive you must keep a reference to
it.
Example usage::
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import RectangleSelector
def onselect(eclick, erelease):
"eclick and erelease are matplotlib events at press and release."
print('startposition: (%f, %f)' % (eclick.xdata, eclick.ydata))
print('endposition : (%f, %f)' % (erelease.xdata, erelease.ydata))
print('used button : ', eclick.button)
def toggle_selector(event):
print('Key pressed.')
if event.key in ['Q', 'q'] and toggle_selector.RS.active:
print('RectangleSelector deactivated.')
toggle_selector.RS.set_active(False)
if event.key in ['A', 'a'] and not toggle_selector.RS.active:
print('RectangleSelector activated.')
toggle_selector.RS.set_active(True)
x = np.arange(100.) / 99
y = np.sin(x)
fig, ax = plt.subplots()
ax.plot(x, y)
toggle_selector.RS = RectangleSelector(ax, onselect, drawtype='line')
fig.canvas.mpl_connect('key_press_event', toggle_selector)
plt.show()
"""
_shape_klass = Rectangle
def __init__(self, ax, onselect, drawtype='box',
minspanx=None, minspany=None, useblit=False,
lineprops=None, rectprops=None, spancoords='data',
button=None, maxdist=10, marker_props=None,
interactive=False, state_modifier_keys=None):
"""
Create a selector in *ax*. When a selection is made, clear
the span and call onselect with::
onselect(pos_1, pos_2)
and clear the drawn box/line. The ``pos_1`` and ``pos_2`` are
arrays of length 2 containing the x- and y-coordinate.
If *minspanx* is not *None* then events smaller than *minspanx*
in x direction are ignored (it's the same for y).
The rectangle is drawn with *rectprops*; default::
rectprops = dict(facecolor='red', edgecolor = 'black',
alpha=0.2, fill=True)
The line is drawn with *lineprops*; default::
lineprops = dict(color='black', linestyle='-',
linewidth = 2, alpha=0.5)
Use *drawtype* if you want the mouse to draw a line,
a box or nothing between click and actual position by setting
``drawtype = 'line'``, ``drawtype='box'`` or ``drawtype = 'none'``.
Drawing a line would result in a line from vertex A to vertex C in
a rectangle ABCD.
*spancoords* is one of 'data' or 'pixels'. If 'data', *minspanx*
and *minspanx* will be interpreted in the same coordinates as
the x and y axis. If 'pixels', they are in pixels.
*button* is a list of integers indicating which mouse buttons should
be used for rectangle selection. You can also specify a single
integer if only a single button is desired. Default is *None*,
which does not limit which button can be used.
Note, typically:
1 = left mouse button
2 = center mouse button (scroll wheel)
3 = right mouse button
*interactive* will draw a set of handles and allow you interact
with the widget after it is drawn.
*state_modifier_keys* are keyboard modifiers that affect the behavior
of the widget.
The defaults are:
dict(move=' ', clear='escape', square='shift', center='ctrl')
Keyboard modifiers, which:
'move': Move the existing shape.
'clear': Clear the current shape.
'square': Makes the shape square.
'center': Make the initial point the center of the shape.
'square' and 'center' can be combined.
"""
_SelectorWidget.__init__(self, ax, onselect, useblit=useblit,
button=button,
state_modifier_keys=state_modifier_keys)
self.to_draw = None
self.visible = True
self.interactive = interactive
if drawtype == 'none':
drawtype = 'line' # draw a line but make it
self.visible = False # invisible
if drawtype == 'box':
if rectprops is None:
rectprops = dict(facecolor='red', edgecolor='black',
alpha=0.2, fill=True)
rectprops['animated'] = self.useblit
self.rectprops = rectprops
self.to_draw = self._shape_klass((0, 0), 0, 1, visible=False,
**self.rectprops)
self.ax.add_patch(self.to_draw)
if drawtype == 'line':
if lineprops is None:
lineprops = dict(color='black', linestyle='-',
linewidth=2, alpha=0.5)
lineprops['animated'] = self.useblit
self.lineprops = lineprops
self.to_draw = Line2D([0, 0], [0, 0], visible=False,
**self.lineprops)
self.ax.add_line(self.to_draw)
self.minspanx = minspanx
self.minspany = minspany
cbook._check_in_list(['data', 'pixels'], spancoords=spancoords)
self.spancoords = spancoords
self.drawtype = drawtype
self.maxdist = maxdist
if rectprops is None:
props = dict(mec='r')
else:
props = dict(mec=rectprops.get('edgecolor', 'r'))
self._corner_order = ['NW', 'NE', 'SE', 'SW']
xc, yc = self.corners
self._corner_handles = ToolHandles(self.ax, xc, yc, marker_props=props,
useblit=self.useblit)
self._edge_order = ['W', 'N', 'E', 'S']
xe, ye = self.edge_centers
self._edge_handles = ToolHandles(self.ax, xe, ye, marker='s',
marker_props=props,
useblit=self.useblit)
xc, yc = self.center
self._center_handle = ToolHandles(self.ax, [xc], [yc], marker='s',
marker_props=props,
useblit=self.useblit)
self.active_handle = None
self.artists = [self.to_draw, self._center_handle.artist,
self._corner_handles.artist,
self._edge_handles.artist]
if not self.interactive:
self.artists = [self.to_draw]
self._extents_on_press = None
def _press(self, event):
"""on button press event"""
# make the drawed box/line visible get the click-coordinates,
# button, ...
if self.interactive and self.to_draw.get_visible():
self._set_active_handle(event)
else:
self.active_handle = None
if self.active_handle is None or not self.interactive:
# Clear previous rectangle before drawing new rectangle.
self.update()
if not self.interactive:
x = event.xdata
y = event.ydata
self.extents = x, x, y, y
self.set_visible(self.visible)
def _release(self, event):
"""on button release event"""
if not self.interactive:
self.to_draw.set_visible(False)
# update the eventpress and eventrelease with the resulting extents
x1, x2, y1, y2 = self.extents
self.eventpress.xdata = x1
self.eventpress.ydata = y1
xy1 = self.ax.transData.transform_point([x1, y1])
self.eventpress.x, self.eventpress.y = xy1
self.eventrelease.xdata = x2
self.eventrelease.ydata = y2
xy2 = self.ax.transData.transform_point([x2, y2])
self.eventrelease.x, self.eventrelease.y = xy2
if self.spancoords == 'data':
xmin, ymin = self.eventpress.xdata, self.eventpress.ydata
xmax, ymax = self.eventrelease.xdata, self.eventrelease.ydata
# calculate dimensions of box or line get values in the right order
elif self.spancoords == 'pixels':
xmin, ymin = self.eventpress.x, self.eventpress.y
xmax, ymax = self.eventrelease.x, self.eventrelease.y
else:
cbook._check_in_list(['data', 'pixels'],
spancoords=self.spancoords)
if xmin > xmax:
xmin, xmax = xmax, xmin
if ymin > ymax:
ymin, ymax = ymax, ymin
spanx = xmax - xmin
spany = ymax - ymin
xproblems = self.minspanx is not None and spanx < self.minspanx
yproblems = self.minspany is not None and spany < self.minspany
# check if drawn distance (if it exists) is not too small in
# either x or y-direction
if self.drawtype != 'none' and (xproblems or yproblems):
for artist in self.artists:
artist.set_visible(False)
self.update()
return
# call desired function
self.onselect(self.eventpress, self.eventrelease)
self.update()
return False
def _onmove(self, event):
"""on motion notify event if box/line is wanted"""
# resize an existing shape
if self.active_handle and not self.active_handle == 'C':
x1, x2, y1, y2 = self._extents_on_press
if self.active_handle in ['E', 'W'] + self._corner_order:
x2 = event.xdata
if self.active_handle in ['N', 'S'] + self._corner_order:
y2 = event.ydata
# move existing shape
elif (('move' in self.state or self.active_handle == 'C')
and self._extents_on_press is not None):
x1, x2, y1, y2 = self._extents_on_press
dx = event.xdata - self.eventpress.xdata
dy = event.ydata - self.eventpress.ydata
x1 += dx
x2 += dx
y1 += dy
y2 += dy
# new shape
else:
center = [self.eventpress.xdata, self.eventpress.ydata]
center_pix = [self.eventpress.x, self.eventpress.y]
dx = (event.xdata - center[0]) / 2.
dy = (event.ydata - center[1]) / 2.
# square shape
if 'square' in self.state:
dx_pix = abs(event.x - center_pix[0])
dy_pix = abs(event.y - center_pix[1])
if not dx_pix:
return
maxd = max(abs(dx_pix), abs(dy_pix))
if abs(dx_pix) < maxd:
dx *= maxd / (abs(dx_pix) + 1e-6)
if abs(dy_pix) < maxd:
dy *= maxd / (abs(dy_pix) + 1e-6)
# from center
if 'center' in self.state:
dx *= 2
dy *= 2
# from corner
else:
center[0] += dx
center[1] += dy
x1, x2, y1, y2 = (center[0] - dx, center[0] + dx,
center[1] - dy, center[1] + dy)
self.extents = x1, x2, y1, y2
@property
def _rect_bbox(self):
if self.drawtype == 'box':
x0 = self.to_draw.get_x()
y0 = self.to_draw.get_y()
width = self.to_draw.get_width()
height = self.to_draw.get_height()
return x0, y0, width, height
else:
x, y = self.to_draw.get_data()
x0, x1 = min(x), max(x)
y0, y1 = min(y), max(y)
return x0, y0, x1 - x0, y1 - y0
@property
def corners(self):
"""Corners of rectangle from lower left, moving clockwise."""
x0, y0, width, height = self._rect_bbox
xc = x0, x0 + width, x0 + width, x0
yc = y0, y0, y0 + height, y0 + height
return xc, yc
@property
def edge_centers(self):
"""Midpoint of rectangle edges from left, moving clockwise."""
x0, y0, width, height = self._rect_bbox
w = width / 2.
h = height / 2.
xe = x0, x0 + w, x0 + width, x0 + w
ye = y0 + h, y0, y0 + h, y0 + height
return xe, ye
@property
def center(self):
"""Center of rectangle"""
x0, y0, width, height = self._rect_bbox
return x0 + width / 2., y0 + height / 2.
@property
def extents(self):
"""Return (xmin, xmax, ymin, ymax)."""
x0, y0, width, height = self._rect_bbox
xmin, xmax = sorted([x0, x0 + width])
ymin, ymax = sorted([y0, y0 + height])
return xmin, xmax, ymin, ymax
@extents.setter
def extents(self, extents):
# Update displayed shape
self.draw_shape(extents)
# Update displayed handles
self._corner_handles.set_data(*self.corners)
self._edge_handles.set_data(*self.edge_centers)
self._center_handle.set_data(*self.center)
self.set_visible(self.visible)
self.update()
def draw_shape(self, extents):
x0, x1, y0, y1 = extents
xmin, xmax = sorted([x0, x1])
ymin, ymax = sorted([y0, y1])
xlim = sorted(self.ax.get_xlim())
ylim = sorted(self.ax.get_ylim())
xmin = max(xlim[0], xmin)
ymin = max(ylim[0], ymin)
xmax = min(xmax, xlim[1])
ymax = min(ymax, ylim[1])
if self.drawtype == 'box':
self.to_draw.set_x(xmin)
self.to_draw.set_y(ymin)
self.to_draw.set_width(xmax - xmin)
self.to_draw.set_height(ymax - ymin)
elif self.drawtype == 'line':
self.to_draw.set_data([xmin, xmax], [ymin, ymax])
def _set_active_handle(self, event):
"""Set active handle based on the location of the mouse event"""
# Note: event.xdata/ydata in data coordinates, event.x/y in pixels
c_idx, c_dist = self._corner_handles.closest(event.x, event.y)
e_idx, e_dist = self._edge_handles.closest(event.x, event.y)
m_idx, m_dist = self._center_handle.closest(event.x, event.y)
if 'move' in self.state:
self.active_handle = 'C'
self._extents_on_press = self.extents
# Set active handle as closest handle, if mouse click is close enough.
elif m_dist < self.maxdist * 2:
self.active_handle = 'C'
elif c_dist > self.maxdist and e_dist > self.maxdist:
self.active_handle = None
return
elif c_dist < e_dist:
self.active_handle = self._corner_order[c_idx]
else:
self.active_handle = self._edge_order[e_idx]
# Save coordinates of rectangle at the start of handle movement.
x1, x2, y1, y2 = self.extents
# Switch variables so that only x2 and/or y2 are updated on move.
if self.active_handle in ['W', 'SW', 'NW']:
x1, x2 = x2, event.xdata
if self.active_handle in ['N', 'NW', 'NE']:
y1, y2 = y2, event.ydata
self._extents_on_press = x1, x2, y1, y2
@property
def geometry(self):
"""
Returns numpy.ndarray of shape (2,5) containing
x (``RectangleSelector.geometry[1,:]``) and
y (``RectangleSelector.geometry[0,:]``)
coordinates of the four corners of the rectangle starting
and ending in the top left corner.
"""
if hasattr(self.to_draw, 'get_verts'):
xfm = self.ax.transData.inverted()
y, x = xfm.transform(self.to_draw.get_verts()).T
return np.array([x, y])
else:
return np.array(self.to_draw.get_data())
class EllipseSelector(RectangleSelector):
"""
Select an elliptical region of an axes.
For the cursor to remain responsive you must keep a reference to
it.
Example usage::
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import EllipseSelector
def onselect(eclick, erelease):
"eclick and erelease are matplotlib events at press and release."
print('startposition: (%f, %f)' % (eclick.xdata, eclick.ydata))
print('endposition : (%f, %f)' % (erelease.xdata, erelease.ydata))
print('used button : ', eclick.button)
def toggle_selector(event):
print(' Key pressed.')
if event.key in ['Q', 'q'] and toggle_selector.ES.active:
print('EllipseSelector deactivated.')
toggle_selector.RS.set_active(False)
if event.key in ['A', 'a'] and not toggle_selector.ES.active:
print('EllipseSelector activated.')
toggle_selector.ES.set_active(True)
x = np.arange(100.) / 99
y = np.sin(x)
fig, ax = plt.subplots()
ax.plot(x, y)
toggle_selector.ES = EllipseSelector(ax, onselect, drawtype='line')
fig.canvas.mpl_connect('key_press_event', toggle_selector)
plt.show()
"""
_shape_klass = Ellipse
def draw_shape(self, extents):
x1, x2, y1, y2 = extents
xmin, xmax = sorted([x1, x2])
ymin, ymax = sorted([y1, y2])
center = [x1 + (x2 - x1) / 2., y1 + (y2 - y1) / 2.]
a = (xmax - xmin) / 2.
b = (ymax - ymin) / 2.
if self.drawtype == 'box':
self.to_draw.center = center
self.to_draw.width = 2 * a
self.to_draw.height = 2 * b
else:
rad = np.deg2rad(np.arange(31) * 12)
x = a * np.cos(rad) + center[0]
y = b * np.sin(rad) + center[1]
self.to_draw.set_data(x, y)
@property
def _rect_bbox(self):
if self.drawtype == 'box':
x, y = self.to_draw.center
width = self.to_draw.width
height = self.to_draw.height
return x - width / 2., y - height / 2., width, height
else:
x, y = self.to_draw.get_data()
x0, x1 = min(x), max(x)
y0, y1 = min(y), max(y)
return x0, y0, x1 - x0, y1 - y0
class LassoSelector(_SelectorWidget):
"""
Selection curve of an arbitrary shape.
For the selector to remain responsive you must keep a reference to it.
The selected path can be used in conjunction with `~.Path.contains_point`
to select data points from an image.
In contrast to `Lasso`, `LassoSelector` is written with an interface
similar to `RectangleSelector` and `SpanSelector`, and will continue to
interact with the axes until disconnected.
Example usage::
ax = subplot(111)
ax.plot(x,y)
def onselect(verts):
print(verts)
lasso = LassoSelector(ax, onselect)
Parameters
----------
ax : :class:`~matplotlib.axes.Axes`
The parent axes for the widget.
onselect : function
Whenever the lasso is released, the *onselect* function is called and
passed the vertices of the selected path.
button : List[Int], optional
A list of integers indicating which mouse buttons should be used for
rectangle selection. You can also specify a single integer if only a
single button is desired. Default is ``None``, which does not limit
which button can be used.
Note, typically:
- 1 = left mouse button
- 2 = center mouse button (scroll wheel)
- 3 = right mouse button
"""
def __init__(self, ax, onselect=None, useblit=True, lineprops=None,
button=None):
_SelectorWidget.__init__(self, ax, onselect, useblit=useblit,
button=button)
self.verts = None
if lineprops is None:
lineprops = dict()
if useblit:
lineprops['animated'] = True
self.line = Line2D([], [], **lineprops)
self.line.set_visible(False)
self.ax.add_line(self.line)
self.artists = [self.line]
def onpress(self, event):
self.press(event)
def _press(self, event):
self.verts = [self._get_data(event)]
self.line.set_visible(True)
def onrelease(self, event):
self.release(event)
def _release(self, event):
if self.verts is not None:
self.verts.append(self._get_data(event))
self.onselect(self.verts)
self.line.set_data([[], []])
self.line.set_visible(False)
self.verts = None
def _onmove(self, event):
if self.verts is None:
return
self.verts.append(self._get_data(event))
self.line.set_data(list(zip(*self.verts)))
self.update()
class PolygonSelector(_SelectorWidget):
"""Select a polygon region of an axes.
Place vertices with each mouse click, and make the selection by completing
the polygon (clicking on the first vertex). Hold the *ctrl* key and click
and drag a vertex to reposition it (the *ctrl* key is not necessary if the
polygon has already been completed). Hold the *shift* key and click and
drag anywhere in the axes to move all vertices. Press the *esc* key to
start a new polygon.
For the selector to remain responsive you must keep a reference to
it.
Parameters
----------
ax : :class:`~matplotlib.axes.Axes`
The parent axes for the widget.
onselect : function
When a polygon is completed or modified after completion,
the `onselect` function is called and passed a list of the vertices as
``(xdata, ydata)`` tuples.
useblit : bool, optional
lineprops : dict, optional
The line for the sides of the polygon is drawn with the properties
given by `lineprops`. The default is ``dict(color='k', linestyle='-',
linewidth=2, alpha=0.5)``.
markerprops : dict, optional
The markers for the vertices of the polygon are drawn with the
properties given by `markerprops`. The default is ``dict(marker='o',
markersize=7, mec='k', mfc='k', alpha=0.5)``.
vertex_select_radius : float, optional
A vertex is selected (to complete the polygon or to move a vertex)
if the mouse click is within `vertex_select_radius` pixels of the
vertex. The default radius is 15 pixels.
Examples
--------
:doc:`/gallery/widgets/polygon_selector_demo`
"""
def __init__(self, ax, onselect, useblit=False,
lineprops=None, markerprops=None, vertex_select_radius=15):
# The state modifiers 'move', 'square', and 'center' are expected by
# _SelectorWidget but are not supported by PolygonSelector
# Note: could not use the existing 'move' state modifier in-place of
# 'move_all' because _SelectorWidget automatically discards 'move'
# from the state on button release.
state_modifier_keys = dict(clear='escape', move_vertex='control',
move_all='shift', move='not-applicable',
square='not-applicable',
center='not-applicable')
_SelectorWidget.__init__(self, ax, onselect, useblit=useblit,
state_modifier_keys=state_modifier_keys)
self._xs, self._ys = [0], [0]
self._polygon_completed = False
if lineprops is None:
lineprops = dict(color='k', linestyle='-', linewidth=2, alpha=0.5)
lineprops['animated'] = self.useblit
self.line = Line2D(self._xs, self._ys, **lineprops)
self.ax.add_line(self.line)
if markerprops is None:
markerprops = dict(mec='k', mfc=lineprops.get('color', 'k'))
self._polygon_handles = ToolHandles(self.ax, self._xs, self._ys,
useblit=self.useblit,
marker_props=markerprops)
self._active_handle_idx = -1
self.vertex_select_radius = vertex_select_radius
self.artists = [self.line, self._polygon_handles.artist]
self.set_visible(True)
def _press(self, event):
"""Button press event handler"""
# Check for selection of a tool handle.
if ((self._polygon_completed or 'move_vertex' in self.state)
and len(self._xs) > 0):
h_idx, h_dist = self._polygon_handles.closest(event.x, event.y)
if h_dist < self.vertex_select_radius:
self._active_handle_idx = h_idx
# Save the vertex positions at the time of the press event (needed to
# support the 'move_all' state modifier).
self._xs_at_press, self._ys_at_press = self._xs[:], self._ys[:]
def _release(self, event):
"""Button release event handler"""
# Release active tool handle.
if self._active_handle_idx >= 0:
self._active_handle_idx = -1
# Complete the polygon.
elif (len(self._xs) > 3
and self._xs[-1] == self._xs[0]
and self._ys[-1] == self._ys[0]):
self._polygon_completed = True
# Place new vertex.
elif (not self._polygon_completed
and 'move_all' not in self.state
and 'move_vertex' not in self.state):
self._xs.insert(-1, event.xdata)
self._ys.insert(-1, event.ydata)
if self._polygon_completed:
self.onselect(self.verts)
def onmove(self, event):
"""Cursor move event handler and validator"""
# Method overrides _SelectorWidget.onmove because the polygon selector
# needs to process the move callback even if there is no button press.
# _SelectorWidget.onmove include logic to ignore move event if
# eventpress is None.
if not self.ignore(event):
event = self._clean_event(event)
self._onmove(event)
return True
return False
def _onmove(self, event):
"""Cursor move event handler"""
# Move the active vertex (ToolHandle).
if self._active_handle_idx >= 0:
idx = self._active_handle_idx
self._xs[idx], self._ys[idx] = event.xdata, event.ydata
# Also update the end of the polygon line if the first vertex is
# the active handle and the polygon is completed.
if idx == 0 and self._polygon_completed:
self._xs[-1], self._ys[-1] = event.xdata, event.ydata
# Move all vertices.
elif 'move_all' in self.state and self.eventpress:
dx = event.xdata - self.eventpress.xdata
dy = event.ydata - self.eventpress.ydata
for k in range(len(self._xs)):
self._xs[k] = self._xs_at_press[k] + dx
self._ys[k] = self._ys_at_press[k] + dy
# Do nothing if completed or waiting for a move.
elif (self._polygon_completed
or 'move_vertex' in self.state or 'move_all' in self.state):
return
# Position pending vertex.
else:
# Calculate distance to the start vertex.
x0, y0 = self.line.get_transform().transform((self._xs[0],
self._ys[0]))
v0_dist = np.hypot(x0 - event.x, y0 - event.y)
# Lock on to the start vertex if near it and ready to complete.
if len(self._xs) > 3 and v0_dist < self.vertex_select_radius:
self._xs[-1], self._ys[-1] = self._xs[0], self._ys[0]
else:
self._xs[-1], self._ys[-1] = event.xdata, event.ydata
self._draw_polygon()
def _on_key_press(self, event):
"""Key press event handler"""
# Remove the pending vertex if entering the 'move_vertex' or
# 'move_all' mode
if (not self._polygon_completed
and ('move_vertex' in self.state or 'move_all' in self.state)):
self._xs, self._ys = self._xs[:-1], self._ys[:-1]
self._draw_polygon()
def _on_key_release(self, event):
"""Key release event handler"""
# Add back the pending vertex if leaving the 'move_vertex' or
# 'move_all' mode (by checking the released key)
if (not self._polygon_completed
and
(event.key == self.state_modifier_keys.get('move_vertex')
or event.key == self.state_modifier_keys.get('move_all'))):
self._xs.append(event.xdata)
self._ys.append(event.ydata)
self._draw_polygon()
# Reset the polygon if the released key is the 'clear' key.
elif event.key == self.state_modifier_keys.get('clear'):
event = self._clean_event(event)
self._xs, self._ys = [event.xdata], [event.ydata]
self._polygon_completed = False
self.set_visible(True)
def _draw_polygon(self):
"""Redraw the polygon based on the new vertex positions."""
self.line.set_data(self._xs, self._ys)
# Only show one tool handle at the start and end vertex of the polygon
# if the polygon is completed or the user is locked on to the start
# vertex.
if (self._polygon_completed
or (len(self._xs) > 3
and self._xs[-1] == self._xs[0]
and self._ys[-1] == self._ys[0])):
self._polygon_handles.set_data(self._xs[:-1], self._ys[:-1])
else:
self._polygon_handles.set_data(self._xs, self._ys)
self.update()
@property
def verts(self):
"""Get the polygon vertices.
Returns
-------
list
A list of the vertices of the polygon as ``(xdata, ydata)`` tuples.
"""
return list(zip(self._xs[:-1], self._ys[:-1]))
class Lasso(AxesWidget):
"""Selection curve of an arbitrary shape.
The selected path can be used in conjunction with
:func:`~matplotlib.path.Path.contains_point` to select data points
from an image.
Unlike :class:`LassoSelector`, this must be initialized with a starting
point `xy`, and the `Lasso` events are destroyed upon release.
Parameters
----------
ax : `~matplotlib.axes.Axes`
The parent axes for the widget.
xy : (float, float)
Coordinates of the start of the lasso.
callback : callable
Whenever the lasso is released, the `callback` function is called and
passed the vertices of the selected path.
"""
def __init__(self, ax, xy, callback=None, useblit=True):
AxesWidget.__init__(self, ax)
self.useblit = useblit and self.canvas.supports_blit
if self.useblit:
self.background = self.canvas.copy_from_bbox(self.ax.bbox)
x, y = xy
self.verts = [(x, y)]
self.line = Line2D([x], [y], linestyle='-', color='black', lw=2)
self.ax.add_line(self.line)
self.callback = callback
self.connect_event('button_release_event', self.onrelease)
self.connect_event('motion_notify_event', self.onmove)
def onrelease(self, event):
if self.ignore(event):
return
if self.verts is not None:
self.verts.append((event.xdata, event.ydata))
if len(self.verts) > 2:
self.callback(self.verts)
self.ax.lines.remove(self.line)
self.verts = None
self.disconnect_events()
def onmove(self, event):
if self.ignore(event):
return
if self.verts is None:
return
if event.inaxes != self.ax:
return
if event.button != 1:
return
self.verts.append((event.xdata, event.ydata))
self.line.set_data(list(zip(*self.verts)))
if self.useblit:
self.canvas.restore_region(self.background)
self.ax.draw_artist(self.line)
self.canvas.blit(self.ax.bbox)
else:
self.canvas.draw_idle()
|
18034b47cb7c2cd357b82a64e8a81bfeec6273a417d9f4f3800e66a51bd97a30
|
"""
Abstract base classes define the primitives for Tools.
These tools are used by `matplotlib.backend_managers.ToolManager`
:class:`ToolBase`
Simple stateless tool
:class:`ToolToggleBase`
Tool that has two states, only one Toggle tool can be
active at any given time for the same
`matplotlib.backend_managers.ToolManager`
"""
from enum import IntEnum
import logging
import re
import time
from types import SimpleNamespace
from weakref import WeakKeyDictionary
import numpy as np
from matplotlib import rcParams
from matplotlib._pylab_helpers import Gcf
import matplotlib.cbook as cbook
_log = logging.getLogger(__name__)
class Cursors(IntEnum): # Must subclass int for the macOS backend.
"""Backend-independent cursor types."""
HAND, POINTER, SELECT_REGION, MOVE, WAIT = range(5)
cursors = Cursors # Backcompat.
# Views positions tool
_views_positions = 'viewpos'
class ToolBase(object):
"""
Base tool class
A base tool, only implements `trigger` method or not method at all.
The tool is instantiated by `matplotlib.backend_managers.ToolManager`
Attributes
----------
toolmanager : `matplotlib.backend_managers.ToolManager`
ToolManager that controls this Tool
figure : `FigureCanvas`
Figure instance that is affected by this Tool
name : string
Used as **Id** of the tool, has to be unique among tools of the same
ToolManager
"""
default_keymap = None
"""
Keymap to associate with this tool
**String**: List of comma separated keys that will be used to call this
tool when the keypress event of *self.figure.canvas* is emitted
"""
description = None
"""
Description of the Tool
**String**: If the Tool is included in the Toolbar this text is used
as a Tooltip
"""
image = None
"""
Filename of the image
**String**: Filename of the image to use in the toolbar. If None, the
`name` is used as a label in the toolbar button
"""
def __init__(self, toolmanager, name):
cbook._warn_external(
'The new Tool classes introduced in v1.5 are experimental; their '
'API (including names) will likely change in future versions.')
self._name = name
self._toolmanager = toolmanager
self._figure = None
@property
def figure(self):
return self._figure
@figure.setter
def figure(self, figure):
self.set_figure(figure)
@property
def canvas(self):
if not self._figure:
return None
return self._figure.canvas
@property
def toolmanager(self):
return self._toolmanager
def _make_classic_style_pseudo_toolbar(self):
"""
Return a placeholder object with a single `canvas` attribute.
This is useful to reuse the implementations of tools already provided
by the classic Toolbars.
"""
return SimpleNamespace(canvas=self.canvas)
def set_figure(self, figure):
"""
Assign a figure to the tool
Parameters
----------
figure : `Figure`
"""
self._figure = figure
def trigger(self, sender, event, data=None):
"""
Called when this tool gets used
This method is called by
`matplotlib.backend_managers.ToolManager.trigger_tool`
Parameters
----------
event : `Event`
The Canvas event that caused this tool to be called
sender : object
Object that requested the tool to be triggered
data : object
Extra data
"""
pass
@property
def name(self):
"""Tool Id"""
return self._name
def destroy(self):
"""
Destroy the tool
This method is called when the tool is removed by
`matplotlib.backend_managers.ToolManager.remove_tool`
"""
pass
class ToolToggleBase(ToolBase):
"""
Toggleable tool
Every time it is triggered, it switches between enable and disable
Parameters
----------
``*args``
Variable length argument to be used by the Tool
``**kwargs``
`toggled` if present and True, sets the initial state of the Tool
Arbitrary keyword arguments to be consumed by the Tool
"""
radio_group = None
"""Attribute to group 'radio' like tools (mutually exclusive)
**String** that identifies the group or **None** if not belonging to a
group
"""
cursor = None
"""Cursor to use when the tool is active"""
default_toggled = False
"""Default of toggled state"""
def __init__(self, *args, **kwargs):
self._toggled = kwargs.pop('toggled', self.default_toggled)
ToolBase.__init__(self, *args, **kwargs)
def trigger(self, sender, event, data=None):
"""Calls `enable` or `disable` based on `toggled` value"""
if self._toggled:
self.disable(event)
else:
self.enable(event)
self._toggled = not self._toggled
def enable(self, event=None):
"""
Enable the toggle tool
`trigger` calls this method when `toggled` is False
"""
pass
def disable(self, event=None):
"""
Disable the toggle tool
`trigger` call this method when `toggled` is True.
This can happen in different circumstances
* Click on the toolbar tool button
* Call to `matplotlib.backend_managers.ToolManager.trigger_tool`
* Another `ToolToggleBase` derived tool is triggered
(from the same `ToolManager`)
"""
pass
@property
def toggled(self):
"""State of the toggled tool"""
return self._toggled
def set_figure(self, figure):
toggled = self.toggled
if toggled:
if self.figure:
self.trigger(self, None)
else:
# if no figure the internal state is not changed
# we change it here so next call to trigger will change it back
self._toggled = False
ToolBase.set_figure(self, figure)
if toggled:
if figure:
self.trigger(self, None)
else:
# if there is no figure, trigger won't change the internal
# state we change it back
self._toggled = True
class SetCursorBase(ToolBase):
"""
Change to the current cursor while inaxes
This tool, keeps track of all `ToolToggleBase` derived tools, and calls
set_cursor when a tool gets triggered
"""
def __init__(self, *args, **kwargs):
ToolBase.__init__(self, *args, **kwargs)
self._idDrag = None
self._cursor = None
self._default_cursor = cursors.POINTER
self._last_cursor = self._default_cursor
self.toolmanager.toolmanager_connect('tool_added_event',
self._add_tool_cbk)
# process current tools
for tool in self.toolmanager.tools.values():
self._add_tool(tool)
def set_figure(self, figure):
if self._idDrag:
self.canvas.mpl_disconnect(self._idDrag)
ToolBase.set_figure(self, figure)
if figure:
self._idDrag = self.canvas.mpl_connect(
'motion_notify_event', self._set_cursor_cbk)
def _tool_trigger_cbk(self, event):
if event.tool.toggled:
self._cursor = event.tool.cursor
else:
self._cursor = None
self._set_cursor_cbk(event.canvasevent)
def _add_tool(self, tool):
"""Set the cursor when the tool is triggered."""
if getattr(tool, 'cursor', None) is not None:
self.toolmanager.toolmanager_connect('tool_trigger_%s' % tool.name,
self._tool_trigger_cbk)
def _add_tool_cbk(self, event):
"""Process every newly added tool."""
if event.tool is self:
return
self._add_tool(event.tool)
def _set_cursor_cbk(self, event):
if not event:
return
if not getattr(event, 'inaxes', False) or not self._cursor:
if self._last_cursor != self._default_cursor:
self.set_cursor(self._default_cursor)
self._last_cursor = self._default_cursor
elif self._cursor:
cursor = self._cursor
if cursor and self._last_cursor != cursor:
self.set_cursor(cursor)
self._last_cursor = cursor
def set_cursor(self, cursor):
"""
Set the cursor
This method has to be implemented per backend
"""
raise NotImplementedError
class ToolCursorPosition(ToolBase):
"""
Send message with the current pointer position
This tool runs in the background reporting the position of the cursor
"""
def __init__(self, *args, **kwargs):
self._idDrag = None
ToolBase.__init__(self, *args, **kwargs)
def set_figure(self, figure):
if self._idDrag:
self.canvas.mpl_disconnect(self._idDrag)
ToolBase.set_figure(self, figure)
if figure:
self._idDrag = self.canvas.mpl_connect(
'motion_notify_event', self.send_message)
def send_message(self, event):
"""Call `matplotlib.backend_managers.ToolManager.message_event`"""
if self.toolmanager.messagelock.locked():
return
message = ' '
if event.inaxes and event.inaxes.get_navigate():
try:
s = event.inaxes.format_coord(event.xdata, event.ydata)
except (ValueError, OverflowError):
pass
else:
artists = [a for a in event.inaxes._mouseover_set
if a.contains(event) and a.get_visible()]
if artists:
a = cbook._topmost_artist(artists)
if a is not event.inaxes.patch:
data = a.get_cursor_data(event)
if data is not None:
data_str = a.format_cursor_data(data)
if data_str is not None:
s = s + ' ' + data_str
message = s
self.toolmanager.message_event(message, self)
class RubberbandBase(ToolBase):
"""Draw and remove rubberband"""
def trigger(self, sender, event, data):
"""Call `draw_rubberband` or `remove_rubberband` based on data"""
if not self.figure.canvas.widgetlock.available(sender):
return
if data is not None:
self.draw_rubberband(*data)
else:
self.remove_rubberband()
def draw_rubberband(self, *data):
"""
Draw rubberband
This method must get implemented per backend
"""
raise NotImplementedError
def remove_rubberband(self):
"""
Remove rubberband
This method should get implemented per backend
"""
pass
class ToolQuit(ToolBase):
"""Tool to call the figure manager destroy method"""
description = 'Quit the figure'
default_keymap = rcParams['keymap.quit']
def trigger(self, sender, event, data=None):
Gcf.destroy_fig(self.figure)
class ToolQuitAll(ToolBase):
"""Tool to call the figure manager destroy method"""
description = 'Quit all figures'
default_keymap = rcParams['keymap.quit_all']
def trigger(self, sender, event, data=None):
Gcf.destroy_all()
class ToolEnableAllNavigation(ToolBase):
"""Tool to enable all axes for toolmanager interaction"""
description = 'Enable all axes toolmanager'
default_keymap = rcParams['keymap.all_axes']
def trigger(self, sender, event, data=None):
if event.inaxes is None:
return
for a in self.figure.get_axes():
if (event.x is not None and event.y is not None
and a.in_axes(event)):
a.set_navigate(True)
class ToolEnableNavigation(ToolBase):
"""Tool to enable a specific axes for toolmanager interaction"""
description = 'Enable one axes toolmanager'
default_keymap = (1, 2, 3, 4, 5, 6, 7, 8, 9)
def trigger(self, sender, event, data=None):
if event.inaxes is None:
return
n = int(event.key) - 1
if n < len(self.figure.get_axes()):
for i, a in enumerate(self.figure.get_axes()):
if (event.x is not None and event.y is not None
and a.in_axes(event)):
a.set_navigate(i == n)
class _ToolGridBase(ToolBase):
"""Common functionality between ToolGrid and ToolMinorGrid."""
_cycle = [(False, False), (True, False), (True, True), (False, True)]
def trigger(self, sender, event, data=None):
ax = event.inaxes
if ax is None:
return
try:
x_state, x_which, y_state, y_which = self._get_next_grid_states(ax)
except ValueError:
pass
else:
ax.grid(x_state, which=x_which, axis="x")
ax.grid(y_state, which=y_which, axis="y")
ax.figure.canvas.draw_idle()
@staticmethod
def _get_uniform_grid_state(ticks):
"""
Check whether all grid lines are in the same visibility state.
Returns True/False if all grid lines are on or off, None if they are
not all in the same state.
"""
if all(tick.gridline.get_visible() for tick in ticks):
return True
elif not any(tick.gridline.get_visible() for tick in ticks):
return False
else:
return None
class ToolGrid(_ToolGridBase):
"""Tool to toggle the major grids of the figure"""
description = 'Toggle major grids'
default_keymap = rcParams['keymap.grid']
def _get_next_grid_states(self, ax):
if None in map(self._get_uniform_grid_state,
[ax.xaxis.minorTicks, ax.yaxis.minorTicks]):
# Bail out if minor grids are not in a uniform state.
raise ValueError
x_state, y_state = map(self._get_uniform_grid_state,
[ax.xaxis.majorTicks, ax.yaxis.majorTicks])
cycle = self._cycle
# Bail out (via ValueError) if major grids are not in a uniform state.
x_state, y_state = (
cycle[(cycle.index((x_state, y_state)) + 1) % len(cycle)])
return (x_state, "major" if x_state else "both",
y_state, "major" if y_state else "both")
class ToolMinorGrid(_ToolGridBase):
"""Tool to toggle the major and minor grids of the figure"""
description = 'Toggle major and minor grids'
default_keymap = rcParams['keymap.grid_minor']
def _get_next_grid_states(self, ax):
if None in map(self._get_uniform_grid_state,
[ax.xaxis.majorTicks, ax.yaxis.majorTicks]):
# Bail out if major grids are not in a uniform state.
raise ValueError
x_state, y_state = map(self._get_uniform_grid_state,
[ax.xaxis.minorTicks, ax.yaxis.minorTicks])
cycle = self._cycle
# Bail out (via ValueError) if minor grids are not in a uniform state.
x_state, y_state = (
cycle[(cycle.index((x_state, y_state)) + 1) % len(cycle)])
return x_state, "both", y_state, "both"
class ToolFullScreen(ToolToggleBase):
"""Tool to toggle full screen"""
description = 'Toggle fullscreen mode'
default_keymap = rcParams['keymap.fullscreen']
def enable(self, event):
self.figure.canvas.manager.full_screen_toggle()
def disable(self, event):
self.figure.canvas.manager.full_screen_toggle()
class AxisScaleBase(ToolToggleBase):
"""Base Tool to toggle between linear and logarithmic"""
def trigger(self, sender, event, data=None):
if event.inaxes is None:
return
ToolToggleBase.trigger(self, sender, event, data)
def enable(self, event):
self.set_scale(event.inaxes, 'log')
self.figure.canvas.draw_idle()
def disable(self, event):
self.set_scale(event.inaxes, 'linear')
self.figure.canvas.draw_idle()
class ToolYScale(AxisScaleBase):
"""Tool to toggle between linear and logarithmic scales on the Y axis"""
description = 'Toggle scale Y axis'
default_keymap = rcParams['keymap.yscale']
def set_scale(self, ax, scale):
ax.set_yscale(scale)
class ToolXScale(AxisScaleBase):
"""Tool to toggle between linear and logarithmic scales on the X axis"""
description = 'Toggle scale X axis'
default_keymap = rcParams['keymap.xscale']
def set_scale(self, ax, scale):
ax.set_xscale(scale)
class ToolViewsPositions(ToolBase):
"""
Auxiliary Tool to handle changes in views and positions
Runs in the background and should get used by all the tools that
need to access the figure's history of views and positions, e.g.
* `ToolZoom`
* `ToolPan`
* `ToolHome`
* `ToolBack`
* `ToolForward`
"""
def __init__(self, *args, **kwargs):
self.views = WeakKeyDictionary()
self.positions = WeakKeyDictionary()
self.home_views = WeakKeyDictionary()
ToolBase.__init__(self, *args, **kwargs)
def add_figure(self, figure):
"""Add the current figure to the stack of views and positions"""
if figure not in self.views:
self.views[figure] = cbook.Stack()
self.positions[figure] = cbook.Stack()
self.home_views[figure] = WeakKeyDictionary()
# Define Home
self.push_current(figure)
# Make sure we add a home view for new axes as they're added
figure.add_axobserver(lambda fig: self.update_home_views(fig))
def clear(self, figure):
"""Reset the axes stack"""
if figure in self.views:
self.views[figure].clear()
self.positions[figure].clear()
self.home_views[figure].clear()
self.update_home_views()
def update_view(self):
"""
Update the view limits and position for each axes from the current
stack position. If any axes are present in the figure that aren't in
the current stack position, use the home view limits for those axes and
don't update *any* positions.
"""
views = self.views[self.figure]()
if views is None:
return
pos = self.positions[self.figure]()
if pos is None:
return
home_views = self.home_views[self.figure]
all_axes = self.figure.get_axes()
for a in all_axes:
if a in views:
cur_view = views[a]
else:
cur_view = home_views[a]
a._set_view(cur_view)
if set(all_axes).issubset(pos):
for a in all_axes:
# Restore both the original and modified positions
a._set_position(pos[a][0], 'original')
a._set_position(pos[a][1], 'active')
self.figure.canvas.draw_idle()
def push_current(self, figure=None):
"""
Push the current view limits and position onto their respective stacks
"""
if not figure:
figure = self.figure
views = WeakKeyDictionary()
pos = WeakKeyDictionary()
for a in figure.get_axes():
views[a] = a._get_view()
pos[a] = self._axes_pos(a)
self.views[figure].push(views)
self.positions[figure].push(pos)
def _axes_pos(self, ax):
"""
Return the original and modified positions for the specified axes
Parameters
----------
ax : (matplotlib.axes.AxesSubplot)
The axes to get the positions for
Returns
-------
limits : (tuple)
A tuple of the original and modified positions
"""
return (ax.get_position(True).frozen(),
ax.get_position().frozen())
def update_home_views(self, figure=None):
"""
Make sure that self.home_views has an entry for all axes present in the
figure
"""
if not figure:
figure = self.figure
for a in figure.get_axes():
if a not in self.home_views[figure]:
self.home_views[figure][a] = a._get_view()
def refresh_locators(self):
"""Redraw the canvases, update the locators"""
for a in self.figure.get_axes():
xaxis = getattr(a, 'xaxis', None)
yaxis = getattr(a, 'yaxis', None)
zaxis = getattr(a, 'zaxis', None)
locators = []
if xaxis is not None:
locators.append(xaxis.get_major_locator())
locators.append(xaxis.get_minor_locator())
if yaxis is not None:
locators.append(yaxis.get_major_locator())
locators.append(yaxis.get_minor_locator())
if zaxis is not None:
locators.append(zaxis.get_major_locator())
locators.append(zaxis.get_minor_locator())
for loc in locators:
loc.refresh()
self.figure.canvas.draw_idle()
def home(self):
"""Recall the first view and position from the stack"""
self.views[self.figure].home()
self.positions[self.figure].home()
def back(self):
"""Back one step in the stack of views and positions"""
self.views[self.figure].back()
self.positions[self.figure].back()
def forward(self):
"""Forward one step in the stack of views and positions"""
self.views[self.figure].forward()
self.positions[self.figure].forward()
class ViewsPositionsBase(ToolBase):
"""Base class for `ToolHome`, `ToolBack` and `ToolForward`"""
_on_trigger = None
def trigger(self, sender, event, data=None):
self.toolmanager.get_tool(_views_positions).add_figure(self.figure)
getattr(self.toolmanager.get_tool(_views_positions),
self._on_trigger)()
self.toolmanager.get_tool(_views_positions).update_view()
class ToolHome(ViewsPositionsBase):
"""Restore the original view lim"""
description = 'Reset original view'
image = 'home'
default_keymap = rcParams['keymap.home']
_on_trigger = 'home'
class ToolBack(ViewsPositionsBase):
"""Move back up the view lim stack"""
description = 'Back to previous view'
image = 'back'
default_keymap = rcParams['keymap.back']
_on_trigger = 'back'
class ToolForward(ViewsPositionsBase):
"""Move forward in the view lim stack"""
description = 'Forward to next view'
image = 'forward'
default_keymap = rcParams['keymap.forward']
_on_trigger = 'forward'
class ConfigureSubplotsBase(ToolBase):
"""Base tool for the configuration of subplots"""
description = 'Configure subplots'
image = 'subplots'
class SaveFigureBase(ToolBase):
"""Base tool for figure saving"""
description = 'Save the figure'
image = 'filesave'
default_keymap = rcParams['keymap.save']
class ZoomPanBase(ToolToggleBase):
"""Base class for `ToolZoom` and `ToolPan`"""
def __init__(self, *args):
ToolToggleBase.__init__(self, *args)
self._button_pressed = None
self._xypress = None
self._idPress = None
self._idRelease = None
self._idScroll = None
self.base_scale = 2.
self.scrollthresh = .5 # .5 second scroll threshold
self.lastscroll = time.time()-self.scrollthresh
def enable(self, event):
"""Connect press/release events and lock the canvas"""
self.figure.canvas.widgetlock(self)
self._idPress = self.figure.canvas.mpl_connect(
'button_press_event', self._press)
self._idRelease = self.figure.canvas.mpl_connect(
'button_release_event', self._release)
self._idScroll = self.figure.canvas.mpl_connect(
'scroll_event', self.scroll_zoom)
def disable(self, event):
"""Release the canvas and disconnect press/release events"""
self._cancel_action()
self.figure.canvas.widgetlock.release(self)
self.figure.canvas.mpl_disconnect(self._idPress)
self.figure.canvas.mpl_disconnect(self._idRelease)
self.figure.canvas.mpl_disconnect(self._idScroll)
def trigger(self, sender, event, data=None):
self.toolmanager.get_tool(_views_positions).add_figure(self.figure)
ToolToggleBase.trigger(self, sender, event, data)
def scroll_zoom(self, event):
# https://gist.github.com/tacaswell/3144287
if event.inaxes is None:
return
if event.button == 'up':
# deal with zoom in
scl = self.base_scale
elif event.button == 'down':
# deal with zoom out
scl = 1/self.base_scale
else:
# deal with something that should never happen
scl = 1
ax = event.inaxes
ax._set_view_from_bbox([event.x, event.y, scl])
# If last scroll was done within the timing threshold, delete the
# previous view
if (time.time()-self.lastscroll) < self.scrollthresh:
self.toolmanager.get_tool(_views_positions).back()
self.figure.canvas.draw_idle() # force re-draw
self.lastscroll = time.time()
self.toolmanager.get_tool(_views_positions).push_current()
class ToolZoom(ZoomPanBase):
"""Zoom to rectangle"""
description = 'Zoom to rectangle'
image = 'zoom_to_rect'
default_keymap = rcParams['keymap.zoom']
cursor = cursors.SELECT_REGION
radio_group = 'default'
def __init__(self, *args):
ZoomPanBase.__init__(self, *args)
self._ids_zoom = []
def _cancel_action(self):
for zoom_id in self._ids_zoom:
self.figure.canvas.mpl_disconnect(zoom_id)
self.toolmanager.trigger_tool('rubberband', self)
self.toolmanager.get_tool(_views_positions).refresh_locators()
self._xypress = None
self._button_pressed = None
self._ids_zoom = []
return
def _press(self, event):
"""Callback for mouse button presses in zoom-to-rectangle mode."""
# If we're already in the middle of a zoom, pressing another
# button works to "cancel"
if self._ids_zoom != []:
self._cancel_action()
if event.button == 1:
self._button_pressed = 1
elif event.button == 3:
self._button_pressed = 3
else:
self._cancel_action()
return
x, y = event.x, event.y
self._xypress = []
for i, a in enumerate(self.figure.get_axes()):
if (x is not None and y is not None and a.in_axes(event) and
a.get_navigate() and a.can_zoom()):
self._xypress.append((x, y, a, i, a._get_view()))
id1 = self.figure.canvas.mpl_connect(
'motion_notify_event', self._mouse_move)
id2 = self.figure.canvas.mpl_connect(
'key_press_event', self._switch_on_zoom_mode)
id3 = self.figure.canvas.mpl_connect(
'key_release_event', self._switch_off_zoom_mode)
self._ids_zoom = id1, id2, id3
self._zoom_mode = event.key
def _switch_on_zoom_mode(self, event):
self._zoom_mode = event.key
self._mouse_move(event)
def _switch_off_zoom_mode(self, event):
self._zoom_mode = None
self._mouse_move(event)
def _mouse_move(self, event):
"""Callback for mouse moves in zoom-to-rectangle mode."""
if self._xypress:
x, y = event.x, event.y
lastx, lasty, a, ind, view = self._xypress[0]
(x1, y1), (x2, y2) = np.clip(
[[lastx, lasty], [x, y]], a.bbox.min, a.bbox.max)
if self._zoom_mode == "x":
y1, y2 = a.bbox.intervaly
elif self._zoom_mode == "y":
x1, x2 = a.bbox.intervalx
self.toolmanager.trigger_tool(
'rubberband', self, data=(x1, y1, x2, y2))
def _release(self, event):
"""Callback for mouse button releases in zoom-to-rectangle mode."""
for zoom_id in self._ids_zoom:
self.figure.canvas.mpl_disconnect(zoom_id)
self._ids_zoom = []
if not self._xypress:
self._cancel_action()
return
last_a = []
for cur_xypress in self._xypress:
x, y = event.x, event.y
lastx, lasty, a, _ind, view = cur_xypress
# ignore singular clicks - 5 pixels is a threshold
if abs(x - lastx) < 5 or abs(y - lasty) < 5:
self._cancel_action()
return
# detect twinx,y axes and avoid double zooming
twinx, twiny = False, False
if last_a:
for la in last_a:
if a.get_shared_x_axes().joined(a, la):
twinx = True
if a.get_shared_y_axes().joined(a, la):
twiny = True
last_a.append(a)
if self._button_pressed == 1:
direction = 'in'
elif self._button_pressed == 3:
direction = 'out'
else:
continue
a._set_view_from_bbox((lastx, lasty, x, y), direction,
self._zoom_mode, twinx, twiny)
self._zoom_mode = None
self.toolmanager.get_tool(_views_positions).push_current()
self._cancel_action()
class ToolPan(ZoomPanBase):
"""Pan axes with left mouse, zoom with right"""
default_keymap = rcParams['keymap.pan']
description = 'Pan axes with left mouse, zoom with right'
image = 'move'
cursor = cursors.MOVE
radio_group = 'default'
def __init__(self, *args):
ZoomPanBase.__init__(self, *args)
self._idDrag = None
def _cancel_action(self):
self._button_pressed = None
self._xypress = []
self.figure.canvas.mpl_disconnect(self._idDrag)
self.toolmanager.messagelock.release(self)
self.toolmanager.get_tool(_views_positions).refresh_locators()
def _press(self, event):
if event.button == 1:
self._button_pressed = 1
elif event.button == 3:
self._button_pressed = 3
else:
self._cancel_action()
return
x, y = event.x, event.y
self._xypress = []
for i, a in enumerate(self.figure.get_axes()):
if (x is not None and y is not None and a.in_axes(event) and
a.get_navigate() and a.can_pan()):
a.start_pan(x, y, event.button)
self._xypress.append((a, i))
self.toolmanager.messagelock(self)
self._idDrag = self.figure.canvas.mpl_connect(
'motion_notify_event', self._mouse_move)
def _release(self, event):
if self._button_pressed is None:
self._cancel_action()
return
self.figure.canvas.mpl_disconnect(self._idDrag)
self.toolmanager.messagelock.release(self)
for a, _ind in self._xypress:
a.end_pan()
if not self._xypress:
self._cancel_action()
return
self.toolmanager.get_tool(_views_positions).push_current()
self._cancel_action()
def _mouse_move(self, event):
for a, _ind in self._xypress:
# safer to use the recorded button at the _press than current
# button: # multiple button can get pressed during motion...
a.drag_pan(self._button_pressed, event.key, event.x, event.y)
self.toolmanager.canvas.draw_idle()
class ToolHelpBase(ToolBase):
description = 'Print tool list, shortcuts and description'
default_keymap = rcParams['keymap.help']
image = 'help.png'
@staticmethod
def format_shortcut(key_sequence):
"""
Converts a shortcut string from the notation used in rc config to the
standard notation for displaying shortcuts, e.g. 'ctrl+a' -> 'Ctrl+A'.
"""
return (key_sequence if len(key_sequence) == 1 else
re.sub(r"\+[A-Z]", r"+Shift\g<0>", key_sequence).title())
def _format_tool_keymap(self, name):
keymaps = self.toolmanager.get_tool_keymap(name)
return ", ".join(self.format_shortcut(keymap) for keymap in keymaps)
def _get_help_entries(self):
entries = []
for name, tool in sorted(self.toolmanager.tools.items()):
if not tool.description:
continue
entries.append((name, self._format_tool_keymap(name),
tool.description))
return entries
def _get_help_text(self):
entries = self._get_help_entries()
entries = ["{}: {}\n\t{}".format(*entry) for entry in entries]
return "\n".join(entries)
def _get_help_html(self):
fmt = "<tr><td>{}</td><td>{}</td><td>{}</td></tr>"
rows = [fmt.format(
"<b>Action</b>", "<b>Shortcuts</b>", "<b>Description</b>")]
rows += [fmt.format(*row) for row in self._get_help_entries()]
return ("<style>td {padding: 0px 4px}</style>"
"<table><thead>" + rows[0] + "</thead>"
"<tbody>".join(rows[1:]) + "</tbody></table>")
class ToolCopyToClipboardBase(ToolBase):
"""Tool to copy the figure to the clipboard"""
description = 'Copy the canvas figure to clipboard'
default_keymap = rcParams['keymap.copy']
def trigger(self, *args, **kwargs):
message = "Copy tool is not available"
self.toolmanager.message_event(message, self)
default_tools = {'home': ToolHome, 'back': ToolBack, 'forward': ToolForward,
'zoom': ToolZoom, 'pan': ToolPan,
'subplots': 'ToolConfigureSubplots',
'save': 'ToolSaveFigure',
'grid': ToolGrid,
'grid_minor': ToolMinorGrid,
'fullscreen': ToolFullScreen,
'quit': ToolQuit,
'quit_all': ToolQuitAll,
'allnav': ToolEnableAllNavigation,
'nav': ToolEnableNavigation,
'xscale': ToolXScale,
'yscale': ToolYScale,
'position': ToolCursorPosition,
_views_positions: ToolViewsPositions,
'cursor': 'ToolSetCursor',
'rubberband': 'ToolRubberband',
'help': 'ToolHelp',
'copy': 'ToolCopyToClipboard',
}
"""Default tools"""
default_toolbar_tools = [['navigation', ['home', 'back', 'forward']],
['zoompan', ['pan', 'zoom', 'subplots']],
['io', ['save', 'help']]]
"""Default tools in the toolbar"""
def add_tools_to_manager(toolmanager, tools=default_tools):
"""
Add multiple tools to `ToolManager`
Parameters
----------
toolmanager : ToolManager
`backend_managers.ToolManager` object that will get the tools added
tools : {str: class_like}, optional
The tools to add in a {name: tool} dict, see `add_tool` for more
info.
"""
for name, tool in tools.items():
toolmanager.add_tool(name, tool)
def add_tools_to_container(container, tools=default_toolbar_tools):
"""
Add multiple tools to the container.
Parameters
----------
container : Container
`backend_bases.ToolContainerBase` object that will get the tools added
tools : list, optional
List in the form
[[group1, [tool1, tool2 ...]], [group2, [...]]]
Where the tools given by tool1, and tool2 will display in group1.
See `add_tool` for details.
"""
for group, grouptools in tools:
for position, tool in enumerate(grouptools):
container.add_tool(tool, group, position)
|
93d927d69dc29b34b1282d7b3f3b05531ff7181353a1d3f551f6ac2901c7fee0
|
"""
Contains a classes for generating hatch patterns.
"""
import numpy as np
from matplotlib.path import Path
class HatchPatternBase(object):
"""
The base class for a hatch pattern.
"""
pass
class HorizontalHatch(HatchPatternBase):
def __init__(self, hatch, density):
self.num_lines = int((hatch.count('-') + hatch.count('+')) * density)
self.num_vertices = self.num_lines * 2
def set_vertices_and_codes(self, vertices, codes):
steps, stepsize = np.linspace(0.0, 1.0, self.num_lines, False,
retstep=True)
steps += stepsize / 2.
vertices[0::2, 0] = 0.0
vertices[0::2, 1] = steps
vertices[1::2, 0] = 1.0
vertices[1::2, 1] = steps
codes[0::2] = Path.MOVETO
codes[1::2] = Path.LINETO
class VerticalHatch(HatchPatternBase):
def __init__(self, hatch, density):
self.num_lines = int((hatch.count('|') + hatch.count('+')) * density)
self.num_vertices = self.num_lines * 2
def set_vertices_and_codes(self, vertices, codes):
steps, stepsize = np.linspace(0.0, 1.0, self.num_lines, False,
retstep=True)
steps += stepsize / 2.
vertices[0::2, 0] = steps
vertices[0::2, 1] = 0.0
vertices[1::2, 0] = steps
vertices[1::2, 1] = 1.0
codes[0::2] = Path.MOVETO
codes[1::2] = Path.LINETO
class NorthEastHatch(HatchPatternBase):
def __init__(self, hatch, density):
self.num_lines = int((hatch.count('/') + hatch.count('x') +
hatch.count('X')) * density)
if self.num_lines:
self.num_vertices = (self.num_lines + 1) * 2
else:
self.num_vertices = 0
def set_vertices_and_codes(self, vertices, codes):
steps = np.linspace(-0.5, 0.5, self.num_lines + 1, True)
vertices[0::2, 0] = 0.0 + steps
vertices[0::2, 1] = 0.0 - steps
vertices[1::2, 0] = 1.0 + steps
vertices[1::2, 1] = 1.0 - steps
codes[0::2] = Path.MOVETO
codes[1::2] = Path.LINETO
class SouthEastHatch(HatchPatternBase):
def __init__(self, hatch, density):
self.num_lines = int((hatch.count('\\') + hatch.count('x') +
hatch.count('X')) * density)
self.num_vertices = (self.num_lines + 1) * 2
if self.num_lines:
self.num_vertices = (self.num_lines + 1) * 2
else:
self.num_vertices = 0
def set_vertices_and_codes(self, vertices, codes):
steps = np.linspace(-0.5, 0.5, self.num_lines + 1, True)
vertices[0::2, 0] = 0.0 + steps
vertices[0::2, 1] = 1.0 + steps
vertices[1::2, 0] = 1.0 + steps
vertices[1::2, 1] = 0.0 + steps
codes[0::2] = Path.MOVETO
codes[1::2] = Path.LINETO
class Shapes(HatchPatternBase):
filled = False
def __init__(self, hatch, density):
if self.num_rows == 0:
self.num_shapes = 0
self.num_vertices = 0
else:
self.num_shapes = ((self.num_rows // 2 + 1) * (self.num_rows + 1) +
(self.num_rows // 2) * (self.num_rows))
self.num_vertices = (self.num_shapes *
len(self.shape_vertices) *
(1 if self.filled else 2))
def set_vertices_and_codes(self, vertices, codes):
offset = 1.0 / self.num_rows
shape_vertices = self.shape_vertices * offset * self.size
if not self.filled:
inner_vertices = shape_vertices[::-1] * 0.9
shape_codes = self.shape_codes
shape_size = len(shape_vertices)
cursor = 0
for row in range(self.num_rows + 1):
if row % 2 == 0:
cols = np.linspace(0.0, 1.0, self.num_rows + 1, True)
else:
cols = np.linspace(offset / 2.0, 1.0 - offset / 2.0,
self.num_rows, True)
row_pos = row * offset
for col_pos in cols:
vertices[cursor:cursor + shape_size] = (shape_vertices +
(col_pos, row_pos))
codes[cursor:cursor + shape_size] = shape_codes
cursor += shape_size
if not self.filled:
vertices[cursor:cursor + shape_size] = (inner_vertices +
(col_pos, row_pos))
codes[cursor:cursor + shape_size] = shape_codes
cursor += shape_size
class Circles(Shapes):
def __init__(self, hatch, density):
path = Path.unit_circle()
self.shape_vertices = path.vertices
self.shape_codes = path.codes
Shapes.__init__(self, hatch, density)
class SmallCircles(Circles):
size = 0.2
def __init__(self, hatch, density):
self.num_rows = (hatch.count('o')) * density
Circles.__init__(self, hatch, density)
class LargeCircles(Circles):
size = 0.35
def __init__(self, hatch, density):
self.num_rows = (hatch.count('O')) * density
Circles.__init__(self, hatch, density)
class SmallFilledCircles(SmallCircles):
size = 0.1
filled = True
def __init__(self, hatch, density):
self.num_rows = (hatch.count('.')) * density
Circles.__init__(self, hatch, density)
class Stars(Shapes):
size = 1.0 / 3.0
filled = True
def __init__(self, hatch, density):
self.num_rows = (hatch.count('*')) * density
path = Path.unit_regular_star(5)
self.shape_vertices = path.vertices
self.shape_codes = np.full(len(self.shape_vertices), Path.LINETO,
dtype=Path.code_type)
self.shape_codes[0] = Path.MOVETO
Shapes.__init__(self, hatch, density)
_hatch_types = [
HorizontalHatch,
VerticalHatch,
NorthEastHatch,
SouthEastHatch,
SmallCircles,
LargeCircles,
SmallFilledCircles,
Stars
]
def get_path(hatchpattern, density=6):
"""
Given a hatch specifier, *hatchpattern*, generates Path to render
the hatch in a unit square. *density* is the number of lines per
unit square.
"""
density = int(density)
patterns = [hatch_type(hatchpattern, density)
for hatch_type in _hatch_types]
num_vertices = sum([pattern.num_vertices for pattern in patterns])
if num_vertices == 0:
return Path(np.empty((0, 2)))
vertices = np.empty((num_vertices, 2))
codes = np.empty(num_vertices, Path.code_type)
cursor = 0
for pattern in patterns:
if pattern.num_vertices != 0:
vertices_chunk = vertices[cursor:cursor + pattern.num_vertices]
codes_chunk = codes[cursor:cursor + pattern.num_vertices]
pattern.set_vertices_and_codes(vertices_chunk, codes_chunk)
cursor += pattern.num_vertices
return Path(vertices, codes)
|
af91bdca771fd05dbe2fc88d4076169d7005817ae43879ad68fb590dd6c61c59
|
"""
Numerical python functions written for compatibility with MATLAB
commands with the same names. Most numerical python functions can be found in
the `numpy` and `scipy` libraries. What remains here is code for performing
spectral computations.
Spectral functions
-------------------
`cohere`
Coherence (normalized cross spectral density)
`csd`
Cross spectral density using Welch's average periodogram
`detrend`
Remove the mean or best fit line from an array
`psd`
Power spectral density using Welch's average periodogram
`specgram`
Spectrogram (spectrum over segments of time)
`complex_spectrum`
Return the complex-valued frequency spectrum of a signal
`magnitude_spectrum`
Return the magnitude of the frequency spectrum of a signal
`angle_spectrum`
Return the angle (wrapped phase) of the frequency spectrum of a signal
`phase_spectrum`
Return the phase (unwrapped angle) of the frequency spectrum of a signal
`detrend_mean`
Remove the mean from a line.
`detrend_linear`
Remove the best fit line from a line.
`detrend_none`
Return the original line.
`stride_windows`
Get all windows in an array in a memory-efficient manner
`stride_repeat`
Repeat an array in a memory-efficient manner
`apply_window`
Apply a window along a given axis
"""
import csv
import inspect
import numpy as np
import matplotlib.cbook as cbook
from matplotlib import docstring
def window_hanning(x):
'''
Return x times the hanning window of len(x).
See Also
--------
window_none : Another window algorithm.
'''
return np.hanning(len(x))*x
def window_none(x):
'''
No window function; simply return x.
See Also
--------
window_hanning : Another window algorithm.
'''
return x
def apply_window(x, window, axis=0, return_window=None):
'''
Apply the given window to the given 1D or 2D array along the given axis.
Parameters
----------
x : 1D or 2D array or sequence
Array or sequence containing the data.
window : function or array.
Either a function to generate a window or an array with length
*x*.shape[*axis*]
axis : integer
The axis over which to do the repetition.
Must be 0 or 1. The default is 0
return_window : bool
If true, also return the 1D values of the window that was applied
'''
x = np.asarray(x)
if x.ndim < 1 or x.ndim > 2:
raise ValueError('only 1D or 2D arrays can be used')
if axis+1 > x.ndim:
raise ValueError('axis(=%s) out of bounds' % axis)
xshape = list(x.shape)
xshapetarg = xshape.pop(axis)
if np.iterable(window):
if len(window) != xshapetarg:
raise ValueError('The len(window) must be the same as the shape '
'of x for the chosen axis')
windowVals = window
else:
windowVals = window(np.ones(xshapetarg, dtype=x.dtype))
if x.ndim == 1:
if return_window:
return windowVals * x, windowVals
else:
return windowVals * x
xshapeother = xshape.pop()
otheraxis = (axis+1) % 2
windowValsRep = stride_repeat(windowVals, xshapeother, axis=otheraxis)
if return_window:
return windowValsRep * x, windowVals
else:
return windowValsRep * x
def detrend(x, key=None, axis=None):
'''
Return x with its trend removed.
Parameters
----------
x : array or sequence
Array or sequence containing the data.
key : [ 'default' | 'constant' | 'mean' | 'linear' | 'none'] or function
Specifies the detrend algorithm to use. 'default' is 'mean', which is
the same as `detrend_mean`. 'constant' is the same. 'linear' is
the same as `detrend_linear`. 'none' is the same as
`detrend_none`. The default is 'mean'. See the corresponding
functions for more details regarding the algorithms. Can also be a
function that carries out the detrend operation.
axis : integer
The axis along which to do the detrending.
See Also
--------
detrend_mean : Implementation of the 'mean' algorithm.
detrend_linear : Implementation of the 'linear' algorithm.
detrend_none : Implementation of the 'none' algorithm.
'''
if key is None or key in ['constant', 'mean', 'default']:
return detrend(x, key=detrend_mean, axis=axis)
elif key == 'linear':
return detrend(x, key=detrend_linear, axis=axis)
elif key == 'none':
return detrend(x, key=detrend_none, axis=axis)
elif isinstance(key, str):
raise ValueError("Unknown value for key %s, must be one of: "
"'default', 'constant', 'mean', "
"'linear', or a function" % key)
if not callable(key):
raise ValueError("Unknown value for key %s, must be one of: "
"'default', 'constant', 'mean', "
"'linear', or a function" % key)
x = np.asarray(x)
if axis is not None and axis+1 > x.ndim:
raise ValueError('axis(=%s) out of bounds' % axis)
if (axis is None and x.ndim == 0) or (not axis and x.ndim == 1):
return key(x)
# try to use the 'axis' argument if the function supports it,
# otherwise use apply_along_axis to do it
try:
return key(x, axis=axis)
except TypeError:
return np.apply_along_axis(key, axis=axis, arr=x)
@cbook.deprecated("3.1", alternative="detrend_mean")
def demean(x, axis=0):
'''
Return x minus its mean along the specified axis.
Parameters
----------
x : array or sequence
Array or sequence containing the data
Can have any dimensionality
axis : integer
The axis along which to take the mean. See numpy.mean for a
description of this argument.
See Also
--------
detrend_mean : Same as `demean` except for the default *axis*.
'''
return detrend_mean(x, axis=axis)
def detrend_mean(x, axis=None):
'''
Return x minus the mean(x).
Parameters
----------
x : array or sequence
Array or sequence containing the data
Can have any dimensionality
axis : integer
The axis along which to take the mean. See numpy.mean for a
description of this argument.
See Also
--------
detrend_linear : Another detrend algorithm.
detrend_none : Another detrend algorithm.
detrend : A wrapper around all the detrend algorithms.
'''
x = np.asarray(x)
if axis is not None and axis+1 > x.ndim:
raise ValueError('axis(=%s) out of bounds' % axis)
return x - x.mean(axis, keepdims=True)
def detrend_none(x, axis=None):
'''
Return x: no detrending.
Parameters
----------
x : any object
An object containing the data
axis : integer
This parameter is ignored.
It is included for compatibility with detrend_mean
See Also
--------
detrend_mean : Another detrend algorithm.
detrend_linear : Another detrend algorithm.
detrend : A wrapper around all the detrend algorithms.
'''
return x
def detrend_linear(y):
'''
Return x minus best fit line; 'linear' detrending.
Parameters
----------
y : 0-D or 1-D array or sequence
Array or sequence containing the data
axis : integer
The axis along which to take the mean. See numpy.mean for a
description of this argument.
See Also
--------
detrend_mean : Another detrend algorithm.
detrend_none : Another detrend algorithm.
detrend : A wrapper around all the detrend algorithms.
'''
# This is faster than an algorithm based on linalg.lstsq.
y = np.asarray(y)
if y.ndim > 1:
raise ValueError('y cannot have ndim > 1')
# short-circuit 0-D array.
if not y.ndim:
return np.array(0., dtype=y.dtype)
x = np.arange(y.size, dtype=float)
C = np.cov(x, y, bias=1)
b = C[0, 1]/C[0, 0]
a = y.mean() - b*x.mean()
return y - (b*x + a)
def stride_windows(x, n, noverlap=None, axis=0):
'''
Get all windows of x with length n as a single array,
using strides to avoid data duplication.
.. warning::
It is not safe to write to the output array. Multiple
elements may point to the same piece of memory,
so modifying one value may change others.
Parameters
----------
x : 1D array or sequence
Array or sequence containing the data.
n : integer
The number of data points in each window.
noverlap : integer
The overlap between adjacent windows.
Default is 0 (no overlap)
axis : integer
The axis along which the windows will run.
References
----------
`stackoverflow: Rolling window for 1D arrays in Numpy?
<http://stackoverflow.com/a/6811241>`_
`stackoverflow: Using strides for an efficient moving average filter
<http://stackoverflow.com/a/4947453>`_
'''
if noverlap is None:
noverlap = 0
if noverlap >= n:
raise ValueError('noverlap must be less than n')
if n < 1:
raise ValueError('n cannot be less than 1')
x = np.asarray(x)
if x.ndim != 1:
raise ValueError('only 1-dimensional arrays can be used')
if n == 1 and noverlap == 0:
if axis == 0:
return x[np.newaxis]
else:
return x[np.newaxis].transpose()
if n > x.size:
raise ValueError('n cannot be greater than the length of x')
# np.lib.stride_tricks.as_strided easily leads to memory corruption for
# non integer shape and strides, i.e. noverlap or n. See #3845.
noverlap = int(noverlap)
n = int(n)
step = n - noverlap
if axis == 0:
shape = (n, (x.shape[-1]-noverlap)//step)
strides = (x.strides[0], step*x.strides[0])
else:
shape = ((x.shape[-1]-noverlap)//step, n)
strides = (step*x.strides[0], x.strides[0])
return np.lib.stride_tricks.as_strided(x, shape=shape, strides=strides)
def stride_repeat(x, n, axis=0):
'''
Repeat the values in an array in a memory-efficient manner. Array x is
stacked vertically n times.
.. warning::
It is not safe to write to the output array. Multiple
elements may point to the same piece of memory, so
modifying one value may change others.
Parameters
----------
x : 1D array or sequence
Array or sequence containing the data.
n : integer
The number of time to repeat the array.
axis : integer
The axis along which the data will run.
References
----------
`stackoverflow: Repeat NumPy array without replicating data?
<http://stackoverflow.com/a/5568169>`_
'''
if axis not in [0, 1]:
raise ValueError('axis must be 0 or 1')
x = np.asarray(x)
if x.ndim != 1:
raise ValueError('only 1-dimensional arrays can be used')
if n == 1:
if axis == 0:
return np.atleast_2d(x)
else:
return np.atleast_2d(x).T
if n < 1:
raise ValueError('n cannot be less than 1')
# np.lib.stride_tricks.as_strided easily leads to memory corruption for
# non integer shape and strides, i.e. n. See #3845.
n = int(n)
if axis == 0:
shape = (n, x.size)
strides = (0, x.strides[0])
else:
shape = (x.size, n)
strides = (x.strides[0], 0)
return np.lib.stride_tricks.as_strided(x, shape=shape, strides=strides)
def _spectral_helper(x, y=None, NFFT=None, Fs=None, detrend_func=None,
window=None, noverlap=None, pad_to=None,
sides=None, scale_by_freq=None, mode=None):
'''
This is a helper function that implements the commonality between the
psd, csd, spectrogram and complex, magnitude, angle, and phase spectrums.
It is *NOT* meant to be used outside of mlab and may change at any time.
'''
if y is None:
# if y is None use x for y
same_data = True
else:
# The checks for if y is x are so that we can use the same function to
# implement the core of psd(), csd(), and spectrogram() without doing
# extra calculations. We return the unaveraged Pxy, freqs, and t.
same_data = y is x
if Fs is None:
Fs = 2
if noverlap is None:
noverlap = 0
if detrend_func is None:
detrend_func = detrend_none
if window is None:
window = window_hanning
# if NFFT is set to None use the whole signal
if NFFT is None:
NFFT = 256
if mode is None or mode == 'default':
mode = 'psd'
elif mode not in ['psd', 'complex', 'magnitude', 'angle', 'phase']:
raise ValueError("Unknown value for mode %s, must be one of: "
"'default', 'psd', 'complex', "
"'magnitude', 'angle', 'phase'" % mode)
if not same_data and mode != 'psd':
raise ValueError("x and y must be equal if mode is not 'psd'")
# Make sure we're dealing with a numpy array. If y and x were the same
# object to start with, keep them that way
x = np.asarray(x)
if not same_data:
y = np.asarray(y)
if sides is None or sides == 'default':
if np.iscomplexobj(x):
sides = 'twosided'
else:
sides = 'onesided'
elif sides not in ['onesided', 'twosided']:
raise ValueError("Unknown value for sides %s, must be one of: "
"'default', 'onesided', or 'twosided'" % sides)
# zero pad x and y up to NFFT if they are shorter than NFFT
if len(x) < NFFT:
n = len(x)
x = np.resize(x, NFFT)
x[n:] = 0
if not same_data and len(y) < NFFT:
n = len(y)
y = np.resize(y, NFFT)
y[n:] = 0
if pad_to is None:
pad_to = NFFT
if mode != 'psd':
scale_by_freq = False
elif scale_by_freq is None:
scale_by_freq = True
# For real x, ignore the negative frequencies unless told otherwise
if sides == 'twosided':
numFreqs = pad_to
if pad_to % 2:
freqcenter = (pad_to - 1)//2 + 1
else:
freqcenter = pad_to//2
scaling_factor = 1.
elif sides == 'onesided':
if pad_to % 2:
numFreqs = (pad_to + 1)//2
else:
numFreqs = pad_to//2 + 1
scaling_factor = 2.
result = stride_windows(x, NFFT, noverlap, axis=0)
result = detrend(result, detrend_func, axis=0)
result, windowVals = apply_window(result, window, axis=0,
return_window=True)
result = np.fft.fft(result, n=pad_to, axis=0)[:numFreqs, :]
freqs = np.fft.fftfreq(pad_to, 1/Fs)[:numFreqs]
if not same_data:
# if same_data is False, mode must be 'psd'
resultY = stride_windows(y, NFFT, noverlap)
resultY = detrend(resultY, detrend_func, axis=0)
resultY = apply_window(resultY, window, axis=0)
resultY = np.fft.fft(resultY, n=pad_to, axis=0)[:numFreqs, :]
result = np.conj(result) * resultY
elif mode == 'psd':
result = np.conj(result) * result
elif mode == 'magnitude':
result = np.abs(result) / np.abs(windowVals).sum()
elif mode == 'angle' or mode == 'phase':
# we unwrap the phase later to handle the onesided vs. twosided case
result = np.angle(result)
elif mode == 'complex':
result /= np.abs(windowVals).sum()
if mode == 'psd':
# Also include scaling factors for one-sided densities and dividing by
# the sampling frequency, if desired. Scale everything, except the DC
# component and the NFFT/2 component:
# if we have a even number of frequencies, don't scale NFFT/2
if not NFFT % 2:
slc = slice(1, -1, None)
# if we have an odd number, just don't scale DC
else:
slc = slice(1, None, None)
result[slc] *= scaling_factor
# MATLAB divides by the sampling frequency so that density function
# has units of dB/Hz and can be integrated by the plotted frequency
# values. Perform the same scaling here.
if scale_by_freq:
result /= Fs
# Scale the spectrum by the norm of the window to compensate for
# windowing loss; see Bendat & Piersol Sec 11.5.2.
result /= (np.abs(windowVals)**2).sum()
else:
# In this case, preserve power in the segment, not amplitude
result /= np.abs(windowVals).sum()**2
t = np.arange(NFFT/2, len(x) - NFFT/2 + 1, NFFT - noverlap)/Fs
if sides == 'twosided':
# center the frequency range at zero
freqs = np.concatenate((freqs[freqcenter:], freqs[:freqcenter]))
result = np.concatenate((result[freqcenter:, :],
result[:freqcenter, :]), 0)
elif not pad_to % 2:
# get the last value correctly, it is negative otherwise
freqs[-1] *= -1
# we unwrap the phase here to handle the onesided vs. twosided case
if mode == 'phase':
result = np.unwrap(result, axis=0)
return result, freqs, t
def _single_spectrum_helper(x, mode, Fs=None, window=None, pad_to=None,
sides=None):
'''
This is a helper function that implements the commonality between the
complex, magnitude, angle, and phase spectrums.
It is *NOT* meant to be used outside of mlab and may change at any time.
'''
if mode is None or mode == 'psd' or mode == 'default':
raise ValueError('_single_spectrum_helper does not work with %s mode'
% mode)
if pad_to is None:
pad_to = len(x)
spec, freqs, _ = _spectral_helper(x=x, y=None, NFFT=len(x), Fs=Fs,
detrend_func=detrend_none, window=window,
noverlap=0, pad_to=pad_to,
sides=sides,
scale_by_freq=False,
mode=mode)
if mode != 'complex':
spec = spec.real
if spec.ndim == 2 and spec.shape[1] == 1:
spec = spec[:, 0]
return spec, freqs
# Split out these keyword docs so that they can be used elsewhere
docstring.interpd.update(Spectral=inspect.cleandoc("""
Fs : scalar
The sampling frequency (samples per time unit). It is used
to calculate the Fourier frequencies, freqs, in cycles per time
unit. The default value is 2.
window : callable or ndarray
A function or a vector of length *NFFT*. To create window vectors see
`window_hanning`, `window_none`, `numpy.blackman`, `numpy.hamming`,
`numpy.bartlett`, `scipy.signal`, `scipy.signal.get_window`, etc. The
default is `window_hanning`. If a function is passed as the argument,
it must take a data segment as an argument and return the windowed
version of the segment.
sides : {'default', 'onesided', 'twosided'}
Specifies which sides of the spectrum to return. Default gives the
default behavior, which returns one-sided for real data and both
for complex data. 'onesided' forces the return of a one-sided
spectrum, while 'twosided' forces two-sided.
"""))
docstring.interpd.update(Single_Spectrum=inspect.cleandoc("""
pad_to : int
The number of points to which the data segment is padded when
performing the FFT. While not increasing the actual resolution of
the spectrum (the minimum distance between resolvable peaks),
this can give more points in the plot, allowing for more
detail. This corresponds to the *n* parameter in the call to fft().
The default is None, which sets *pad_to* equal to the length of the
input signal (i.e. no padding).
"""))
docstring.interpd.update(PSD=inspect.cleandoc("""
pad_to : int
The number of points to which the data segment is padded when
performing the FFT. This can be different from *NFFT*, which
specifies the number of data points used. While not increasing
the actual resolution of the spectrum (the minimum distance between
resolvable peaks), this can give more points in the plot,
allowing for more detail. This corresponds to the *n* parameter
in the call to fft(). The default is None, which sets *pad_to*
equal to *NFFT*
NFFT : int
The number of data points used in each block for the FFT.
A power 2 is most efficient. The default value is 256.
This should *NOT* be used to get zero padding, or the scaling of the
result will be incorrect. Use *pad_to* for this instead.
detrend : {'none', 'mean', 'linear'} or callable, default 'none'
The function applied to each segment before fft-ing, designed to
remove the mean or linear trend. Unlike in MATLAB, where the
*detrend* parameter is a vector, in Matplotlib is it a function.
The :mod:`~matplotlib.mlab` module defines `.detrend_none`,
`.detrend_mean`, and `.detrend_linear`, but you can use a custom
function as well. You can also use a string to choose one of the
functions: 'none' calls `.detrend_none`. 'mean' calls `.detrend_mean`.
'linear' calls `.detrend_linear`.
scale_by_freq : bool, optional
Specifies whether the resulting density values should be scaled
by the scaling frequency, which gives density in units of Hz^-1.
This allows for integration over the returned frequency values.
The default is True for MATLAB compatibility.
"""))
@docstring.dedent_interpd
def psd(x, NFFT=None, Fs=None, detrend=None, window=None,
noverlap=None, pad_to=None, sides=None, scale_by_freq=None):
r"""
Compute the power spectral density.
The power spectral density :math:`P_{xx}` by Welch's average
periodogram method. The vector *x* is divided into *NFFT* length
segments. Each segment is detrended by function *detrend* and
windowed by function *window*. *noverlap* gives the length of
the overlap between segments. The :math:`|\mathrm{fft}(i)|^2`
of each segment :math:`i` are averaged to compute :math:`P_{xx}`.
If len(*x*) < *NFFT*, it will be zero padded to *NFFT*.
Parameters
----------
x : 1-D array or sequence
Array or sequence containing the data
%(Spectral)s
%(PSD)s
noverlap : integer
The number of points of overlap between segments.
The default value is 0 (no overlap).
Returns
-------
Pxx : 1-D array
The values for the power spectrum `P_{xx}` (real valued)
freqs : 1-D array
The frequencies corresponding to the elements in *Pxx*
References
----------
Bendat & Piersol -- Random Data: Analysis and Measurement Procedures, John
Wiley & Sons (1986)
See Also
--------
specgram
`specgram` differs in the default overlap; in not returning the mean of
the segment periodograms; and in returning the times of the segments.
magnitude_spectrum : returns the magnitude spectrum.
csd : returns the spectral density between two signals.
"""
Pxx, freqs = csd(x=x, y=None, NFFT=NFFT, Fs=Fs, detrend=detrend,
window=window, noverlap=noverlap, pad_to=pad_to,
sides=sides, scale_by_freq=scale_by_freq)
return Pxx.real, freqs
@docstring.dedent_interpd
def csd(x, y, NFFT=None, Fs=None, detrend=None, window=None,
noverlap=None, pad_to=None, sides=None, scale_by_freq=None):
"""
Compute the cross-spectral density.
The cross spectral density :math:`P_{xy}` by Welch's average
periodogram method. The vectors *x* and *y* are divided into
*NFFT* length segments. Each segment is detrended by function
*detrend* and windowed by function *window*. *noverlap* gives
the length of the overlap between segments. The product of
the direct FFTs of *x* and *y* are averaged over each segment
to compute :math:`P_{xy}`, with a scaling to correct for power
loss due to windowing.
If len(*x*) < *NFFT* or len(*y*) < *NFFT*, they will be zero
padded to *NFFT*.
Parameters
----------
x, y : 1-D arrays or sequences
Arrays or sequences containing the data
%(Spectral)s
%(PSD)s
noverlap : integer
The number of points of overlap between segments.
The default value is 0 (no overlap).
Returns
-------
Pxy : 1-D array
The values for the cross spectrum `P_{xy}` before scaling (real valued)
freqs : 1-D array
The frequencies corresponding to the elements in *Pxy*
References
----------
Bendat & Piersol -- Random Data: Analysis and Measurement Procedures, John
Wiley & Sons (1986)
See Also
--------
psd : equivalent to setting ``y = x``.
"""
if NFFT is None:
NFFT = 256
Pxy, freqs, _ = _spectral_helper(x=x, y=y, NFFT=NFFT, Fs=Fs,
detrend_func=detrend, window=window,
noverlap=noverlap, pad_to=pad_to,
sides=sides, scale_by_freq=scale_by_freq,
mode='psd')
if Pxy.ndim == 2:
if Pxy.shape[1] > 1:
Pxy = Pxy.mean(axis=1)
else:
Pxy = Pxy[:, 0]
return Pxy, freqs
@docstring.dedent_interpd
def complex_spectrum(x, Fs=None, window=None, pad_to=None,
sides=None):
"""
Compute the complex-valued frequency spectrum of *x*. Data is padded to a
length of *pad_to* and the windowing function *window* is applied to the
signal.
Parameters
----------
x : 1-D array or sequence
Array or sequence containing the data
%(Spectral)s
%(Single_Spectrum)s
Returns
-------
spectrum : 1-D array
The values for the complex spectrum (complex valued)
freqs : 1-D array
The frequencies corresponding to the elements in *spectrum*
See Also
--------
magnitude_spectrum
Returns the absolute value of this function.
angle_spectrum
Returns the angle of this function.
phase_spectrum
Returns the phase (unwrapped angle) of this function.
specgram
Can return the complex spectrum of segments within the signal.
"""
return _single_spectrum_helper(x=x, Fs=Fs, window=window, pad_to=pad_to,
sides=sides, mode='complex')
@docstring.dedent_interpd
def magnitude_spectrum(x, Fs=None, window=None, pad_to=None,
sides=None):
"""
Compute the magnitude (absolute value) of the frequency spectrum of
*x*. Data is padded to a length of *pad_to* and the windowing function
*window* is applied to the signal.
Parameters
----------
x : 1-D array or sequence
Array or sequence containing the data
%(Spectral)s
%(Single_Spectrum)s
Returns
-------
spectrum : 1-D array
The values for the magnitude spectrum (real valued)
freqs : 1-D array
The frequencies corresponding to the elements in *spectrum*
See Also
--------
psd
Returns the power spectral density.
complex_spectrum
This function returns the absolute value of `complex_spectrum`.
angle_spectrum
Returns the angles of the corresponding frequencies.
phase_spectrum
Returns the phase (unwrapped angle) of the corresponding frequencies.
specgram
Can return the complex spectrum of segments within the signal.
"""
return _single_spectrum_helper(x=x, Fs=Fs, window=window, pad_to=pad_to,
sides=sides, mode='magnitude')
@docstring.dedent_interpd
def angle_spectrum(x, Fs=None, window=None, pad_to=None,
sides=None):
"""
Compute the angle of the frequency spectrum (wrapped phase spectrum) of
*x*. Data is padded to a length of *pad_to* and the windowing function
*window* is applied to the signal.
Parameters
----------
x : 1-D array or sequence
Array or sequence containing the data
%(Spectral)s
%(Single_Spectrum)s
Returns
-------
spectrum : 1-D array
The values for the angle spectrum in radians (real valued)
freqs : 1-D array
The frequencies corresponding to the elements in *spectrum*
See Also
--------
complex_spectrum
This function returns the angle value of `complex_spectrum`.
magnitude_spectrum
Returns the magnitudes of the corresponding frequencies.
phase_spectrum
Returns the phase (unwrapped angle) of the corresponding frequencies.
specgram
Can return the complex spectrum of segments within the signal.
"""
return _single_spectrum_helper(x=x, Fs=Fs, window=window, pad_to=pad_to,
sides=sides, mode='angle')
@docstring.dedent_interpd
def phase_spectrum(x, Fs=None, window=None, pad_to=None,
sides=None):
"""
Compute the phase of the frequency spectrum (unwrapped angle spectrum) of
*x*. Data is padded to a length of *pad_to* and the windowing function
*window* is applied to the signal.
Parameters
----------
x : 1-D array or sequence
Array or sequence containing the data
%(Spectral)s
%(Single_Spectrum)s
Returns
-------
spectrum : 1-D array
The values for the phase spectrum in radians (real valued)
freqs : 1-D array
The frequencies corresponding to the elements in *spectrum*
See Also
--------
complex_spectrum
This function returns the phase value of `complex_spectrum`.
magnitude_spectrum
Returns the magnitudes of the corresponding frequencies.
angle_spectrum
Returns the angle (wrapped phase) of the corresponding frequencies.
specgram
Can return the complex spectrum of segments within the signal.
"""
return _single_spectrum_helper(x=x, Fs=Fs, window=window, pad_to=pad_to,
sides=sides, mode='phase')
@docstring.dedent_interpd
def specgram(x, NFFT=None, Fs=None, detrend=None, window=None,
noverlap=None, pad_to=None, sides=None, scale_by_freq=None,
mode=None):
"""
Compute a spectrogram.
Compute and plot a spectrogram of data in x. Data are split into
NFFT length segments and the spectrum of each section is
computed. The windowing function window is applied to each
segment, and the amount of overlap of each segment is
specified with noverlap.
Parameters
----------
x : array_like
1-D array or sequence.
%(Spectral)s
%(PSD)s
noverlap : int, optional
The number of points of overlap between blocks. The default
value is 128.
mode : str, optional
What sort of spectrum to use, default is 'psd'.
'psd'
Returns the power spectral density.
'complex'
Returns the complex-valued frequency spectrum.
'magnitude'
Returns the magnitude spectrum.
'angle'
Returns the phase spectrum without unwrapping.
'phase'
Returns the phase spectrum with unwrapping.
Returns
-------
spectrum : array_like
2-D array, columns are the periodograms of successive segments.
freqs : array_like
1-D array, frequencies corresponding to the rows in *spectrum*.
t : array_like
1-D array, the times corresponding to midpoints of segments
(i.e the columns in *spectrum*).
See Also
--------
psd : differs in the overlap and in the return values.
complex_spectrum : similar, but with complex valued frequencies.
magnitude_spectrum : similar single segment when mode is 'magnitude'.
angle_spectrum : similar to single segment when mode is 'angle'.
phase_spectrum : similar to single segment when mode is 'phase'.
Notes
-----
detrend and scale_by_freq only apply when *mode* is set to 'psd'.
"""
if noverlap is None:
noverlap = 128 # default in _spectral_helper() is noverlap = 0
if NFFT is None:
NFFT = 256 # same default as in _spectral_helper()
if len(x) <= NFFT:
cbook._warn_external("Only one segment is calculated since parameter "
"NFFT (=%d) >= signal length (=%d)." %
(NFFT, len(x)))
spec, freqs, t = _spectral_helper(x=x, y=None, NFFT=NFFT, Fs=Fs,
detrend_func=detrend, window=window,
noverlap=noverlap, pad_to=pad_to,
sides=sides,
scale_by_freq=scale_by_freq,
mode=mode)
if mode != 'complex':
spec = spec.real # Needed since helper implements generically
return spec, freqs, t
_coh_error = """Coherence is calculated by averaging over *NFFT*
length segments. Your signal is too short for your choice of *NFFT*.
"""
@docstring.dedent_interpd
def cohere(x, y, NFFT=256, Fs=2, detrend=detrend_none, window=window_hanning,
noverlap=0, pad_to=None, sides='default', scale_by_freq=None):
"""
The coherence between *x* and *y*. Coherence is the normalized
cross spectral density:
.. math::
C_{xy} = \\frac{|P_{xy}|^2}{P_{xx}P_{yy}}
Parameters
----------
x, y
Array or sequence containing the data
%(Spectral)s
%(PSD)s
noverlap : integer
The number of points of overlap between blocks. The default value
is 0 (no overlap).
Returns
-------
The return value is the tuple (*Cxy*, *f*), where *f* are the
frequencies of the coherence vector. For cohere, scaling the
individual densities by the sampling frequency has no effect,
since the factors cancel out.
See Also
--------
:func:`psd`, :func:`csd` :
For information about the methods used to compute :math:`P_{xy}`,
:math:`P_{xx}` and :math:`P_{yy}`.
"""
if len(x) < 2 * NFFT:
raise ValueError(_coh_error)
Pxx, f = psd(x, NFFT, Fs, detrend, window, noverlap, pad_to, sides,
scale_by_freq)
Pyy, f = psd(y, NFFT, Fs, detrend, window, noverlap, pad_to, sides,
scale_by_freq)
Pxy, f = csd(x, y, NFFT, Fs, detrend, window, noverlap, pad_to, sides,
scale_by_freq)
Cxy = np.abs(Pxy) ** 2 / (Pxx * Pyy)
return Cxy, f
def _csv2rec(fname, comments='#', skiprows=0, checkrows=0, delimiter=',',
converterd=None, names=None, missing='', missingd=None,
use_mrecords=False, dayfirst=False, yearfirst=False):
"""
Load data from comma/space/tab delimited file in *fname* into a
numpy record array and return the record array.
If *names* is *None*, a header row is required to automatically
assign the recarray names. The headers will be lower cased,
spaces will be converted to underscores, and illegal attribute
name characters removed. If *names* is not *None*, it is a
sequence of names to use for the column names. In this case, it
is assumed there is no header row.
- *fname*: can be a filename or a file handle. Support for gzipped
files is automatic, if the filename ends in '.gz'
- *comments*: the character used to indicate the start of a comment
in the file, or *None* to switch off the removal of comments
- *skiprows*: is the number of rows from the top to skip
- *checkrows*: is the number of rows to check to validate the column
data type. When set to zero all rows are validated.
- *converterd*: if not *None*, is a dictionary mapping column number or
munged column name to a converter function.
- *names*: if not None, is a list of header names. In this case, no
header will be read from the file
- *missingd* is a dictionary mapping munged column names to field values
which signify that the field does not contain actual data and should
be masked, e.g., '0000-00-00' or 'unused'
- *missing*: a string whose value signals a missing field regardless of
the column it appears in
- *use_mrecords*: if True, return an mrecords.fromrecords record array if
any of the data are missing
- *dayfirst*: default is False so that MM-DD-YY has precedence over
DD-MM-YY. See
http://labix.org/python-dateutil#head-b95ce2094d189a89f80f5ae52a05b4ab7b41af47
for further information.
- *yearfirst*: default is False so that MM-DD-YY has precedence over
YY-MM-DD. See
http://labix.org/python-dateutil#head-b95ce2094d189a89f80f5ae52a05b4ab7b41af47
for further information.
If no rows are found, *None* is returned
"""
if converterd is None:
converterd = dict()
if missingd is None:
missingd = {}
import dateutil.parser
import datetime
fh = cbook.to_filehandle(fname)
delimiter = str(delimiter)
class FH:
"""
For space-delimited files, we want different behavior than
comma or tab. Generally, we want multiple spaces to be
treated as a single separator, whereas with comma and tab we
want multiple commas to return multiple (empty) fields. The
join/strip trick below effects this.
"""
def __init__(self, fh):
self.fh = fh
def close(self):
self.fh.close()
def seek(self, arg):
self.fh.seek(arg)
def fix(self, s):
return ' '.join(s.split())
def __next__(self):
return self.fix(next(self.fh))
def __iter__(self):
for line in self.fh:
yield self.fix(line)
if delimiter == ' ':
fh = FH(fh)
reader = csv.reader(fh, delimiter=delimiter)
def process_skiprows(reader):
if skiprows:
for i, row in enumerate(reader):
if i >= (skiprows-1):
break
return fh, reader
process_skiprows(reader)
def ismissing(name, val):
"Should the value val in column name be masked?"
return val == missing or val == missingd.get(name) or val == ''
def with_default_value(func, default):
def newfunc(name, val):
if ismissing(name, val):
return default
else:
return func(val)
return newfunc
def mybool(x):
if x == 'True':
return True
elif x == 'False':
return False
else:
raise ValueError('invalid bool')
dateparser = dateutil.parser.parse
def mydateparser(x):
# try and return a datetime object
d = dateparser(x, dayfirst=dayfirst, yearfirst=yearfirst)
return d
mydateparser = with_default_value(mydateparser, datetime.datetime(1, 1, 1))
myfloat = with_default_value(float, np.nan)
myint = with_default_value(int, -1)
mystr = with_default_value(str, '')
mybool = with_default_value(mybool, None)
def mydate(x):
# try and return a date object
d = dateparser(x, dayfirst=dayfirst, yearfirst=yearfirst)
if d.hour > 0 or d.minute > 0 or d.second > 0:
raise ValueError('not a date')
return d.date()
mydate = with_default_value(mydate, datetime.date(1, 1, 1))
def get_func(name, item, func):
# promote functions in this order
funcs = [mybool, myint, myfloat, mydate, mydateparser, mystr]
for func in funcs[funcs.index(func):]:
try:
func(name, item)
except Exception:
continue
return func
raise ValueError('Could not find a working conversion function')
# map column names that clash with builtins -- TODO - extend this list
itemd = {
'return': 'return_',
'file': 'file_',
'print': 'print_',
}
def get_converters(reader, comments):
converters = None
i = 0
for row in reader:
if (len(row) and comments is not None and
row[0].startswith(comments)):
continue
if i == 0:
converters = [mybool]*len(row)
if checkrows and i > checkrows:
break
i += 1
for j, (name, item) in enumerate(zip(names, row)):
func = converterd.get(j)
if func is None:
func = converterd.get(name)
if func is None:
func = converters[j]
if len(item.strip()):
func = get_func(name, item, func)
else:
# how should we handle custom converters and defaults?
func = with_default_value(func, None)
converters[j] = func
return converters
# Get header and remove invalid characters
needheader = names is None
if needheader:
for row in reader:
if (len(row) and comments is not None and
row[0].startswith(comments)):
continue
headers = row
break
# remove these chars
delete = set(r"""~!@#$%^&*()-=+~\|}[]{';: /?.>,<""")
delete.add('"')
names = []
seen = dict()
for i, item in enumerate(headers):
item = item.strip().lower().replace(' ', '_')
item = ''.join([c for c in item if c not in delete])
if not len(item):
item = 'column%d' % i
item = itemd.get(item, item)
cnt = seen.get(item, 0)
if cnt > 0:
names.append(item + '_%d' % cnt)
else:
names.append(item)
seen[item] = cnt+1
else:
if isinstance(names, str):
names = [n.strip() for n in names.split(',')]
# get the converter functions by inspecting checkrows
converters = get_converters(reader, comments)
if converters is None:
raise ValueError('Could not find any valid data in CSV file')
# reset the reader and start over
fh.seek(0)
reader = csv.reader(fh, delimiter=delimiter)
process_skiprows(reader)
if needheader:
while True:
# skip past any comments and consume one line of column header
row = next(reader)
if (len(row) and comments is not None and
row[0].startswith(comments)):
continue
break
# iterate over the remaining rows and convert the data to date
# objects, ints, or floats as appropriate
rows = []
rowmasks = []
for i, row in enumerate(reader):
if not len(row):
continue
if comments is not None and row[0].startswith(comments):
continue
# Ensure that the row returned always has the same nr of elements
row.extend([''] * (len(converters) - len(row)))
rows.append([func(name, val)
for func, name, val in zip(converters, names, row)])
rowmasks.append([ismissing(name, val)
for name, val in zip(names, row)])
fh.close()
if not len(rows):
return None
if use_mrecords and np.any(rowmasks):
r = np.ma.mrecords.fromrecords(rows, names=names, mask=rowmasks)
else:
r = np.rec.fromrecords(rows, names=names)
return r
class GaussianKDE(object):
"""
Representation of a kernel-density estimate using Gaussian kernels.
Parameters
----------
dataset : array_like
Datapoints to estimate from. In case of univariate data this is a 1-D
array, otherwise a 2-D array with shape (# of dims, # of data).
bw_method : str, scalar or callable, optional
The method used to calculate the estimator bandwidth. This can be
'scott', 'silverman', a scalar constant or a callable. If a
scalar, this will be used directly as `kde.factor`. If a
callable, it should take a `GaussianKDE` instance as only
parameter and return a scalar. If None (default), 'scott' is used.
Attributes
----------
dataset : ndarray
The dataset with which `gaussian_kde` was initialized.
dim : int
Number of dimensions.
num_dp : int
Number of datapoints.
factor : float
The bandwidth factor, obtained from `kde.covariance_factor`, with which
the covariance matrix is multiplied.
covariance : ndarray
The covariance matrix of `dataset`, scaled by the calculated bandwidth
(`kde.factor`).
inv_cov : ndarray
The inverse of `covariance`.
Methods
-------
kde.evaluate(points) : ndarray
Evaluate the estimated pdf on a provided set of points.
kde(points) : ndarray
Same as kde.evaluate(points)
"""
# This implementation with minor modification was too good to pass up.
# from scipy: https://github.com/scipy/scipy/blob/master/scipy/stats/kde.py
def __init__(self, dataset, bw_method=None):
self.dataset = np.atleast_2d(dataset)
if not np.array(self.dataset).size > 1:
raise ValueError("`dataset` input should have multiple elements.")
self.dim, self.num_dp = np.array(self.dataset).shape
isString = isinstance(bw_method, str)
if bw_method is None:
pass
elif (isString and bw_method == 'scott'):
self.covariance_factor = self.scotts_factor
elif (isString and bw_method == 'silverman'):
self.covariance_factor = self.silverman_factor
elif (np.isscalar(bw_method) and not isString):
self._bw_method = 'use constant'
self.covariance_factor = lambda: bw_method
elif callable(bw_method):
self._bw_method = bw_method
self.covariance_factor = lambda: self._bw_method(self)
else:
raise ValueError("`bw_method` should be 'scott', 'silverman', a "
"scalar or a callable")
# Computes the covariance matrix for each Gaussian kernel using
# covariance_factor().
self.factor = self.covariance_factor()
# Cache covariance and inverse covariance of the data
if not hasattr(self, '_data_inv_cov'):
self.data_covariance = np.atleast_2d(
np.cov(
self.dataset,
rowvar=1,
bias=False))
self.data_inv_cov = np.linalg.inv(self.data_covariance)
self.covariance = self.data_covariance * self.factor ** 2
self.inv_cov = self.data_inv_cov / self.factor ** 2
self.norm_factor = np.sqrt(
np.linalg.det(
2 * np.pi * self.covariance)) * self.num_dp
def scotts_factor(self):
return np.power(self.num_dp, -1. / (self.dim + 4))
def silverman_factor(self):
return np.power(
self.num_dp * (self.dim + 2.0) / 4.0, -1. / (self.dim + 4))
# Default method to calculate bandwidth, can be overwritten by subclass
covariance_factor = scotts_factor
def evaluate(self, points):
"""Evaluate the estimated pdf on a set of points.
Parameters
----------
points : (# of dimensions, # of points)-array
Alternatively, a (# of dimensions,) vector can be passed in and
treated as a single point.
Returns
-------
values : (# of points,)-array
The values at each point.
Raises
------
ValueError : if the dimensionality of the input points is different
than the dimensionality of the KDE.
"""
points = np.atleast_2d(points)
dim, num_m = np.array(points).shape
if dim != self.dim:
raise ValueError("points have dimension {}, dataset has dimension "
"{}".format(dim, self.dim))
result = np.zeros(num_m)
if num_m >= self.num_dp:
# there are more points than data, so loop over data
for i in range(self.num_dp):
diff = self.dataset[:, i, np.newaxis] - points
tdiff = np.dot(self.inv_cov, diff)
energy = np.sum(diff * tdiff, axis=0) / 2.0
result = result + np.exp(-energy)
else:
# loop over points
for i in range(num_m):
diff = self.dataset - points[:, i, np.newaxis]
tdiff = np.dot(self.inv_cov, diff)
energy = np.sum(diff * tdiff, axis=0) / 2.0
result[i] = np.sum(np.exp(-energy), axis=0)
result = result / self.norm_factor
return result
__call__ = evaluate
|
b3b1908e8b86414f701de77a5b87dad0b5eba1d5d433211efeba834a7a43702e
|
"""
A module for reading dvi files output by TeX. Several limitations make
this not (currently) useful as a general-purpose dvi preprocessor, but
it is currently used by the pdf backend for processing usetex text.
Interface::
with Dvi(filename, 72) as dvi:
# iterate over pages:
for page in dvi:
w, h, d = page.width, page.height, page.descent
for x, y, font, glyph, width in page.text:
fontname = font.texname
pointsize = font.size
...
for x, y, height, width in page.boxes:
...
"""
from collections import namedtuple
import enum
from functools import lru_cache, partial, wraps
import logging
import os
import re
import struct
import textwrap
import numpy as np
from matplotlib import cbook, rcParams
_log = logging.getLogger(__name__)
# Many dvi related files are looked for by external processes, require
# additional parsing, and are used many times per rendering, which is why they
# are cached using lru_cache().
# Dvi is a bytecode format documented in
# http://mirrors.ctan.org/systems/knuth/dist/texware/dvitype.web
# http://texdoc.net/texmf-dist/doc/generic/knuth/texware/dvitype.pdf
#
# The file consists of a preamble, some number of pages, a postamble,
# and a finale. Different opcodes are allowed in different contexts,
# so the Dvi object has a parser state:
#
# pre: expecting the preamble
# outer: between pages (followed by a page or the postamble,
# also e.g. font definitions are allowed)
# page: processing a page
# post_post: state after the postamble (our current implementation
# just stops reading)
# finale: the finale (unimplemented in our current implementation)
_dvistate = enum.Enum('DviState', 'pre outer inpage post_post finale')
# The marks on a page consist of text and boxes. A page also has dimensions.
Page = namedtuple('Page', 'text boxes height width descent')
Text = namedtuple('Text', 'x y font glyph width')
Box = namedtuple('Box', 'x y height width')
# Opcode argument parsing
#
# Each of the following functions takes a Dvi object and delta,
# which is the difference between the opcode and the minimum opcode
# with the same meaning. Dvi opcodes often encode the number of
# argument bytes in this delta.
def _arg_raw(dvi, delta):
"""Return *delta* without reading anything more from the dvi file"""
return delta
def _arg(bytes, signed, dvi, _):
"""Read *bytes* bytes, returning the bytes interpreted as a
signed integer if *signed* is true, unsigned otherwise."""
return dvi._arg(bytes, signed)
def _arg_slen(dvi, delta):
"""Signed, length *delta*
Read *delta* bytes, returning None if *delta* is zero, and
the bytes interpreted as a signed integer otherwise."""
if delta == 0:
return None
return dvi._arg(delta, True)
def _arg_slen1(dvi, delta):
"""Signed, length *delta*+1
Read *delta*+1 bytes, returning the bytes interpreted as signed."""
return dvi._arg(delta+1, True)
def _arg_ulen1(dvi, delta):
"""Unsigned length *delta*+1
Read *delta*+1 bytes, returning the bytes interpreted as unsigned."""
return dvi._arg(delta+1, False)
def _arg_olen1(dvi, delta):
"""Optionally signed, length *delta*+1
Read *delta*+1 bytes, returning the bytes interpreted as
unsigned integer for 0<=*delta*<3 and signed if *delta*==3."""
return dvi._arg(delta + 1, delta == 3)
_arg_mapping = dict(raw=_arg_raw,
u1=partial(_arg, 1, False),
u4=partial(_arg, 4, False),
s4=partial(_arg, 4, True),
slen=_arg_slen,
olen1=_arg_olen1,
slen1=_arg_slen1,
ulen1=_arg_ulen1)
def _dispatch(table, min, max=None, state=None, args=('raw',)):
"""Decorator for dispatch by opcode. Sets the values in *table*
from *min* to *max* to this method, adds a check that the Dvi state
matches *state* if not None, reads arguments from the file according
to *args*.
*table*
the dispatch table to be filled in
*min*
minimum opcode for calling this function
*max*
maximum opcode for calling this function, None if only *min* is allowed
*state*
state of the Dvi object in which these opcodes are allowed
*args*
sequence of argument specifications:
``'raw'``: opcode minus minimum
``'u1'``: read one unsigned byte
``'u4'``: read four bytes, treat as an unsigned number
``'s4'``: read four bytes, treat as a signed number
``'slen'``: read (opcode - minimum) bytes, treat as signed
``'slen1'``: read (opcode - minimum + 1) bytes, treat as signed
``'ulen1'``: read (opcode - minimum + 1) bytes, treat as unsigned
``'olen1'``: read (opcode - minimum + 1) bytes, treat as unsigned
if under four bytes, signed if four bytes
"""
def decorate(method):
get_args = [_arg_mapping[x] for x in args]
@wraps(method)
def wrapper(self, byte):
if state is not None and self.state != state:
raise ValueError("state precondition failed")
return method(self, *[f(self, byte-min) for f in get_args])
if max is None:
table[min] = wrapper
else:
for i in range(min, max+1):
assert table[i] is None
table[i] = wrapper
return wrapper
return decorate
class Dvi(object):
"""
A reader for a dvi ("device-independent") file, as produced by TeX.
The current implementation can only iterate through pages in order,
and does not even attempt to verify the postamble.
This class can be used as a context manager to close the underlying
file upon exit. Pages can be read via iteration. Here is an overly
simple way to extract text without trying to detect whitespace::
>>> with matplotlib.dviread.Dvi('input.dvi', 72) as dvi:
... for page in dvi:
... print(''.join(chr(t.glyph) for t in page.text))
"""
# dispatch table
_dtable = [None] * 256
_dispatch = partial(_dispatch, _dtable)
def __init__(self, filename, dpi):
"""
Read the data from the file named *filename* and convert
TeX's internal units to units of *dpi* per inch.
*dpi* only sets the units and does not limit the resolution.
Use None to return TeX's internal units.
"""
_log.debug('Dvi: %s', filename)
self.file = open(filename, 'rb')
self.dpi = dpi
self.fonts = {}
self.state = _dvistate.pre
self.baseline = self._get_baseline(filename)
def _get_baseline(self, filename):
if rcParams['text.latex.preview']:
base, ext = os.path.splitext(filename)
baseline_filename = base + ".baseline"
if os.path.exists(baseline_filename):
with open(baseline_filename, 'rb') as fd:
l = fd.read().split()
height, depth, width = l
return float(depth)
return None
def __enter__(self):
"""
Context manager enter method, does nothing.
"""
return self
def __exit__(self, etype, evalue, etrace):
"""
Context manager exit method, closes the underlying file if it is open.
"""
self.close()
def __iter__(self):
"""
Iterate through the pages of the file.
Yields
------
Page
Details of all the text and box objects on the page.
The Page tuple contains lists of Text and Box tuples and
the page dimensions, and the Text and Box tuples contain
coordinates transformed into a standard Cartesian
coordinate system at the dpi value given when initializing.
The coordinates are floating point numbers, but otherwise
precision is not lost and coordinate values are not clipped to
integers.
"""
while self._read():
yield self._output()
def close(self):
"""
Close the underlying file if it is open.
"""
if not self.file.closed:
self.file.close()
def _output(self):
"""
Output the text and boxes belonging to the most recent page.
page = dvi._output()
"""
minx, miny, maxx, maxy = np.inf, np.inf, -np.inf, -np.inf
maxy_pure = -np.inf
for elt in self.text + self.boxes:
if isinstance(elt, Box):
x, y, h, w = elt
e = 0 # zero depth
else: # glyph
x, y, font, g, w = elt
h, e = font._height_depth_of(g)
minx = min(minx, x)
miny = min(miny, y - h)
maxx = max(maxx, x + w)
maxy = max(maxy, y + e)
maxy_pure = max(maxy_pure, y)
if self.dpi is None:
# special case for ease of debugging: output raw dvi coordinates
return Page(text=self.text, boxes=self.boxes,
width=maxx-minx, height=maxy_pure-miny,
descent=maxy-maxy_pure)
# convert from TeX's "scaled points" to dpi units
d = self.dpi / (72.27 * 2**16)
if self.baseline is None:
descent = (maxy - maxy_pure) * d
else:
descent = self.baseline
text = [Text((x-minx)*d, (maxy-y)*d - descent, f, g, w*d)
for (x, y, f, g, w) in self.text]
boxes = [Box((x-minx)*d, (maxy-y)*d - descent, h*d, w*d)
for (x, y, h, w) in self.boxes]
return Page(text=text, boxes=boxes, width=(maxx-minx)*d,
height=(maxy_pure-miny)*d, descent=descent)
def _read(self):
"""
Read one page from the file. Return True if successful,
False if there were no more pages.
"""
while True:
byte = self.file.read(1)[0]
self._dtable[byte](self, byte)
if byte == 140: # end of page
return True
if self.state is _dvistate.post_post: # end of file
self.close()
return False
def _arg(self, nbytes, signed=False):
"""
Read and return an integer argument *nbytes* long.
Signedness is determined by the *signed* keyword.
"""
str = self.file.read(nbytes)
value = str[0]
if signed and value >= 0x80:
value = value - 0x100
for i in range(1, nbytes):
value = 0x100*value + str[i]
return value
@_dispatch(min=0, max=127, state=_dvistate.inpage)
def _set_char_immediate(self, char):
self._put_char_real(char)
self.h += self.fonts[self.f]._width_of(char)
@_dispatch(min=128, max=131, state=_dvistate.inpage, args=('olen1',))
def _set_char(self, char):
self._put_char_real(char)
self.h += self.fonts[self.f]._width_of(char)
@_dispatch(132, state=_dvistate.inpage, args=('s4', 's4'))
def _set_rule(self, a, b):
self._put_rule_real(a, b)
self.h += b
@_dispatch(min=133, max=136, state=_dvistate.inpage, args=('olen1',))
def _put_char(self, char):
self._put_char_real(char)
def _put_char_real(self, char):
font = self.fonts[self.f]
if font._vf is None:
self.text.append(Text(self.h, self.v, font, char,
font._width_of(char)))
else:
scale = font._scale
for x, y, f, g, w in font._vf[char].text:
newf = DviFont(scale=_mul2012(scale, f._scale),
tfm=f._tfm, texname=f.texname, vf=f._vf)
self.text.append(Text(self.h + _mul2012(x, scale),
self.v + _mul2012(y, scale),
newf, g, newf._width_of(g)))
self.boxes.extend([Box(self.h + _mul2012(x, scale),
self.v + _mul2012(y, scale),
_mul2012(a, scale), _mul2012(b, scale))
for x, y, a, b in font._vf[char].boxes])
@_dispatch(137, state=_dvistate.inpage, args=('s4', 's4'))
def _put_rule(self, a, b):
self._put_rule_real(a, b)
def _put_rule_real(self, a, b):
if a > 0 and b > 0:
self.boxes.append(Box(self.h, self.v, a, b))
@_dispatch(138)
def _nop(self, _):
pass
@_dispatch(139, state=_dvistate.outer, args=('s4',)*11)
def _bop(self, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, p):
self.state = _dvistate.inpage
self.h, self.v, self.w, self.x, self.y, self.z = 0, 0, 0, 0, 0, 0
self.stack = []
self.text = [] # list of Text objects
self.boxes = [] # list of Box objects
@_dispatch(140, state=_dvistate.inpage)
def _eop(self, _):
self.state = _dvistate.outer
del self.h, self.v, self.w, self.x, self.y, self.z, self.stack
@_dispatch(141, state=_dvistate.inpage)
def _push(self, _):
self.stack.append((self.h, self.v, self.w, self.x, self.y, self.z))
@_dispatch(142, state=_dvistate.inpage)
def _pop(self, _):
self.h, self.v, self.w, self.x, self.y, self.z = self.stack.pop()
@_dispatch(min=143, max=146, state=_dvistate.inpage, args=('slen1',))
def _right(self, b):
self.h += b
@_dispatch(min=147, max=151, state=_dvistate.inpage, args=('slen',))
def _right_w(self, new_w):
if new_w is not None:
self.w = new_w
self.h += self.w
@_dispatch(min=152, max=156, state=_dvistate.inpage, args=('slen',))
def _right_x(self, new_x):
if new_x is not None:
self.x = new_x
self.h += self.x
@_dispatch(min=157, max=160, state=_dvistate.inpage, args=('slen1',))
def _down(self, a):
self.v += a
@_dispatch(min=161, max=165, state=_dvistate.inpage, args=('slen',))
def _down_y(self, new_y):
if new_y is not None:
self.y = new_y
self.v += self.y
@_dispatch(min=166, max=170, state=_dvistate.inpage, args=('slen',))
def _down_z(self, new_z):
if new_z is not None:
self.z = new_z
self.v += self.z
@_dispatch(min=171, max=234, state=_dvistate.inpage)
def _fnt_num_immediate(self, k):
self.f = k
@_dispatch(min=235, max=238, state=_dvistate.inpage, args=('olen1',))
def _fnt_num(self, new_f):
self.f = new_f
@_dispatch(min=239, max=242, args=('ulen1',))
def _xxx(self, datalen):
special = self.file.read(datalen)
_log.debug(
'Dvi._xxx: encountered special: %s',
''.join([chr(ch) if 32 <= ch < 127 else '<%02x>' % ch
for ch in special]))
@_dispatch(min=243, max=246, args=('olen1', 'u4', 'u4', 'u4', 'u1', 'u1'))
def _fnt_def(self, k, c, s, d, a, l):
self._fnt_def_real(k, c, s, d, a, l)
def _fnt_def_real(self, k, c, s, d, a, l):
n = self.file.read(a + l)
fontname = n[-l:].decode('ascii')
tfm = _tfmfile(fontname)
if tfm is None:
raise FileNotFoundError("missing font metrics file: %s" % fontname)
if c != 0 and tfm.checksum != 0 and c != tfm.checksum:
raise ValueError('tfm checksum mismatch: %s' % n)
vf = _vffile(fontname)
self.fonts[k] = DviFont(scale=s, tfm=tfm, texname=n, vf=vf)
@_dispatch(247, state=_dvistate.pre, args=('u1', 'u4', 'u4', 'u4', 'u1'))
def _pre(self, i, num, den, mag, k):
comment = self.file.read(k)
if i != 2:
raise ValueError("Unknown dvi format %d" % i)
if num != 25400000 or den != 7227 * 2**16:
raise ValueError("nonstandard units in dvi file")
# meaning: TeX always uses those exact values, so it
# should be enough for us to support those
# (There are 72.27 pt to an inch so 7227 pt =
# 7227 * 2**16 sp to 100 in. The numerator is multiplied
# by 10^5 to get units of 10**-7 meters.)
if mag != 1000:
raise ValueError("nonstandard magnification in dvi file")
# meaning: LaTeX seems to frown on setting \mag, so
# I think we can assume this is constant
self.state = _dvistate.outer
@_dispatch(248, state=_dvistate.outer)
def _post(self, _):
self.state = _dvistate.post_post
# TODO: actually read the postamble and finale?
# currently post_post just triggers closing the file
@_dispatch(249)
def _post_post(self, _):
raise NotImplementedError
@_dispatch(min=250, max=255)
def _malformed(self, offset):
raise ValueError("unknown command: byte %d", 250 + offset)
class DviFont(object):
"""
Encapsulation of a font that a DVI file can refer to.
This class holds a font's texname and size, supports comparison,
and knows the widths of glyphs in the same units as the AFM file.
There are also internal attributes (for use by dviread.py) that
are *not* used for comparison.
The size is in Adobe points (converted from TeX points).
Parameters
----------
scale : float
Factor by which the font is scaled from its natural size.
tfm : Tfm
TeX font metrics for this font
texname : bytes
Name of the font as used internally by TeX and friends, as an
ASCII bytestring. This is usually very different from any external
font names, and :class:`dviread.PsfontsMap` can be used to find
the external name of the font.
vf : Vf
A TeX "virtual font" file, or None if this font is not virtual.
Attributes
----------
texname : bytes
size : float
Size of the font in Adobe points, converted from the slightly
smaller TeX points.
widths : list
Widths of glyphs in glyph-space units, typically 1/1000ths of
the point size.
"""
__slots__ = ('texname', 'size', 'widths', '_scale', '_vf', '_tfm')
def __init__(self, scale, tfm, texname, vf):
if not isinstance(texname, bytes):
raise ValueError("texname must be a bytestring, got %s"
% type(texname))
self._scale = scale
self._tfm = tfm
self.texname = texname
self._vf = vf
self.size = scale * (72.0 / (72.27 * 2**16))
try:
nchars = max(tfm.width) + 1
except ValueError:
nchars = 0
self.widths = [(1000*tfm.width.get(char, 0)) >> 20
for char in range(nchars)]
def __eq__(self, other):
return (type(self) == type(other)
and self.texname == other.texname and self.size == other.size)
def __ne__(self, other):
return not self.__eq__(other)
def __repr__(self):
return "<{}: {}>".format(type(self).__name__, self.texname)
def _width_of(self, char):
"""Width of char in dvi units."""
width = self._tfm.width.get(char, None)
if width is not None:
return _mul2012(width, self._scale)
_log.debug('No width for char %d in font %s.', char, self.texname)
return 0
def _height_depth_of(self, char):
"""Height and depth of char in dvi units."""
result = []
for metric, name in ((self._tfm.height, "height"),
(self._tfm.depth, "depth")):
value = metric.get(char, None)
if value is None:
_log.debug('No %s for char %d in font %s',
name, char, self.texname)
result.append(0)
else:
result.append(_mul2012(value, self._scale))
return result
class Vf(Dvi):
r"""
A virtual font (\*.vf file) containing subroutines for dvi files.
Usage::
vf = Vf(filename)
glyph = vf[code]
glyph.text, glyph.boxes, glyph.width
Parameters
----------
filename : string or bytestring
Notes
-----
The virtual font format is a derivative of dvi:
http://mirrors.ctan.org/info/knuth/virtual-fonts
This class reuses some of the machinery of `Dvi`
but replaces the `_read` loop and dispatch mechanism.
"""
def __init__(self, filename):
Dvi.__init__(self, filename, 0)
try:
self._first_font = None
self._chars = {}
self._read()
finally:
self.close()
def __getitem__(self, code):
return self._chars[code]
def _read(self):
"""
Read one page from the file. Return True if successful,
False if there were no more pages.
"""
packet_char, packet_ends = None, None
packet_len, packet_width = None, None
while True:
byte = self.file.read(1)[0]
# If we are in a packet, execute the dvi instructions
if self.state is _dvistate.inpage:
byte_at = self.file.tell()-1
if byte_at == packet_ends:
self._finalize_packet(packet_char, packet_width)
packet_len, packet_char, packet_width = None, None, None
# fall through to out-of-packet code
elif byte_at > packet_ends:
raise ValueError("Packet length mismatch in vf file")
else:
if byte in (139, 140) or byte >= 243:
raise ValueError(
"Inappropriate opcode %d in vf file" % byte)
Dvi._dtable[byte](self, byte)
continue
# We are outside a packet
if byte < 242: # a short packet (length given by byte)
packet_len = byte
packet_char, packet_width = self._arg(1), self._arg(3)
packet_ends = self._init_packet(byte)
self.state = _dvistate.inpage
elif byte == 242: # a long packet
packet_len, packet_char, packet_width = \
[self._arg(x) for x in (4, 4, 4)]
self._init_packet(packet_len)
elif 243 <= byte <= 246:
k = self._arg(byte - 242, byte == 246)
c, s, d, a, l = [self._arg(x) for x in (4, 4, 4, 1, 1)]
self._fnt_def_real(k, c, s, d, a, l)
if self._first_font is None:
self._first_font = k
elif byte == 247: # preamble
i, k = self._arg(1), self._arg(1)
x = self.file.read(k)
cs, ds = self._arg(4), self._arg(4)
self._pre(i, x, cs, ds)
elif byte == 248: # postamble (just some number of 248s)
break
else:
raise ValueError("unknown vf opcode %d" % byte)
def _init_packet(self, pl):
if self.state != _dvistate.outer:
raise ValueError("Misplaced packet in vf file")
self.h, self.v, self.w, self.x, self.y, self.z = 0, 0, 0, 0, 0, 0
self.stack, self.text, self.boxes = [], [], []
self.f = self._first_font
return self.file.tell() + pl
def _finalize_packet(self, packet_char, packet_width):
self._chars[packet_char] = Page(
text=self.text, boxes=self.boxes, width=packet_width,
height=None, descent=None)
self.state = _dvistate.outer
def _pre(self, i, x, cs, ds):
if self.state is not _dvistate.pre:
raise ValueError("pre command in middle of vf file")
if i != 202:
raise ValueError("Unknown vf format %d" % i)
if len(x):
_log.debug('vf file comment: %s', x)
self.state = _dvistate.outer
# cs = checksum, ds = design size
def _fix2comp(num):
"""Convert from two's complement to negative."""
assert 0 <= num < 2**32
if num & 2**31:
return num - 2**32
else:
return num
def _mul2012(num1, num2):
"""Multiply two numbers in 20.12 fixed point format."""
# Separated into a function because >> has surprising precedence
return (num1*num2) >> 20
class Tfm(object):
"""
A TeX Font Metric file.
This implementation covers only the bare minimum needed by the Dvi class.
Parameters
----------
filename : string or bytestring
Attributes
----------
checksum : int
Used for verifying against the dvi file.
design_size : int
Design size of the font (unknown units)
width, height, depth : dict
Dimensions of each character, need to be scaled by the factor
specified in the dvi file. These are dicts because indexing may
not start from 0.
"""
__slots__ = ('checksum', 'design_size', 'width', 'height', 'depth')
def __init__(self, filename):
_log.debug('opening tfm file %s', filename)
with open(filename, 'rb') as file:
header1 = file.read(24)
lh, bc, ec, nw, nh, nd = \
struct.unpack('!6H', header1[2:14])
_log.debug('lh=%d, bc=%d, ec=%d, nw=%d, nh=%d, nd=%d',
lh, bc, ec, nw, nh, nd)
header2 = file.read(4*lh)
self.checksum, self.design_size = \
struct.unpack('!2I', header2[:8])
# there is also encoding information etc.
char_info = file.read(4*(ec-bc+1))
widths = file.read(4*nw)
heights = file.read(4*nh)
depths = file.read(4*nd)
self.width, self.height, self.depth = {}, {}, {}
widths, heights, depths = \
[struct.unpack('!%dI' % (len(x)/4), x)
for x in (widths, heights, depths)]
for idx, char in enumerate(range(bc, ec+1)):
byte0 = char_info[4*idx]
byte1 = char_info[4*idx+1]
self.width[char] = _fix2comp(widths[byte0])
self.height[char] = _fix2comp(heights[byte1 >> 4])
self.depth[char] = _fix2comp(depths[byte1 & 0xf])
PsFont = namedtuple('Font', 'texname psname effects encoding filename')
class PsfontsMap(object):
"""
A psfonts.map formatted file, mapping TeX fonts to PS fonts.
Usage::
>>> map = PsfontsMap(find_tex_file('pdftex.map'))
>>> entry = map[b'ptmbo8r']
>>> entry.texname
b'ptmbo8r'
>>> entry.psname
b'Times-Bold'
>>> entry.encoding
'/usr/local/texlive/2008/texmf-dist/fonts/enc/dvips/base/8r.enc'
>>> entry.effects
{'slant': 0.16700000000000001}
>>> entry.filename
Parameters
----------
filename : string or bytestring
Notes
-----
For historical reasons, TeX knows many Type-1 fonts by different
names than the outside world. (For one thing, the names have to
fit in eight characters.) Also, TeX's native fonts are not Type-1
but Metafont, which is nontrivial to convert to PostScript except
as a bitmap. While high-quality conversions to Type-1 format exist
and are shipped with modern TeX distributions, we need to know
which Type-1 fonts are the counterparts of which native fonts. For
these reasons a mapping is needed from internal font names to font
file names.
A texmf tree typically includes mapping files called e.g.
:file:`psfonts.map`, :file:`pdftex.map`, or :file:`dvipdfm.map`.
The file :file:`psfonts.map` is used by :program:`dvips`,
:file:`pdftex.map` by :program:`pdfTeX`, and :file:`dvipdfm.map`
by :program:`dvipdfm`. :file:`psfonts.map` might avoid embedding
the 35 PostScript fonts (i.e., have no filename for them, as in
the Times-Bold example above), while the pdf-related files perhaps
only avoid the "Base 14" pdf fonts. But the user may have
configured these files differently.
"""
__slots__ = ('_font', '_filename')
# Create a filename -> PsfontsMap cache, so that calling
# `PsfontsMap(filename)` with the same filename a second time immediately
# returns the same object.
@lru_cache()
def __new__(cls, filename):
self = object.__new__(cls)
self._font = {}
self._filename = os.fsdecode(filename)
with open(filename, 'rb') as file:
self._parse(file)
return self
def __getitem__(self, texname):
assert isinstance(texname, bytes)
try:
result = self._font[texname]
except KeyError:
fmt = ('A PostScript file for the font whose TeX name is "{0}" '
'could not be found in the file "{1}". The dviread module '
'can only handle fonts that have an associated PostScript '
'font file. '
'This problem can often be solved by installing '
'a suitable PostScript font package in your (TeX) '
'package manager.')
msg = fmt.format(texname.decode('ascii'), self._filename)
msg = textwrap.fill(msg, break_on_hyphens=False,
break_long_words=False)
_log.info(msg)
raise
fn, enc = result.filename, result.encoding
if fn is not None and not fn.startswith(b'/'):
fn = find_tex_file(fn)
if enc is not None and not enc.startswith(b'/'):
enc = find_tex_file(result.encoding)
return result._replace(filename=fn, encoding=enc)
def _parse(self, file):
"""
Parse the font mapping file.
The format is, AFAIK: texname fontname [effects and filenames]
Effects are PostScript snippets like ".177 SlantFont",
filenames begin with one or two less-than signs. A filename
ending in enc is an encoding file, other filenames are font
files. This can be overridden with a left bracket: <[foobar
indicates an encoding file named foobar.
There is some difference between <foo.pfb and <<bar.pfb in
subsetting, but I have no example of << in my TeX installation.
"""
# If the map file specifies multiple encodings for a font, we
# follow pdfTeX in choosing the last one specified. Such
# entries are probably mistakes but they have occurred.
# http://tex.stackexchange.com/questions/10826/
# http://article.gmane.org/gmane.comp.tex.pdftex/4914
empty_re = re.compile(br'%|\s*$')
word_re = re.compile(
br'''(?x) (?:
"<\[ (?P<enc1> [^"]+ )" | # quoted encoding marked by [
"< (?P<enc2> [^"]+.enc)" | # quoted encoding, ends in .enc
"<<? (?P<file1> [^"]+ )" | # quoted font file name
" (?P<eff1> [^"]+ )" | # quoted effects or font name
<\[ (?P<enc3> \S+ ) | # encoding marked by [
< (?P<enc4> \S+ .enc) | # encoding, ends in .enc
<<? (?P<file2> \S+ ) | # font file name
(?P<eff2> \S+ ) # effects or font name
)''')
effects_re = re.compile(
br'''(?x) (?P<slant> -?[0-9]*(?:\.[0-9]+)) \s* SlantFont
| (?P<extend>-?[0-9]*(?:\.[0-9]+)) \s* ExtendFont''')
lines = (line.strip()
for line in file
if not empty_re.match(line))
for line in lines:
effects, encoding, filename = b'', None, None
words = word_re.finditer(line)
# The named groups are mutually exclusive and are
# referenced below at an estimated order of probability of
# occurrence based on looking at my copy of pdftex.map.
# The font names are probably unquoted:
w = next(words)
texname = w.group('eff2') or w.group('eff1')
w = next(words)
psname = w.group('eff2') or w.group('eff1')
for w in words:
# Any effects are almost always quoted:
eff = w.group('eff1') or w.group('eff2')
if eff:
effects = eff
continue
# Encoding files usually have the .enc suffix
# and almost never need quoting:
enc = (w.group('enc4') or w.group('enc3') or
w.group('enc2') or w.group('enc1'))
if enc:
if encoding is not None:
_log.debug('Multiple encodings for %s = %s',
texname, psname)
encoding = enc
continue
# File names are probably unquoted:
filename = w.group('file2') or w.group('file1')
effects_dict = {}
for match in effects_re.finditer(effects):
slant = match.group('slant')
if slant:
effects_dict['slant'] = float(slant)
else:
effects_dict['extend'] = float(match.group('extend'))
self._font[texname] = PsFont(
texname=texname, psname=psname, effects=effects_dict,
encoding=encoding, filename=filename)
class Encoding(object):
r"""
Parses a \*.enc file referenced from a psfonts.map style file.
The format this class understands is a very limited subset of
PostScript.
Usage (subject to change)::
for name in Encoding(filename):
whatever(name)
Parameters
----------
filename : string or bytestring
Attributes
----------
encoding : list
List of character names
"""
__slots__ = ('encoding',)
def __init__(self, filename):
with open(filename, 'rb') as file:
_log.debug('Parsing TeX encoding %s', filename)
self.encoding = self._parse(file)
_log.debug('Result: %s', self.encoding)
def __iter__(self):
yield from self.encoding
@staticmethod
def _parse(file):
lines = (line.split(b'%', 1)[0].strip() for line in file)
data = b''.join(lines)
beginning = data.find(b'[')
if beginning < 0:
raise ValueError("Cannot locate beginning of encoding in {}"
.format(file))
data = data[beginning:]
end = data.find(b']')
if end < 0:
raise ValueError("Cannot locate end of encoding in {}"
.format(file))
data = data[:end]
return re.findall(br'/([^][{}<>\s]+)', data)
# Note: this function should ultimately replace the Encoding class, which
# appears to be mostly broken: because it uses b''.join(), there is no
# whitespace left between glyph names (only slashes) so the final re.findall
# returns a single string with all glyph names. However this does not appear
# to bother backend_pdf, so that needs to be investigated more. (The fixed
# version below is necessary for textpath/backend_svg, though.)
def _parse_enc(path):
r"""
Parses a \*.enc file referenced from a psfonts.map style file.
The format this class understands is a very limited subset of PostScript.
Parameters
----------
path : os.PathLike
Returns
-------
encoding : list
The nth entry of the list is the PostScript glyph name of the nth
glyph.
"""
with open(path, encoding="ascii") as file:
no_comments = "\n".join(line.split("%")[0].rstrip() for line in file)
array = re.search(r"(?s)\[(.*)\]", no_comments).group(1)
lines = [line for line in array.split("\n") if line]
if all(line.startswith("/") for line in lines):
return [line[1:] for line in lines]
else:
raise ValueError(
"Failed to parse {} as Postscript encoding".format(path))
@lru_cache()
def find_tex_file(filename, format=None):
"""
Find a file in the texmf tree.
Calls :program:`kpsewhich` which is an interface to the kpathsea
library [1]_. Most existing TeX distributions on Unix-like systems use
kpathsea. It is also available as part of MikTeX, a popular
distribution on Windows.
*If the file is not found, an empty string is returned*.
Parameters
----------
filename : string or bytestring
format : string or bytestring
Used as the value of the `--format` option to :program:`kpsewhich`.
Could be e.g. 'tfm' or 'vf' to limit the search to that type of files.
References
----------
.. [1] `Kpathsea documentation <http://www.tug.org/kpathsea/>`_
The library that :program:`kpsewhich` is part of.
"""
# we expect these to always be ascii encoded, but use utf-8
# out of caution
if isinstance(filename, bytes):
filename = filename.decode('utf-8', errors='replace')
if isinstance(format, bytes):
format = format.decode('utf-8', errors='replace')
if os.name == 'nt':
# On Windows only, kpathsea can use utf-8 for cmd args and output.
# The `command_line_encoding` environment variable is set to force it
# to always use utf-8 encoding. See mpl issue #11848 for more info.
kwargs = dict(env=dict(os.environ, command_line_encoding='utf-8'))
else:
kwargs = {}
cmd = ['kpsewhich']
if format is not None:
cmd += ['--format=' + format]
cmd += [filename]
try:
result = cbook._check_and_log_subprocess(cmd, _log, **kwargs)
except RuntimeError:
return ''
if os.name == 'nt':
return result.decode('utf-8').rstrip('\r\n')
else:
return os.fsdecode(result).rstrip('\n')
@lru_cache()
def _fontfile(cls, suffix, texname):
filename = find_tex_file(texname + suffix)
return cls(filename) if filename else None
_tfmfile = partial(_fontfile, Tfm, ".tfm")
_vffile = partial(_fontfile, Vf, ".vf")
if __name__ == '__main__':
from argparse import ArgumentParser
import itertools
parser = ArgumentParser()
parser.add_argument("filename")
parser.add_argument("dpi", nargs="?", type=float, default=None)
args = parser.parse_args()
with Dvi(args.filename, args.dpi) as dvi:
fontmap = PsfontsMap(find_tex_file('pdftex.map'))
for page in dvi:
print('=== new page ===')
for font, group in itertools.groupby(
page.text, lambda text: text.font):
print('font', font.texname, 'scaled', font._scale / 2 ** 20)
for text in group:
print(text.x, text.y, text.glyph,
chr(text.glyph) if chr(text.glyph).isprintable()
else ".",
text.width)
for x, y, w, h in page.boxes:
print(x, y, 'BOX', w, h)
|
0a6285456ea65c226a8194906a234e486fd5527f56892c791eb83ee2a2889f5e
|
"""
font data tables for truetype and afm computer modern fonts
"""
latex_to_bakoma = {
'\\__sqrt__' : ('cmex10', 0x70),
'\\bigcap' : ('cmex10', 0x5c),
'\\bigcup' : ('cmex10', 0x5b),
'\\bigodot' : ('cmex10', 0x4b),
'\\bigoplus' : ('cmex10', 0x4d),
'\\bigotimes' : ('cmex10', 0x4f),
'\\biguplus' : ('cmex10', 0x5d),
'\\bigvee' : ('cmex10', 0x5f),
'\\bigwedge' : ('cmex10', 0x5e),
'\\coprod' : ('cmex10', 0x61),
'\\int' : ('cmex10', 0x5a),
'\\langle' : ('cmex10', 0xad),
'\\leftangle' : ('cmex10', 0xad),
'\\leftbrace' : ('cmex10', 0xa9),
'\\oint' : ('cmex10', 0x49),
'\\prod' : ('cmex10', 0x59),
'\\rangle' : ('cmex10', 0xae),
'\\rightangle' : ('cmex10', 0xae),
'\\rightbrace' : ('cmex10', 0xaa),
'\\sum' : ('cmex10', 0x58),
'\\widehat' : ('cmex10', 0x62),
'\\widetilde' : ('cmex10', 0x65),
'\\{' : ('cmex10', 0xa9),
'\\}' : ('cmex10', 0xaa),
'{' : ('cmex10', 0xa9),
'}' : ('cmex10', 0xaa),
',' : ('cmmi10', 0x3b),
'.' : ('cmmi10', 0x3a),
'/' : ('cmmi10', 0x3d),
'<' : ('cmmi10', 0x3c),
'>' : ('cmmi10', 0x3e),
'\\alpha' : ('cmmi10', 0xae),
'\\beta' : ('cmmi10', 0xaf),
'\\chi' : ('cmmi10', 0xc2),
'\\combiningrightarrowabove' : ('cmmi10', 0x7e),
'\\delta' : ('cmmi10', 0xb1),
'\\ell' : ('cmmi10', 0x60),
'\\epsilon' : ('cmmi10', 0xb2),
'\\eta' : ('cmmi10', 0xb4),
'\\flat' : ('cmmi10', 0x5b),
'\\frown' : ('cmmi10', 0x5f),
'\\gamma' : ('cmmi10', 0xb0),
'\\imath' : ('cmmi10', 0x7b),
'\\iota' : ('cmmi10', 0xb6),
'\\jmath' : ('cmmi10', 0x7c),
'\\kappa' : ('cmmi10', 0x2219),
'\\lambda' : ('cmmi10', 0xb8),
'\\leftharpoondown' : ('cmmi10', 0x29),
'\\leftharpoonup' : ('cmmi10', 0x28),
'\\mu' : ('cmmi10', 0xb9),
'\\natural' : ('cmmi10', 0x5c),
'\\nu' : ('cmmi10', 0xba),
'\\omega' : ('cmmi10', 0x21),
'\\phi' : ('cmmi10', 0xc1),
'\\pi' : ('cmmi10', 0xbc),
'\\psi' : ('cmmi10', 0xc3),
'\\rho' : ('cmmi10', 0xbd),
'\\rightharpoondown' : ('cmmi10', 0x2b),
'\\rightharpoonup' : ('cmmi10', 0x2a),
'\\sharp' : ('cmmi10', 0x5d),
'\\sigma' : ('cmmi10', 0xbe),
'\\smile' : ('cmmi10', 0x5e),
'\\tau' : ('cmmi10', 0xbf),
'\\theta' : ('cmmi10', 0xb5),
'\\triangleleft' : ('cmmi10', 0x2f),
'\\triangleright' : ('cmmi10', 0x2e),
'\\upsilon' : ('cmmi10', 0xc0),
'\\varepsilon' : ('cmmi10', 0x22),
'\\varphi' : ('cmmi10', 0x27),
'\\varrho' : ('cmmi10', 0x25),
'\\varsigma' : ('cmmi10', 0x26),
'\\vartheta' : ('cmmi10', 0x23),
'\\wp' : ('cmmi10', 0x7d),
'\\xi' : ('cmmi10', 0xbb),
'\\zeta' : ('cmmi10', 0xb3),
'!' : ('cmr10', 0x21),
'%' : ('cmr10', 0x25),
'&' : ('cmr10', 0x26),
'(' : ('cmr10', 0x28),
')' : ('cmr10', 0x29),
'+' : ('cmr10', 0x2b),
'0' : ('cmr10', 0x30),
'1' : ('cmr10', 0x31),
'2' : ('cmr10', 0x32),
'3' : ('cmr10', 0x33),
'4' : ('cmr10', 0x34),
'5' : ('cmr10', 0x35),
'6' : ('cmr10', 0x36),
'7' : ('cmr10', 0x37),
'8' : ('cmr10', 0x38),
'9' : ('cmr10', 0x39),
':' : ('cmr10', 0x3a),
';' : ('cmr10', 0x3b),
'=' : ('cmr10', 0x3d),
'?' : ('cmr10', 0x3f),
'@' : ('cmr10', 0x40),
'[' : ('cmr10', 0x5b),
'\\#' : ('cmr10', 0x23),
'\\$' : ('cmr10', 0x24),
'\\%' : ('cmr10', 0x25),
'\\Delta' : ('cmr10', 0xa2),
'\\Gamma' : ('cmr10', 0xa1),
'\\Lambda' : ('cmr10', 0xa4),
'\\Omega' : ('cmr10', 0xad),
'\\Phi' : ('cmr10', 0xa9),
'\\Pi' : ('cmr10', 0xa6),
'\\Psi' : ('cmr10', 0xaa),
'\\Sigma' : ('cmr10', 0xa7),
'\\Theta' : ('cmr10', 0xa3),
'\\Upsilon' : ('cmr10', 0xa8),
'\\Xi' : ('cmr10', 0xa5),
'\\circumflexaccent' : ('cmr10', 0x5e),
'\\combiningacuteaccent' : ('cmr10', 0xb6),
'\\combiningbreve' : ('cmr10', 0xb8),
'\\combiningdiaeresis' : ('cmr10', 0xc4),
'\\combiningdotabove' : ('cmr10', 0x5f),
'\\combininggraveaccent' : ('cmr10', 0xb5),
'\\combiningoverline' : ('cmr10', 0xb9),
'\\combiningtilde' : ('cmr10', 0x7e),
'\\leftbracket' : ('cmr10', 0x5b),
'\\leftparen' : ('cmr10', 0x28),
'\\rightbracket' : ('cmr10', 0x5d),
'\\rightparen' : ('cmr10', 0x29),
'\\widebar' : ('cmr10', 0xb9),
']' : ('cmr10', 0x5d),
'*' : ('cmsy10', 0xa4),
'-' : ('cmsy10', 0xa1),
'\\Downarrow' : ('cmsy10', 0x2b),
'\\Im' : ('cmsy10', 0x3d),
'\\Leftarrow' : ('cmsy10', 0x28),
'\\Leftrightarrow' : ('cmsy10', 0x2c),
'\\P' : ('cmsy10', 0x7b),
'\\Re' : ('cmsy10', 0x3c),
'\\Rightarrow' : ('cmsy10', 0x29),
'\\S' : ('cmsy10', 0x78),
'\\Uparrow' : ('cmsy10', 0x2a),
'\\Updownarrow' : ('cmsy10', 0x6d),
'\\Vert' : ('cmsy10', 0x6b),
'\\aleph' : ('cmsy10', 0x40),
'\\approx' : ('cmsy10', 0xbc),
'\\ast' : ('cmsy10', 0xa4),
'\\asymp' : ('cmsy10', 0xb3),
'\\backslash' : ('cmsy10', 0x6e),
'\\bigcirc' : ('cmsy10', 0xb0),
'\\bigtriangledown' : ('cmsy10', 0x35),
'\\bigtriangleup' : ('cmsy10', 0x34),
'\\bot' : ('cmsy10', 0x3f),
'\\bullet' : ('cmsy10', 0xb2),
'\\cap' : ('cmsy10', 0x5c),
'\\cdot' : ('cmsy10', 0xa2),
'\\circ' : ('cmsy10', 0xb1),
'\\clubsuit' : ('cmsy10', 0x7c),
'\\cup' : ('cmsy10', 0x5b),
'\\dag' : ('cmsy10', 0x79),
'\\dashv' : ('cmsy10', 0x61),
'\\ddag' : ('cmsy10', 0x7a),
'\\diamond' : ('cmsy10', 0xa6),
'\\diamondsuit' : ('cmsy10', 0x7d),
'\\div' : ('cmsy10', 0xa5),
'\\downarrow' : ('cmsy10', 0x23),
'\\emptyset' : ('cmsy10', 0x3b),
'\\equiv' : ('cmsy10', 0xb4),
'\\exists' : ('cmsy10', 0x39),
'\\forall' : ('cmsy10', 0x38),
'\\geq' : ('cmsy10', 0xb8),
'\\gg' : ('cmsy10', 0xc0),
'\\heartsuit' : ('cmsy10', 0x7e),
'\\in' : ('cmsy10', 0x32),
'\\infty' : ('cmsy10', 0x31),
'\\lbrace' : ('cmsy10', 0x66),
'\\lceil' : ('cmsy10', 0x64),
'\\leftarrow' : ('cmsy10', 0xc3),
'\\leftrightarrow' : ('cmsy10', 0x24),
'\\leq' : ('cmsy10', 0x2219),
'\\lfloor' : ('cmsy10', 0x62),
'\\ll' : ('cmsy10', 0xbf),
'\\mid' : ('cmsy10', 0x6a),
'\\mp' : ('cmsy10', 0xa8),
'\\nabla' : ('cmsy10', 0x72),
'\\nearrow' : ('cmsy10', 0x25),
'\\neg' : ('cmsy10', 0x3a),
'\\ni' : ('cmsy10', 0x33),
'\\nwarrow' : ('cmsy10', 0x2d),
'\\odot' : ('cmsy10', 0xaf),
'\\ominus' : ('cmsy10', 0xaa),
'\\oplus' : ('cmsy10', 0xa9),
'\\oslash' : ('cmsy10', 0xae),
'\\otimes' : ('cmsy10', 0xad),
'\\pm' : ('cmsy10', 0xa7),
'\\prec' : ('cmsy10', 0xc1),
'\\preceq' : ('cmsy10', 0xb9),
'\\prime' : ('cmsy10', 0x30),
'\\propto' : ('cmsy10', 0x2f),
'\\rbrace' : ('cmsy10', 0x67),
'\\rceil' : ('cmsy10', 0x65),
'\\rfloor' : ('cmsy10', 0x63),
'\\rightarrow' : ('cmsy10', 0x21),
'\\searrow' : ('cmsy10', 0x26),
'\\sim' : ('cmsy10', 0xbb),
'\\simeq' : ('cmsy10', 0x27),
'\\slash' : ('cmsy10', 0x36),
'\\spadesuit' : ('cmsy10', 0xc4),
'\\sqcap' : ('cmsy10', 0x75),
'\\sqcup' : ('cmsy10', 0x74),
'\\sqsubseteq' : ('cmsy10', 0x76),
'\\sqsupseteq' : ('cmsy10', 0x77),
'\\subset' : ('cmsy10', 0xbd),
'\\subseteq' : ('cmsy10', 0xb5),
'\\succ' : ('cmsy10', 0xc2),
'\\succeq' : ('cmsy10', 0xba),
'\\supset' : ('cmsy10', 0xbe),
'\\supseteq' : ('cmsy10', 0xb6),
'\\swarrow' : ('cmsy10', 0x2e),
'\\times' : ('cmsy10', 0xa3),
'\\to' : ('cmsy10', 0x21),
'\\top' : ('cmsy10', 0x3e),
'\\uparrow' : ('cmsy10', 0x22),
'\\updownarrow' : ('cmsy10', 0x6c),
'\\uplus' : ('cmsy10', 0x5d),
'\\vdash' : ('cmsy10', 0x60),
'\\vee' : ('cmsy10', 0x5f),
'\\vert' : ('cmsy10', 0x6a),
'\\wedge' : ('cmsy10', 0x5e),
'\\wr' : ('cmsy10', 0x6f),
'\\|' : ('cmsy10', 0x6b),
'|' : ('cmsy10', 0x6a),
'\\_' : ('cmtt10', 0x5f)
}
latex_to_cmex = {
r'\__sqrt__' : 112,
r'\bigcap' : 92,
r'\bigcup' : 91,
r'\bigodot' : 75,
r'\bigoplus' : 77,
r'\bigotimes' : 79,
r'\biguplus' : 93,
r'\bigvee' : 95,
r'\bigwedge' : 94,
r'\coprod' : 97,
r'\int' : 90,
r'\leftangle' : 173,
r'\leftbrace' : 169,
r'\oint' : 73,
r'\prod' : 89,
r'\rightangle' : 174,
r'\rightbrace' : 170,
r'\sum' : 88,
r'\widehat' : 98,
r'\widetilde' : 101,
}
latex_to_standard = {
r'\cong' : ('psyr', 64),
r'\Delta' : ('psyr', 68),
r'\Phi' : ('psyr', 70),
r'\Gamma' : ('psyr', 89),
r'\alpha' : ('psyr', 97),
r'\beta' : ('psyr', 98),
r'\chi' : ('psyr', 99),
r'\delta' : ('psyr', 100),
r'\varepsilon' : ('psyr', 101),
r'\phi' : ('psyr', 102),
r'\gamma' : ('psyr', 103),
r'\eta' : ('psyr', 104),
r'\iota' : ('psyr', 105),
r'\varpsi' : ('psyr', 106),
r'\kappa' : ('psyr', 108),
r'\nu' : ('psyr', 110),
r'\pi' : ('psyr', 112),
r'\theta' : ('psyr', 113),
r'\rho' : ('psyr', 114),
r'\sigma' : ('psyr', 115),
r'\tau' : ('psyr', 116),
r'\upsilon' : ('psyr', 117),
r'\varpi' : ('psyr', 118),
r'\omega' : ('psyr', 119),
r'\xi' : ('psyr', 120),
r'\psi' : ('psyr', 121),
r'\zeta' : ('psyr', 122),
r'\sim' : ('psyr', 126),
r'\leq' : ('psyr', 163),
r'\infty' : ('psyr', 165),
r'\clubsuit' : ('psyr', 167),
r'\diamondsuit' : ('psyr', 168),
r'\heartsuit' : ('psyr', 169),
r'\spadesuit' : ('psyr', 170),
r'\leftrightarrow' : ('psyr', 171),
r'\leftarrow' : ('psyr', 172),
r'\uparrow' : ('psyr', 173),
r'\rightarrow' : ('psyr', 174),
r'\downarrow' : ('psyr', 175),
r'\pm' : ('psyr', 176),
r'\geq' : ('psyr', 179),
r'\times' : ('psyr', 180),
r'\propto' : ('psyr', 181),
r'\partial' : ('psyr', 182),
r'\bullet' : ('psyr', 183),
r'\div' : ('psyr', 184),
r'\neq' : ('psyr', 185),
r'\equiv' : ('psyr', 186),
r'\approx' : ('psyr', 187),
r'\ldots' : ('psyr', 188),
r'\aleph' : ('psyr', 192),
r'\Im' : ('psyr', 193),
r'\Re' : ('psyr', 194),
r'\wp' : ('psyr', 195),
r'\otimes' : ('psyr', 196),
r'\oplus' : ('psyr', 197),
r'\oslash' : ('psyr', 198),
r'\cap' : ('psyr', 199),
r'\cup' : ('psyr', 200),
r'\supset' : ('psyr', 201),
r'\supseteq' : ('psyr', 202),
r'\subset' : ('psyr', 204),
r'\subseteq' : ('psyr', 205),
r'\in' : ('psyr', 206),
r'\notin' : ('psyr', 207),
r'\angle' : ('psyr', 208),
r'\nabla' : ('psyr', 209),
r'\textregistered' : ('psyr', 210),
r'\copyright' : ('psyr', 211),
r'\texttrademark' : ('psyr', 212),
r'\Pi' : ('psyr', 213),
r'\prod' : ('psyr', 213),
r'\surd' : ('psyr', 214),
r'\__sqrt__' : ('psyr', 214),
r'\cdot' : ('psyr', 215),
r'\urcorner' : ('psyr', 216),
r'\vee' : ('psyr', 217),
r'\wedge' : ('psyr', 218),
r'\Leftrightarrow' : ('psyr', 219),
r'\Leftarrow' : ('psyr', 220),
r'\Uparrow' : ('psyr', 221),
r'\Rightarrow' : ('psyr', 222),
r'\Downarrow' : ('psyr', 223),
r'\Diamond' : ('psyr', 224),
r'\Sigma' : ('psyr', 229),
r'\sum' : ('psyr', 229),
r'\forall' : ('psyr', 34),
r'\exists' : ('psyr', 36),
r'\lceil' : ('psyr', 233),
r'\lbrace' : ('psyr', 123),
r'\Psi' : ('psyr', 89),
r'\bot' : ('psyr', 0o136),
r'\Omega' : ('psyr', 0o127),
r'\leftbracket' : ('psyr', 0o133),
r'\rightbracket' : ('psyr', 0o135),
r'\leftbrace' : ('psyr', 123),
r'\leftparen' : ('psyr', 0o50),
r'\prime' : ('psyr', 0o242),
r'\sharp' : ('psyr', 0o43),
r'\slash' : ('psyr', 0o57),
r'\Lamda' : ('psyr', 0o114),
r'\neg' : ('psyr', 0o330),
r'\Upsilon' : ('psyr', 0o241),
r'\rightbrace' : ('psyr', 0o175),
r'\rfloor' : ('psyr', 0o373),
r'\lambda' : ('psyr', 0o154),
r'\to' : ('psyr', 0o256),
r'\Xi' : ('psyr', 0o130),
r'\emptyset' : ('psyr', 0o306),
r'\lfloor' : ('psyr', 0o353),
r'\rightparen' : ('psyr', 0o51),
r'\rceil' : ('psyr', 0o371),
r'\ni' : ('psyr', 0o47),
r'\epsilon' : ('psyr', 0o145),
r'\Theta' : ('psyr', 0o121),
r'\langle' : ('psyr', 0o341),
r'\leftangle' : ('psyr', 0o341),
r'\rangle' : ('psyr', 0o361),
r'\rightangle' : ('psyr', 0o361),
r'\rbrace' : ('psyr', 0o175),
r'\circ' : ('psyr', 0o260),
r'\diamond' : ('psyr', 0o340),
r'\mu' : ('psyr', 0o155),
r'\mid' : ('psyr', 0o352),
r'\imath' : ('pncri8a', 105),
r'\%' : ('pncr8a', 37),
r'\$' : ('pncr8a', 36),
r'\{' : ('pncr8a', 123),
r'\}' : ('pncr8a', 125),
r'\backslash' : ('pncr8a', 92),
r'\ast' : ('pncr8a', 42),
r'\#' : ('pncr8a', 35),
r'\circumflexaccent' : ('pncri8a', 124), # for \hat
r'\combiningbreve' : ('pncri8a', 81), # for \breve
r'\combininggraveaccent' : ('pncri8a', 114), # for \grave
r'\combiningacuteaccent' : ('pncri8a', 63), # for \accute
r'\combiningdiaeresis' : ('pncri8a', 91), # for \ddot
r'\combiningtilde' : ('pncri8a', 75), # for \tilde
r'\combiningrightarrowabove' : ('pncri8a', 110), # for \vec
r'\combiningdotabove' : ('pncri8a', 26), # for \dot
}
# Automatically generated.
type12uni = {
'uni24C8' : 9416,
'aring' : 229,
'uni22A0' : 8864,
'uni2292' : 8850,
'quotedblright' : 8221,
'uni03D2' : 978,
'uni2215' : 8725,
'uni03D0' : 976,
'V' : 86,
'dollar' : 36,
'uni301E' : 12318,
'uni03D5' : 981,
'four' : 52,
'uni25A0' : 9632,
'uni013C' : 316,
'uni013B' : 315,
'uni013E' : 318,
'Yacute' : 221,
'uni25DE' : 9694,
'uni013F' : 319,
'uni255A' : 9562,
'uni2606' : 9734,
'uni0180' : 384,
'uni22B7' : 8887,
'uni044F' : 1103,
'uni22B5' : 8885,
'uni22B4' : 8884,
'uni22AE' : 8878,
'uni22B2' : 8882,
'uni22B1' : 8881,
'uni22B0' : 8880,
'uni25CD' : 9677,
'uni03CE' : 974,
'uni03CD' : 973,
'uni03CC' : 972,
'uni03CB' : 971,
'uni03CA' : 970,
'uni22B8' : 8888,
'uni22C9' : 8905,
'uni0449' : 1097,
'uni20DD' : 8413,
'uni20DC' : 8412,
'uni20DB' : 8411,
'uni2231' : 8753,
'uni25CF' : 9679,
'uni306E' : 12398,
'uni03D1' : 977,
'uni01A1' : 417,
'uni20D7' : 8407,
'uni03D6' : 982,
'uni2233' : 8755,
'uni20D2' : 8402,
'uni20D1' : 8401,
'uni20D0' : 8400,
'P' : 80,
'uni22BE' : 8894,
'uni22BD' : 8893,
'uni22BC' : 8892,
'uni22BB' : 8891,
'underscore' : 95,
'uni03C8' : 968,
'uni03C7' : 967,
'uni0328' : 808,
'uni03C5' : 965,
'uni03C4' : 964,
'uni03C3' : 963,
'uni03C2' : 962,
'uni03C1' : 961,
'uni03C0' : 960,
'uni2010' : 8208,
'uni0130' : 304,
'uni0133' : 307,
'uni0132' : 306,
'uni0135' : 309,
'uni0134' : 308,
'uni0137' : 311,
'uni0136' : 310,
'uni0139' : 313,
'uni0138' : 312,
'uni2244' : 8772,
'uni229A' : 8858,
'uni2571' : 9585,
'uni0278' : 632,
'uni2239' : 8761,
'p' : 112,
'uni3019' : 12313,
'uni25CB' : 9675,
'uni03DB' : 987,
'uni03DC' : 988,
'uni03DA' : 986,
'uni03DF' : 991,
'uni03DD' : 989,
'uni013D' : 317,
'uni220A' : 8714,
'uni220C' : 8716,
'uni220B' : 8715,
'uni220E' : 8718,
'uni220D' : 8717,
'uni220F' : 8719,
'uni22CC' : 8908,
'Otilde' : 213,
'uni25E5' : 9701,
'uni2736' : 10038,
'perthousand' : 8240,
'zero' : 48,
'uni279B' : 10139,
'dotlessi' : 305,
'uni2279' : 8825,
'Scaron' : 352,
'zcaron' : 382,
'uni21D8' : 8664,
'egrave' : 232,
'uni0271' : 625,
'uni01AA' : 426,
'uni2332' : 9010,
'section' : 167,
'uni25E4' : 9700,
'Icircumflex' : 206,
'ntilde' : 241,
'uni041E' : 1054,
'ampersand' : 38,
'uni041C' : 1052,
'uni041A' : 1050,
'uni22AB' : 8875,
'uni21DB' : 8667,
'dotaccent' : 729,
'uni0416' : 1046,
'uni0417' : 1047,
'uni0414' : 1044,
'uni0415' : 1045,
'uni0412' : 1042,
'uni0413' : 1043,
'degree' : 176,
'uni0411' : 1041,
'K' : 75,
'uni25EB' : 9707,
'uni25EF' : 9711,
'uni0418' : 1048,
'uni0419' : 1049,
'uni2263' : 8803,
'uni226E' : 8814,
'uni2251' : 8785,
'uni02C8' : 712,
'uni2262' : 8802,
'acircumflex' : 226,
'uni22B3' : 8883,
'uni2261' : 8801,
'uni2394' : 9108,
'Aring' : 197,
'uni2260' : 8800,
'uni2254' : 8788,
'uni0436' : 1078,
'uni2267' : 8807,
'k' : 107,
'uni22C8' : 8904,
'uni226A' : 8810,
'uni231F' : 8991,
'smalltilde' : 732,
'uni2201' : 8705,
'uni2200' : 8704,
'uni2203' : 8707,
'uni02BD' : 701,
'uni2205' : 8709,
'uni2204' : 8708,
'Agrave' : 192,
'uni2206' : 8710,
'uni2209' : 8713,
'uni2208' : 8712,
'uni226D' : 8813,
'uni2264' : 8804,
'uni263D' : 9789,
'uni2258' : 8792,
'uni02D3' : 723,
'uni02D2' : 722,
'uni02D1' : 721,
'uni02D0' : 720,
'uni25E1' : 9697,
'divide' : 247,
'uni02D5' : 725,
'uni02D4' : 724,
'ocircumflex' : 244,
'uni2524' : 9508,
'uni043A' : 1082,
'uni24CC' : 9420,
'asciitilde' : 126,
'uni22B9' : 8889,
'uni24D2' : 9426,
'uni211E' : 8478,
'uni211D' : 8477,
'uni24DD' : 9437,
'uni211A' : 8474,
'uni211C' : 8476,
'uni211B' : 8475,
'uni25C6' : 9670,
'uni017F' : 383,
'uni017A' : 378,
'uni017C' : 380,
'uni017B' : 379,
'uni0346' : 838,
'uni22F1' : 8945,
'uni22F0' : 8944,
'two' : 50,
'uni2298' : 8856,
'uni24D1' : 9425,
'E' : 69,
'uni025D' : 605,
'scaron' : 353,
'uni2322' : 8994,
'uni25E3' : 9699,
'uni22BF' : 8895,
'F' : 70,
'uni0440' : 1088,
'uni255E' : 9566,
'uni22BA' : 8890,
'uni0175' : 373,
'uni0174' : 372,
'uni0177' : 375,
'uni0176' : 374,
'bracketleft' : 91,
'uni0170' : 368,
'uni0173' : 371,
'uni0172' : 370,
'asciicircum' : 94,
'uni0179' : 377,
'uni2590' : 9616,
'uni25E2' : 9698,
'uni2119' : 8473,
'uni2118' : 8472,
'uni25CC' : 9676,
'f' : 102,
'ordmasculine' : 186,
'uni229B' : 8859,
'uni22A1' : 8865,
'uni2111' : 8465,
'uni2110' : 8464,
'uni2113' : 8467,
'uni2112' : 8466,
'mu' : 181,
'uni2281' : 8833,
'paragraph' : 182,
'nine' : 57,
'uni25EC' : 9708,
'v' : 118,
'uni040C' : 1036,
'uni0113' : 275,
'uni22D0' : 8912,
'uni21CC' : 8652,
'uni21CB' : 8651,
'uni21CA' : 8650,
'uni22A5' : 8869,
'uni21CF' : 8655,
'uni21CE' : 8654,
'uni21CD' : 8653,
'guilsinglleft' : 8249,
'backslash' : 92,
'uni2284' : 8836,
'uni224E' : 8782,
'uni224D' : 8781,
'uni224F' : 8783,
'uni224A' : 8778,
'uni2287' : 8839,
'uni224C' : 8780,
'uni224B' : 8779,
'uni21BD' : 8637,
'uni2286' : 8838,
'uni030F' : 783,
'uni030D' : 781,
'uni030E' : 782,
'uni030B' : 779,
'uni030C' : 780,
'uni030A' : 778,
'uni026E' : 622,
'uni026D' : 621,
'six' : 54,
'uni026A' : 618,
'uni026C' : 620,
'uni25C1' : 9665,
'uni20D6' : 8406,
'uni045B' : 1115,
'uni045C' : 1116,
'uni256B' : 9579,
'uni045A' : 1114,
'uni045F' : 1119,
'uni045E' : 1118,
'A' : 65,
'uni2569' : 9577,
'uni0458' : 1112,
'uni0459' : 1113,
'uni0452' : 1106,
'uni0453' : 1107,
'uni2562' : 9570,
'uni0451' : 1105,
'uni0456' : 1110,
'uni0457' : 1111,
'uni0454' : 1108,
'uni0455' : 1109,
'icircumflex' : 238,
'uni0307' : 775,
'uni0304' : 772,
'uni0305' : 773,
'uni0269' : 617,
'uni0268' : 616,
'uni0300' : 768,
'uni0301' : 769,
'uni0265' : 613,
'uni0264' : 612,
'uni0267' : 615,
'uni0266' : 614,
'uni0261' : 609,
'uni0260' : 608,
'uni0263' : 611,
'uni0262' : 610,
'a' : 97,
'uni2207' : 8711,
'uni2247' : 8775,
'uni2246' : 8774,
'uni2241' : 8769,
'uni2240' : 8768,
'uni2243' : 8771,
'uni2242' : 8770,
'uni2312' : 8978,
'ogonek' : 731,
'uni2249' : 8777,
'uni2248' : 8776,
'uni3030' : 12336,
'q' : 113,
'uni21C2' : 8642,
'uni21C1' : 8641,
'uni21C0' : 8640,
'uni21C7' : 8647,
'uni21C6' : 8646,
'uni21C5' : 8645,
'uni21C4' : 8644,
'uni225F' : 8799,
'uni212C' : 8492,
'uni21C8' : 8648,
'uni2467' : 9319,
'oacute' : 243,
'uni028F' : 655,
'uni028E' : 654,
'uni026F' : 623,
'uni028C' : 652,
'uni028B' : 651,
'uni028A' : 650,
'uni2510' : 9488,
'ograve' : 242,
'edieresis' : 235,
'uni22CE' : 8910,
'uni22CF' : 8911,
'uni219F' : 8607,
'comma' : 44,
'uni22CA' : 8906,
'uni0429' : 1065,
'uni03C6' : 966,
'uni0427' : 1063,
'uni0426' : 1062,
'uni0425' : 1061,
'uni0424' : 1060,
'uni0423' : 1059,
'uni0422' : 1058,
'uni0421' : 1057,
'uni0420' : 1056,
'uni2465' : 9317,
'uni24D0' : 9424,
'uni2464' : 9316,
'uni0430' : 1072,
'otilde' : 245,
'uni2661' : 9825,
'uni24D6' : 9430,
'uni2466' : 9318,
'uni24D5' : 9429,
'uni219A' : 8602,
'uni2518' : 9496,
'uni22B6' : 8886,
'uni2461' : 9313,
'uni24D4' : 9428,
'uni2460' : 9312,
'uni24EA' : 9450,
'guillemotright' : 187,
'ecircumflex' : 234,
'greater' : 62,
'uni2011' : 8209,
'uacute' : 250,
'uni2462' : 9314,
'L' : 76,
'bullet' : 8226,
'uni02A4' : 676,
'uni02A7' : 679,
'cedilla' : 184,
'uni02A2' : 674,
'uni2015' : 8213,
'uni22C4' : 8900,
'uni22C5' : 8901,
'uni22AD' : 8877,
'uni22C7' : 8903,
'uni22C0' : 8896,
'uni2016' : 8214,
'uni22C2' : 8898,
'uni22C3' : 8899,
'uni24CF' : 9423,
'uni042F' : 1071,
'uni042E' : 1070,
'uni042D' : 1069,
'ydieresis' : 255,
'l' : 108,
'logicalnot' : 172,
'uni24CA' : 9418,
'uni0287' : 647,
'uni0286' : 646,
'uni0285' : 645,
'uni0284' : 644,
'uni0283' : 643,
'uni0282' : 642,
'uni0281' : 641,
'uni027C' : 636,
'uni2664' : 9828,
'exclamdown' : 161,
'uni25C4' : 9668,
'uni0289' : 649,
'uni0288' : 648,
'uni039A' : 922,
'endash' : 8211,
'uni2640' : 9792,
'uni20E4' : 8420,
'uni0473' : 1139,
'uni20E1' : 8417,
'uni2642' : 9794,
'uni03B8' : 952,
'uni03B9' : 953,
'agrave' : 224,
'uni03B4' : 948,
'uni03B5' : 949,
'uni03B6' : 950,
'uni03B7' : 951,
'uni03B0' : 944,
'uni03B1' : 945,
'uni03B2' : 946,
'uni03B3' : 947,
'uni2555' : 9557,
'Adieresis' : 196,
'germandbls' : 223,
'Odieresis' : 214,
'space' : 32,
'uni0126' : 294,
'uni0127' : 295,
'uni0124' : 292,
'uni0125' : 293,
'uni0122' : 290,
'uni0123' : 291,
'uni0120' : 288,
'uni0121' : 289,
'quoteright' : 8217,
'uni2560' : 9568,
'uni2556' : 9558,
'ucircumflex' : 251,
'uni2561' : 9569,
'uni2551' : 9553,
'uni25B2' : 9650,
'uni2550' : 9552,
'uni2563' : 9571,
'uni2553' : 9555,
'G' : 71,
'uni2564' : 9572,
'uni2552' : 9554,
'quoteleft' : 8216,
'uni2565' : 9573,
'uni2572' : 9586,
'uni2568' : 9576,
'uni2566' : 9574,
'W' : 87,
'uni214A' : 8522,
'uni012F' : 303,
'uni012D' : 301,
'uni012E' : 302,
'uni012B' : 299,
'uni012C' : 300,
'uni255C' : 9564,
'uni012A' : 298,
'uni2289' : 8841,
'Q' : 81,
'uni2320' : 8992,
'uni2321' : 8993,
'g' : 103,
'uni03BD' : 957,
'uni03BE' : 958,
'uni03BF' : 959,
'uni2282' : 8834,
'uni2285' : 8837,
'uni03BA' : 954,
'uni03BB' : 955,
'uni03BC' : 956,
'uni2128' : 8488,
'uni25B7' : 9655,
'w' : 119,
'uni0302' : 770,
'uni03DE' : 990,
'uni25DA' : 9690,
'uni0303' : 771,
'uni0463' : 1123,
'uni0462' : 1122,
'uni3018' : 12312,
'uni2514' : 9492,
'question' : 63,
'uni25B3' : 9651,
'uni24E1' : 9441,
'one' : 49,
'uni200A' : 8202,
'uni2278' : 8824,
'ring' : 730,
'uni0195' : 405,
'figuredash' : 8210,
'uni22EC' : 8940,
'uni0339' : 825,
'uni0338' : 824,
'uni0337' : 823,
'uni0336' : 822,
'uni0335' : 821,
'uni0333' : 819,
'uni0332' : 818,
'uni0331' : 817,
'uni0330' : 816,
'uni01C1' : 449,
'uni01C0' : 448,
'uni01C3' : 451,
'uni01C2' : 450,
'uni2353' : 9043,
'uni0308' : 776,
'uni2218' : 8728,
'uni2219' : 8729,
'uni2216' : 8726,
'uni2217' : 8727,
'uni2214' : 8724,
'uni0309' : 777,
'uni2609' : 9737,
'uni2213' : 8723,
'uni2210' : 8720,
'uni2211' : 8721,
'uni2245' : 8773,
'B' : 66,
'uni25D6' : 9686,
'iacute' : 237,
'uni02E6' : 742,
'uni02E7' : 743,
'uni02E8' : 744,
'uni02E9' : 745,
'uni221D' : 8733,
'uni221E' : 8734,
'Ydieresis' : 376,
'uni221C' : 8732,
'uni22D7' : 8919,
'uni221A' : 8730,
'R' : 82,
'uni24DC' : 9436,
'uni033F' : 831,
'uni033E' : 830,
'uni033C' : 828,
'uni033B' : 827,
'uni033A' : 826,
'b' : 98,
'uni228A' : 8842,
'uni22DB' : 8923,
'uni2554' : 9556,
'uni046B' : 1131,
'uni046A' : 1130,
'r' : 114,
'uni24DB' : 9435,
'Ccedilla' : 199,
'minus' : 8722,
'uni24DA' : 9434,
'uni03F0' : 1008,
'uni03F1' : 1009,
'uni20AC' : 8364,
'uni2276' : 8822,
'uni24C0' : 9408,
'uni0162' : 354,
'uni0163' : 355,
'uni011E' : 286,
'uni011D' : 285,
'uni011C' : 284,
'uni011B' : 283,
'uni0164' : 356,
'uni0165' : 357,
'Lslash' : 321,
'uni0168' : 360,
'uni0169' : 361,
'uni25C9' : 9673,
'uni02E5' : 741,
'uni21C3' : 8643,
'uni24C4' : 9412,
'uni24E2' : 9442,
'uni2277' : 8823,
'uni013A' : 314,
'uni2102' : 8450,
'Uacute' : 218,
'uni2317' : 8983,
'uni2107' : 8455,
'uni221F' : 8735,
'yacute' : 253,
'uni3012' : 12306,
'Ucircumflex' : 219,
'uni015D' : 349,
'quotedbl' : 34,
'uni25D9' : 9689,
'uni2280' : 8832,
'uni22AF' : 8879,
'onehalf' : 189,
'uni221B' : 8731,
'Thorn' : 222,
'uni2226' : 8742,
'M' : 77,
'uni25BA' : 9658,
'uni2463' : 9315,
'uni2336' : 9014,
'eight' : 56,
'uni2236' : 8758,
'multiply' : 215,
'uni210C' : 8460,
'uni210A' : 8458,
'uni21C9' : 8649,
'grave' : 96,
'uni210E' : 8462,
'uni0117' : 279,
'uni016C' : 364,
'uni0115' : 277,
'uni016A' : 362,
'uni016F' : 367,
'uni0112' : 274,
'uni016D' : 365,
'uni016E' : 366,
'Ocircumflex' : 212,
'uni2305' : 8965,
'm' : 109,
'uni24DF' : 9439,
'uni0119' : 281,
'uni0118' : 280,
'uni20A3' : 8355,
'uni20A4' : 8356,
'uni20A7' : 8359,
'uni2288' : 8840,
'uni24C3' : 9411,
'uni251C' : 9500,
'uni228D' : 8845,
'uni222F' : 8751,
'uni222E' : 8750,
'uni222D' : 8749,
'uni222C' : 8748,
'uni222B' : 8747,
'uni222A' : 8746,
'uni255B' : 9563,
'Ugrave' : 217,
'uni24DE' : 9438,
'guilsinglright' : 8250,
'uni250A' : 9482,
'Ntilde' : 209,
'uni0279' : 633,
'questiondown' : 191,
'uni256C' : 9580,
'Atilde' : 195,
'uni0272' : 626,
'uni0273' : 627,
'uni0270' : 624,
'ccedilla' : 231,
'uni0276' : 630,
'uni0277' : 631,
'uni0274' : 628,
'uni0275' : 629,
'uni2252' : 8786,
'uni041F' : 1055,
'uni2250' : 8784,
'Z' : 90,
'uni2256' : 8790,
'uni2257' : 8791,
'copyright' : 169,
'uni2255' : 8789,
'uni043D' : 1085,
'uni043E' : 1086,
'uni043F' : 1087,
'yen' : 165,
'uni041D' : 1053,
'uni043B' : 1083,
'uni043C' : 1084,
'uni21B0' : 8624,
'uni21B1' : 8625,
'uni21B2' : 8626,
'uni21B3' : 8627,
'uni21B4' : 8628,
'uni21B5' : 8629,
'uni21B6' : 8630,
'uni21B7' : 8631,
'uni21B8' : 8632,
'Eacute' : 201,
'uni2311' : 8977,
'uni2310' : 8976,
'uni228F' : 8847,
'uni25DB' : 9691,
'uni21BA' : 8634,
'uni21BB' : 8635,
'uni21BC' : 8636,
'uni2017' : 8215,
'uni21BE' : 8638,
'uni21BF' : 8639,
'uni231C' : 8988,
'H' : 72,
'uni0293' : 659,
'uni2202' : 8706,
'uni22A4' : 8868,
'uni231E' : 8990,
'uni2232' : 8754,
'uni225B' : 8795,
'uni225C' : 8796,
'uni24D9' : 9433,
'uni225A' : 8794,
'uni0438' : 1080,
'uni0439' : 1081,
'uni225D' : 8797,
'uni225E' : 8798,
'uni0434' : 1076,
'X' : 88,
'uni007F' : 127,
'uni0437' : 1079,
'Idieresis' : 207,
'uni0431' : 1073,
'uni0432' : 1074,
'uni0433' : 1075,
'uni22AC' : 8876,
'uni22CD' : 8909,
'uni25A3' : 9635,
'bar' : 124,
'uni24BB' : 9403,
'uni037E' : 894,
'uni027B' : 635,
'h' : 104,
'uni027A' : 634,
'uni027F' : 639,
'uni027D' : 637,
'uni027E' : 638,
'uni2227' : 8743,
'uni2004' : 8196,
'uni2225' : 8741,
'uni2224' : 8740,
'uni2223' : 8739,
'uni2222' : 8738,
'uni2221' : 8737,
'uni2220' : 8736,
'x' : 120,
'uni2323' : 8995,
'uni2559' : 9561,
'uni2558' : 9560,
'uni2229' : 8745,
'uni2228' : 8744,
'udieresis' : 252,
'uni029D' : 669,
'ordfeminine' : 170,
'uni22CB' : 8907,
'uni233D' : 9021,
'uni0428' : 1064,
'uni24C6' : 9414,
'uni22DD' : 8925,
'uni24C7' : 9415,
'uni015C' : 348,
'uni015B' : 347,
'uni015A' : 346,
'uni22AA' : 8874,
'uni015F' : 351,
'uni015E' : 350,
'braceleft' : 123,
'uni24C5' : 9413,
'uni0410' : 1040,
'uni03AA' : 938,
'uni24C2' : 9410,
'uni03AC' : 940,
'uni03AB' : 939,
'macron' : 175,
'uni03AD' : 941,
'uni03AF' : 943,
'uni0294' : 660,
'uni0295' : 661,
'uni0296' : 662,
'uni0297' : 663,
'uni0290' : 656,
'uni0291' : 657,
'uni0292' : 658,
'atilde' : 227,
'Acircumflex' : 194,
'uni2370' : 9072,
'uni24C1' : 9409,
'uni0298' : 664,
'uni0299' : 665,
'Oslash' : 216,
'uni029E' : 670,
'C' : 67,
'quotedblleft' : 8220,
'uni029B' : 667,
'uni029C' : 668,
'uni03A9' : 937,
'uni03A8' : 936,
'S' : 83,
'uni24C9' : 9417,
'uni03A1' : 929,
'uni03A0' : 928,
'exclam' : 33,
'uni03A5' : 933,
'uni03A4' : 932,
'uni03A7' : 935,
'Zcaron' : 381,
'uni2133' : 8499,
'uni2132' : 8498,
'uni0159' : 345,
'uni0158' : 344,
'uni2137' : 8503,
'uni2005' : 8197,
'uni2135' : 8501,
'uni2134' : 8500,
'uni02BA' : 698,
'uni2033' : 8243,
'uni0151' : 337,
'uni0150' : 336,
'uni0157' : 343,
'equal' : 61,
'uni0155' : 341,
'uni0154' : 340,
's' : 115,
'uni233F' : 9023,
'eth' : 240,
'uni24BE' : 9406,
'uni21E9' : 8681,
'uni2060' : 8288,
'Egrave' : 200,
'uni255D' : 9565,
'uni24CD' : 9421,
'uni21E1' : 8673,
'uni21B9' : 8633,
'hyphen' : 45,
'uni01BE' : 446,
'uni01BB' : 443,
'period' : 46,
'igrave' : 236,
'uni01BA' : 442,
'uni2296' : 8854,
'uni2297' : 8855,
'uni2294' : 8852,
'uni2295' : 8853,
'colon' : 58,
'uni2293' : 8851,
'uni2290' : 8848,
'uni2291' : 8849,
'uni032D' : 813,
'uni032E' : 814,
'uni032F' : 815,
'uni032A' : 810,
'uni032B' : 811,
'uni032C' : 812,
'uni231D' : 8989,
'Ecircumflex' : 202,
'uni24D7' : 9431,
'uni25DD' : 9693,
'trademark' : 8482,
'Aacute' : 193,
'cent' : 162,
'uni0445' : 1093,
'uni266E' : 9838,
'uni266D' : 9837,
'uni266B' : 9835,
'uni03C9' : 969,
'uni2003' : 8195,
'uni2047' : 8263,
'lslash' : 322,
'uni03A6' : 934,
'uni2043' : 8259,
'uni250C' : 9484,
'uni2040' : 8256,
'uni255F' : 9567,
'uni24CB' : 9419,
'uni0472' : 1138,
'uni0446' : 1094,
'uni0474' : 1140,
'uni0475' : 1141,
'uni2508' : 9480,
'uni2660' : 9824,
'uni2506' : 9478,
'uni2502' : 9474,
'c' : 99,
'uni2500' : 9472,
'N' : 78,
'uni22A6' : 8870,
'uni21E7' : 8679,
'uni2130' : 8496,
'uni2002' : 8194,
'breve' : 728,
'uni0442' : 1090,
'Oacute' : 211,
'uni229F' : 8863,
'uni25C7' : 9671,
'uni229D' : 8861,
'uni229E' : 8862,
'guillemotleft' : 171,
'uni0329' : 809,
'uni24E5' : 9445,
'uni011F' : 287,
'uni0324' : 804,
'uni0325' : 805,
'uni0326' : 806,
'uni0327' : 807,
'uni0321' : 801,
'uni0322' : 802,
'n' : 110,
'uni2032' : 8242,
'uni2269' : 8809,
'uni2268' : 8808,
'uni0306' : 774,
'uni226B' : 8811,
'uni21EA' : 8682,
'uni0166' : 358,
'uni203B' : 8251,
'uni01B5' : 437,
'idieresis' : 239,
'uni02BC' : 700,
'uni01B0' : 432,
'braceright' : 125,
'seven' : 55,
'uni02BB' : 699,
'uni011A' : 282,
'uni29FB' : 10747,
'brokenbar' : 166,
'uni2036' : 8246,
'uni25C0' : 9664,
'uni0156' : 342,
'uni22D5' : 8917,
'uni0258' : 600,
'ugrave' : 249,
'uni22D6' : 8918,
'uni22D1' : 8913,
'uni2034' : 8244,
'uni22D3' : 8915,
'uni22D2' : 8914,
'uni203C' : 8252,
'uni223E' : 8766,
'uni02BF' : 703,
'uni22D9' : 8921,
'uni22D8' : 8920,
'uni25BD' : 9661,
'uni25BE' : 9662,
'uni25BF' : 9663,
'uni041B' : 1051,
'periodcentered' : 183,
'uni25BC' : 9660,
'uni019E' : 414,
'uni019B' : 411,
'uni019A' : 410,
'uni2007' : 8199,
'uni0391' : 913,
'uni0390' : 912,
'uni0393' : 915,
'uni0392' : 914,
'uni0395' : 917,
'uni0394' : 916,
'uni0397' : 919,
'uni0396' : 918,
'uni0399' : 921,
'uni0398' : 920,
'uni25C8' : 9672,
'uni2468' : 9320,
'sterling' : 163,
'uni22EB' : 8939,
'uni039C' : 924,
'uni039B' : 923,
'uni039E' : 926,
'uni039D' : 925,
'uni039F' : 927,
'I' : 73,
'uni03E1' : 993,
'uni03E0' : 992,
'uni2319' : 8985,
'uni228B' : 8843,
'uni25B5' : 9653,
'uni25B6' : 9654,
'uni22EA' : 8938,
'uni24B9' : 9401,
'uni044E' : 1102,
'uni0199' : 409,
'uni2266' : 8806,
'Y' : 89,
'uni22A2' : 8866,
'Eth' : 208,
'uni266F' : 9839,
'emdash' : 8212,
'uni263B' : 9787,
'uni24BD' : 9405,
'uni22DE' : 8926,
'uni0360' : 864,
'uni2557' : 9559,
'uni22DF' : 8927,
'uni22DA' : 8922,
'uni22DC' : 8924,
'uni0361' : 865,
'i' : 105,
'uni24BF' : 9407,
'uni0362' : 866,
'uni263E' : 9790,
'uni028D' : 653,
'uni2259' : 8793,
'uni0323' : 803,
'uni2265' : 8805,
'daggerdbl' : 8225,
'y' : 121,
'uni010A' : 266,
'plusminus' : 177,
'less' : 60,
'uni21AE' : 8622,
'uni0315' : 789,
'uni230B' : 8971,
'uni21AF' : 8623,
'uni21AA' : 8618,
'uni21AC' : 8620,
'uni21AB' : 8619,
'uni01FB' : 507,
'uni01FC' : 508,
'uni223A' : 8762,
'uni01FA' : 506,
'uni01FF' : 511,
'uni01FD' : 509,
'uni01FE' : 510,
'uni2567' : 9575,
'uni25E0' : 9696,
'uni0104' : 260,
'uni0105' : 261,
'uni0106' : 262,
'uni0107' : 263,
'uni0100' : 256,
'uni0101' : 257,
'uni0102' : 258,
'uni0103' : 259,
'uni2038' : 8248,
'uni2009' : 8201,
'uni2008' : 8200,
'uni0108' : 264,
'uni0109' : 265,
'uni02A1' : 673,
'uni223B' : 8763,
'uni226C' : 8812,
'uni25AC' : 9644,
'uni24D3' : 9427,
'uni21E0' : 8672,
'uni21E3' : 8675,
'Udieresis' : 220,
'uni21E2' : 8674,
'D' : 68,
'uni21E5' : 8677,
'uni2621' : 9761,
'uni21D1' : 8657,
'uni203E' : 8254,
'uni22C6' : 8902,
'uni21E4' : 8676,
'uni010D' : 269,
'uni010E' : 270,
'uni010F' : 271,
'five' : 53,
'T' : 84,
'uni010B' : 267,
'uni010C' : 268,
'uni2605' : 9733,
'uni2663' : 9827,
'uni21E6' : 8678,
'uni24B6' : 9398,
'uni22C1' : 8897,
'oslash' : 248,
'acute' : 180,
'uni01F0' : 496,
'd' : 100,
'OE' : 338,
'uni22E3' : 8931,
'Igrave' : 204,
'uni2308' : 8968,
'uni2309' : 8969,
'uni21A9' : 8617,
't' : 116,
'uni2313' : 8979,
'uni03A3' : 931,
'uni21A4' : 8612,
'uni21A7' : 8615,
'uni21A6' : 8614,
'uni21A1' : 8609,
'uni21A0' : 8608,
'uni21A3' : 8611,
'uni21A2' : 8610,
'parenright' : 41,
'uni256A' : 9578,
'uni25DC' : 9692,
'uni24CE' : 9422,
'uni042C' : 1068,
'uni24E0' : 9440,
'uni042B' : 1067,
'uni0409' : 1033,
'uni0408' : 1032,
'uni24E7' : 9447,
'uni25B4' : 9652,
'uni042A' : 1066,
'uni228E' : 8846,
'uni0401' : 1025,
'adieresis' : 228,
'uni0403' : 1027,
'quotesingle' : 39,
'uni0405' : 1029,
'uni0404' : 1028,
'uni0407' : 1031,
'uni0406' : 1030,
'uni229C' : 8860,
'uni2306' : 8966,
'uni2253' : 8787,
'twodotenleader' : 8229,
'uni2131' : 8497,
'uni21DA' : 8666,
'uni2234' : 8756,
'uni2235' : 8757,
'uni01A5' : 421,
'uni2237' : 8759,
'uni2230' : 8752,
'uni02CC' : 716,
'slash' : 47,
'uni01A0' : 416,
'ellipsis' : 8230,
'uni2299' : 8857,
'uni2238' : 8760,
'numbersign' : 35,
'uni21A8' : 8616,
'uni223D' : 8765,
'uni01AF' : 431,
'uni223F' : 8767,
'uni01AD' : 429,
'uni01AB' : 427,
'odieresis' : 246,
'uni223C' : 8764,
'uni227D' : 8829,
'uni0280' : 640,
'O' : 79,
'uni227E' : 8830,
'uni21A5' : 8613,
'uni22D4' : 8916,
'uni25D4' : 9684,
'uni227F' : 8831,
'uni0435' : 1077,
'uni2302' : 8962,
'uni2669' : 9833,
'uni24E3' : 9443,
'uni2720' : 10016,
'uni22A8' : 8872,
'uni22A9' : 8873,
'uni040A' : 1034,
'uni22A7' : 8871,
'oe' : 339,
'uni040B' : 1035,
'uni040E' : 1038,
'uni22A3' : 8867,
'o' : 111,
'uni040F' : 1039,
'Edieresis' : 203,
'uni25D5' : 9685,
'plus' : 43,
'uni044D' : 1101,
'uni263C' : 9788,
'uni22E6' : 8934,
'uni2283' : 8835,
'uni258C' : 9612,
'uni219E' : 8606,
'uni24E4' : 9444,
'uni2136' : 8502,
'dagger' : 8224,
'uni24B7' : 9399,
'uni219B' : 8603,
'uni22E5' : 8933,
'three' : 51,
'uni210B' : 8459,
'uni2534' : 9524,
'uni24B8' : 9400,
'uni230A' : 8970,
'hungarumlaut' : 733,
'parenleft' : 40,
'uni0148' : 328,
'uni0149' : 329,
'uni2124' : 8484,
'uni2125' : 8485,
'uni2126' : 8486,
'uni2127' : 8487,
'uni0140' : 320,
'uni2129' : 8489,
'uni25C5' : 9669,
'uni0143' : 323,
'uni0144' : 324,
'uni0145' : 325,
'uni0146' : 326,
'uni0147' : 327,
'uni210D' : 8461,
'fraction' : 8260,
'uni2031' : 8241,
'uni2196' : 8598,
'uni2035' : 8245,
'uni24E6' : 9446,
'uni016B' : 363,
'uni24BA' : 9402,
'uni266A' : 9834,
'uni0116' : 278,
'uni2115' : 8469,
'registered' : 174,
'J' : 74,
'uni25DF' : 9695,
'uni25CE' : 9678,
'uni273D' : 10045,
'dieresis' : 168,
'uni212B' : 8491,
'uni0114' : 276,
'uni212D' : 8493,
'uni212E' : 8494,
'uni212F' : 8495,
'uni014A' : 330,
'uni014B' : 331,
'uni014C' : 332,
'uni014D' : 333,
'uni014E' : 334,
'uni014F' : 335,
'uni025E' : 606,
'uni24E8' : 9448,
'uni0111' : 273,
'uni24E9' : 9449,
'Ograve' : 210,
'j' : 106,
'uni2195' : 8597,
'uni2194' : 8596,
'uni2197' : 8599,
'uni2037' : 8247,
'uni2191' : 8593,
'uni2190' : 8592,
'uni2193' : 8595,
'uni2192' : 8594,
'uni29FA' : 10746,
'uni2713' : 10003,
'z' : 122,
'uni2199' : 8601,
'uni2198' : 8600,
'uni2667' : 9831,
'ae' : 230,
'uni0448' : 1096,
'semicolon' : 59,
'uni2666' : 9830,
'uni038F' : 911,
'uni0444' : 1092,
'uni0447' : 1095,
'uni038E' : 910,
'uni0441' : 1089,
'uni038C' : 908,
'uni0443' : 1091,
'uni038A' : 906,
'uni0250' : 592,
'uni0251' : 593,
'uni0252' : 594,
'uni0253' : 595,
'uni0254' : 596,
'at' : 64,
'uni0256' : 598,
'uni0257' : 599,
'uni0167' : 359,
'uni0259' : 601,
'uni228C' : 8844,
'uni2662' : 9826,
'uni0319' : 793,
'uni0318' : 792,
'uni24BC' : 9404,
'uni0402' : 1026,
'uni22EF' : 8943,
'Iacute' : 205,
'uni22ED' : 8941,
'uni22EE' : 8942,
'uni0311' : 785,
'uni0310' : 784,
'uni21E8' : 8680,
'uni0312' : 786,
'percent' : 37,
'uni0317' : 791,
'uni0316' : 790,
'uni21D6' : 8662,
'uni21D7' : 8663,
'uni21D4' : 8660,
'uni21D5' : 8661,
'uni21D2' : 8658,
'uni21D3' : 8659,
'uni21D0' : 8656,
'uni2138' : 8504,
'uni2270' : 8816,
'uni2271' : 8817,
'uni2272' : 8818,
'uni2273' : 8819,
'uni2274' : 8820,
'uni2275' : 8821,
'bracketright' : 93,
'uni21D9' : 8665,
'uni21DF' : 8671,
'uni21DD' : 8669,
'uni21DE' : 8670,
'AE' : 198,
'uni03AE' : 942,
'uni227A' : 8826,
'uni227B' : 8827,
'uni227C' : 8828,
'asterisk' : 42,
'aacute' : 225,
'uni226F' : 8815,
'uni22E2' : 8930,
'uni0386' : 902,
'uni22E0' : 8928,
'uni22E1' : 8929,
'U' : 85,
'uni22E7' : 8935,
'uni22E4' : 8932,
'uni0387' : 903,
'uni031A' : 794,
'eacute' : 233,
'uni22E8' : 8936,
'uni22E9' : 8937,
'uni24D8' : 9432,
'uni025A' : 602,
'uni025B' : 603,
'uni025C' : 604,
'e' : 101,
'uni0128' : 296,
'uni025F' : 607,
'uni2665' : 9829,
'thorn' : 254,
'uni0129' : 297,
'uni253C' : 9532,
'uni25D7' : 9687,
'u' : 117,
'uni0388' : 904,
'uni0389' : 905,
'uni0255' : 597,
'uni0171' : 369,
'uni0384' : 900,
'uni0385' : 901,
'uni044A' : 1098,
'uni252C' : 9516,
'uni044C' : 1100,
'uni044B' : 1099
}
uni2type1 = {v: k for k, v in type12uni.items()}
tex2uni = {
'widehat' : 0x0302,
'widetilde' : 0x0303,
'widebar' : 0x0305,
'langle' : 0x27e8,
'rangle' : 0x27e9,
'perp' : 0x27c2,
'neq' : 0x2260,
'Join' : 0x2a1d,
'leqslant' : 0x2a7d,
'geqslant' : 0x2a7e,
'lessapprox' : 0x2a85,
'gtrapprox' : 0x2a86,
'lesseqqgtr' : 0x2a8b,
'gtreqqless' : 0x2a8c,
'triangleeq' : 0x225c,
'eqslantless' : 0x2a95,
'eqslantgtr' : 0x2a96,
'backepsilon' : 0x03f6,
'precapprox' : 0x2ab7,
'succapprox' : 0x2ab8,
'fallingdotseq' : 0x2252,
'subseteqq' : 0x2ac5,
'supseteqq' : 0x2ac6,
'varpropto' : 0x221d,
'precnapprox' : 0x2ab9,
'succnapprox' : 0x2aba,
'subsetneqq' : 0x2acb,
'supsetneqq' : 0x2acc,
'lnapprox' : 0x2ab9,
'gnapprox' : 0x2aba,
'longleftarrow' : 0x27f5,
'longrightarrow' : 0x27f6,
'longleftrightarrow' : 0x27f7,
'Longleftarrow' : 0x27f8,
'Longrightarrow' : 0x27f9,
'Longleftrightarrow' : 0x27fa,
'longmapsto' : 0x27fc,
'leadsto' : 0x21dd,
'dashleftarrow' : 0x290e,
'dashrightarrow' : 0x290f,
'circlearrowleft' : 0x21ba,
'circlearrowright' : 0x21bb,
'leftrightsquigarrow' : 0x21ad,
'leftsquigarrow' : 0x219c,
'rightsquigarrow' : 0x219d,
'Game' : 0x2141,
'hbar' : 0x0127,
'hslash' : 0x210f,
'ldots' : 0x2026,
'vdots' : 0x22ee,
'doteqdot' : 0x2251,
'doteq' : 8784,
'partial' : 8706,
'gg' : 8811,
'asymp' : 8781,
'blacktriangledown' : 9662,
'otimes' : 8855,
'nearrow' : 8599,
'varpi' : 982,
'vee' : 8744,
'vec' : 8407,
'smile' : 8995,
'succnsim' : 8937,
'gimel' : 8503,
'vert' : 124,
'|' : 124,
'varrho' : 1009,
'P' : 182,
'approxident' : 8779,
'Swarrow' : 8665,
'textasciicircum' : 94,
'imageof' : 8887,
'ntriangleleft' : 8938,
'nleq' : 8816,
'div' : 247,
'nparallel' : 8742,
'Leftarrow' : 8656,
'lll' : 8920,
'oiint' : 8751,
'ngeq' : 8817,
'Theta' : 920,
'origof' : 8886,
'blacksquare' : 9632,
'solbar' : 9023,
'neg' : 172,
'sum' : 8721,
'Vdash' : 8873,
'coloneq' : 8788,
'degree' : 176,
'bowtie' : 8904,
'blacktriangleright' : 9654,
'varsigma' : 962,
'leq' : 8804,
'ggg' : 8921,
'lneqq' : 8808,
'scurel' : 8881,
'stareq' : 8795,
'BbbN' : 8469,
'nLeftarrow' : 8653,
'nLeftrightarrow' : 8654,
'k' : 808,
'bot' : 8869,
'BbbC' : 8450,
'Lsh' : 8624,
'leftleftarrows' : 8647,
'BbbZ' : 8484,
'digamma' : 989,
'BbbR' : 8477,
'BbbP' : 8473,
'BbbQ' : 8474,
'vartriangleright' : 8883,
'succsim' : 8831,
'wedge' : 8743,
'lessgtr' : 8822,
'veebar' : 8891,
'mapsdown' : 8615,
'Rsh' : 8625,
'chi' : 967,
'prec' : 8826,
'nsubseteq' : 8840,
'therefore' : 8756,
'eqcirc' : 8790,
'textexclamdown' : 161,
'nRightarrow' : 8655,
'flat' : 9837,
'notin' : 8713,
'llcorner' : 8990,
'varepsilon' : 949,
'bigtriangleup' : 9651,
'aleph' : 8501,
'dotminus' : 8760,
'upsilon' : 965,
'Lambda' : 923,
'cap' : 8745,
'barleftarrow' : 8676,
'mu' : 956,
'boxplus' : 8862,
'mp' : 8723,
'circledast' : 8859,
'tau' : 964,
'in' : 8712,
'backslash' : 92,
'varnothing' : 8709,
'sharp' : 9839,
'eqsim' : 8770,
'gnsim' : 8935,
'Searrow' : 8664,
'updownarrows' : 8645,
'heartsuit' : 9825,
'trianglelefteq' : 8884,
'ddag' : 8225,
'sqsubseteq' : 8849,
'mapsfrom' : 8612,
'boxbar' : 9707,
'sim' : 8764,
'Nwarrow' : 8662,
'nequiv' : 8802,
'succ' : 8827,
'vdash' : 8866,
'Leftrightarrow' : 8660,
'parallel' : 8741,
'invnot' : 8976,
'natural' : 9838,
'ss' : 223,
'uparrow' : 8593,
'nsim' : 8769,
'hookrightarrow' : 8618,
'Equiv' : 8803,
'approx' : 8776,
'Vvdash' : 8874,
'nsucc' : 8833,
'leftrightharpoons' : 8651,
'Re' : 8476,
'boxminus' : 8863,
'equiv' : 8801,
'Lleftarrow' : 8666,
'll' : 8810,
'Cup' : 8915,
'measeq' : 8798,
'upharpoonleft' : 8639,
'lq' : 8216,
'Upsilon' : 933,
'subsetneq' : 8842,
'greater' : 62,
'supsetneq' : 8843,
'Cap' : 8914,
'L' : 321,
'spadesuit' : 9824,
'lrcorner' : 8991,
'not' : 824,
'bar' : 772,
'rightharpoonaccent' : 8401,
'boxdot' : 8865,
'l' : 322,
'leftharpoondown' : 8637,
'bigcup' : 8899,
'iint' : 8748,
'bigwedge' : 8896,
'downharpoonleft' : 8643,
'textasciitilde' : 126,
'subset' : 8834,
'leqq' : 8806,
'mapsup' : 8613,
'nvDash' : 8877,
'looparrowleft' : 8619,
'nless' : 8814,
'rightarrowbar' : 8677,
'Vert' : 8214,
'downdownarrows' : 8650,
'uplus' : 8846,
'simeq' : 8771,
'napprox' : 8777,
'ast' : 8727,
'twoheaduparrow' : 8607,
'doublebarwedge' : 8966,
'Sigma' : 931,
'leftharpoonaccent' : 8400,
'ntrianglelefteq' : 8940,
'nexists' : 8708,
'times' : 215,
'measuredangle' : 8737,
'bumpeq' : 8783,
'carriagereturn' : 8629,
'adots' : 8944,
'checkmark' : 10003,
'lambda' : 955,
'xi' : 958,
'rbrace' : 125,
'rbrack' : 93,
'Nearrow' : 8663,
'maltese' : 10016,
'clubsuit' : 9827,
'top' : 8868,
'overarc' : 785,
'varphi' : 966,
'Delta' : 916,
'iota' : 953,
'nleftarrow' : 8602,
'candra' : 784,
'supset' : 8835,
'triangleleft' : 9665,
'gtreqless' : 8923,
'ntrianglerighteq' : 8941,
'quad' : 8195,
'Xi' : 926,
'gtrdot' : 8919,
'leftthreetimes' : 8907,
'minus' : 8722,
'preccurlyeq' : 8828,
'nleftrightarrow' : 8622,
'lambdabar' : 411,
'blacktriangle' : 9652,
'kernelcontraction' : 8763,
'Phi' : 934,
'angle' : 8736,
'spadesuitopen' : 9828,
'eqless' : 8924,
'mid' : 8739,
'varkappa' : 1008,
'Ldsh' : 8626,
'updownarrow' : 8597,
'beta' : 946,
'textquotedblleft' : 8220,
'rho' : 961,
'alpha' : 945,
'intercal' : 8890,
'beth' : 8502,
'grave' : 768,
'acwopencirclearrow' : 8634,
'nmid' : 8740,
'nsupset' : 8837,
'sigma' : 963,
'dot' : 775,
'Rightarrow' : 8658,
'turnednot' : 8985,
'backsimeq' : 8909,
'leftarrowtail' : 8610,
'approxeq' : 8778,
'curlyeqsucc' : 8927,
'rightarrowtail' : 8611,
'Psi' : 936,
'copyright' : 169,
'yen' : 165,
'vartriangleleft' : 8882,
'rasp' : 700,
'triangleright' : 9655,
'precsim' : 8830,
'infty' : 8734,
'geq' : 8805,
'updownarrowbar' : 8616,
'precnsim' : 8936,
'H' : 779,
'ulcorner' : 8988,
'looparrowright' : 8620,
'ncong' : 8775,
'downarrow' : 8595,
'circeq' : 8791,
'subseteq' : 8838,
'bigstar' : 9733,
'prime' : 8242,
'lceil' : 8968,
'Rrightarrow' : 8667,
'oiiint' : 8752,
'curlywedge' : 8911,
'vDash' : 8872,
'lfloor' : 8970,
'ddots' : 8945,
'exists' : 8707,
'underbar' : 817,
'Pi' : 928,
'leftrightarrows' : 8646,
'sphericalangle' : 8738,
'coprod' : 8720,
'circledcirc' : 8858,
'gtrsim' : 8819,
'gneqq' : 8809,
'between' : 8812,
'theta' : 952,
'complement' : 8705,
'arceq' : 8792,
'nVdash' : 8878,
'S' : 167,
'wr' : 8768,
'wp' : 8472,
'backcong' : 8780,
'lasp' : 701,
'c' : 807,
'nabla' : 8711,
'dotplus' : 8724,
'eta' : 951,
'forall' : 8704,
'eth' : 240,
'colon' : 58,
'sqcup' : 8852,
'rightrightarrows' : 8649,
'sqsupset' : 8848,
'mapsto' : 8614,
'bigtriangledown' : 9661,
'sqsupseteq' : 8850,
'propto' : 8733,
'pi' : 960,
'pm' : 177,
'dots' : 0x2026,
'nrightarrow' : 8603,
'textasciiacute' : 180,
'Doteq' : 8785,
'breve' : 774,
'sqcap' : 8851,
'twoheadrightarrow' : 8608,
'kappa' : 954,
'vartriangle' : 9653,
'diamondsuit' : 9826,
'pitchfork' : 8916,
'blacktriangleleft' : 9664,
'nprec' : 8832,
'curvearrowright' : 8631,
'barwedge' : 8892,
'multimap' : 8888,
'textquestiondown' : 191,
'cong' : 8773,
'rtimes' : 8906,
'rightzigzagarrow' : 8669,
'rightarrow' : 8594,
'leftarrow' : 8592,
'__sqrt__' : 8730,
'twoheaddownarrow' : 8609,
'oint' : 8750,
'bigvee' : 8897,
'eqdef' : 8797,
'sterling' : 163,
'phi' : 981,
'Updownarrow' : 8661,
'backprime' : 8245,
'emdash' : 8212,
'Gamma' : 915,
'i' : 305,
'rceil' : 8969,
'leftharpoonup' : 8636,
'Im' : 8465,
'curvearrowleft' : 8630,
'wedgeq' : 8793,
'curlyeqprec' : 8926,
'questeq' : 8799,
'less' : 60,
'upuparrows' : 8648,
'tilde' : 771,
'textasciigrave' : 96,
'smallsetminus' : 8726,
'ell' : 8467,
'cup' : 8746,
'danger' : 9761,
'nVDash' : 8879,
'cdotp' : 183,
'cdots' : 8943,
'hat' : 770,
'eqgtr' : 8925,
'psi' : 968,
'frown' : 8994,
'acute' : 769,
'downzigzagarrow' : 8623,
'ntriangleright' : 8939,
'cupdot' : 8845,
'circleddash' : 8861,
'oslash' : 8856,
'mho' : 8487,
'd' : 803,
'sqsubset' : 8847,
'cdot' : 8901,
'Omega' : 937,
'OE' : 338,
'veeeq' : 8794,
'Finv' : 8498,
't' : 865,
'leftrightarrow' : 8596,
'swarrow' : 8601,
'rightthreetimes' : 8908,
'rightleftharpoons' : 8652,
'lesssim' : 8818,
'searrow' : 8600,
'because' : 8757,
'gtrless' : 8823,
'star' : 8902,
'nsubset' : 8836,
'zeta' : 950,
'dddot' : 8411,
'bigcirc' : 9675,
'Supset' : 8913,
'circ' : 8728,
'slash' : 8725,
'ocirc' : 778,
'prod' : 8719,
'twoheadleftarrow' : 8606,
'daleth' : 8504,
'upharpoonright' : 8638,
'odot' : 8857,
'Uparrow' : 8657,
'O' : 216,
'hookleftarrow' : 8617,
'trianglerighteq' : 8885,
'nsime' : 8772,
'oe' : 339,
'nwarrow' : 8598,
'o' : 248,
'ddddot' : 8412,
'downharpoonright' : 8642,
'succcurlyeq' : 8829,
'gamma' : 947,
'scrR' : 8475,
'dag' : 8224,
'thickspace' : 8197,
'frakZ' : 8488,
'lessdot' : 8918,
'triangledown' : 9663,
'ltimes' : 8905,
'scrB' : 8492,
'endash' : 8211,
'scrE' : 8496,
'scrF' : 8497,
'scrH' : 8459,
'scrI' : 8464,
'rightharpoondown' : 8641,
'scrL' : 8466,
'scrM' : 8499,
'frakC' : 8493,
'nsupseteq' : 8841,
'circledR' : 174,
'circledS' : 9416,
'ngtr' : 8815,
'bigcap' : 8898,
'scre' : 8495,
'Downarrow' : 8659,
'scrg' : 8458,
'overleftrightarrow' : 8417,
'scro' : 8500,
'lnsim' : 8934,
'eqcolon' : 8789,
'curlyvee' : 8910,
'urcorner' : 8989,
'lbrace' : 123,
'Bumpeq' : 8782,
'delta' : 948,
'boxtimes' : 8864,
'overleftarrow' : 8406,
'prurel' : 8880,
'clubsuitopen' : 9831,
'cwopencirclearrow' : 8635,
'geqq' : 8807,
'rightleftarrows' : 8644,
'ac' : 8766,
'ae' : 230,
'int' : 8747,
'rfloor' : 8971,
'risingdotseq' : 8787,
'nvdash' : 8876,
'diamond' : 8900,
'ddot' : 776,
'backsim' : 8765,
'oplus' : 8853,
'triangleq' : 8796,
'check' : 780,
'ni' : 8715,
'iiint' : 8749,
'ne' : 8800,
'lesseqgtr' : 8922,
'obar' : 9021,
'supseteq' : 8839,
'nu' : 957,
'AA' : 197,
'AE' : 198,
'models' : 8871,
'ominus' : 8854,
'dashv' : 8867,
'omega' : 969,
'rq' : 8217,
'Subset' : 8912,
'rightharpoonup' : 8640,
'Rdsh' : 8627,
'bullet' : 8729,
'divideontimes' : 8903,
'lbrack' : 91,
'textquotedblright' : 8221,
'Colon' : 8759,
'%' : 37,
'$' : 36,
'{' : 123,
'}' : 125,
'_' : 95,
'#' : 35,
'imath' : 0x131,
'circumflexaccent' : 770,
'combiningbreve' : 774,
'combiningoverline' : 772,
'combininggraveaccent' : 768,
'combiningacuteaccent' : 769,
'combiningdiaeresis' : 776,
'combiningtilde' : 771,
'combiningrightarrowabove' : 8407,
'combiningdotabove' : 775,
'to' : 8594,
'succeq' : 8829,
'emptyset' : 8709,
'leftparen' : 40,
'rightparen' : 41,
'bigoplus' : 10753,
'leftangle' : 10216,
'rightangle' : 10217,
'leftbrace' : 124,
'rightbrace' : 125,
'jmath' : 567,
'bigodot' : 10752,
'preceq' : 8828,
'biguplus' : 10756,
'epsilon' : 949,
'vartheta' : 977,
'bigotimes' : 10754,
'guillemotleft' : 171,
'ring' : 730,
'Thorn' : 222,
'guilsinglright' : 8250,
'perthousand' : 8240,
'macron' : 175,
'cent' : 162,
'guillemotright' : 187,
'equal' : 61,
'asterisk' : 42,
'guilsinglleft' : 8249,
'plus' : 43,
'thorn' : 254,
'dagger' : 8224
}
# Each element is a 4-tuple of the form:
# src_start, src_end, dst_font, dst_start
#
stix_virtual_fonts = {
'bb':
{
'rm':
[
(0x0030, 0x0039, 'rm', 0x1d7d8), # 0-9
(0x0041, 0x0042, 'rm', 0x1d538), # A-B
(0x0043, 0x0043, 'rm', 0x2102), # C
(0x0044, 0x0047, 'rm', 0x1d53b), # D-G
(0x0048, 0x0048, 'rm', 0x210d), # H
(0x0049, 0x004d, 'rm', 0x1d540), # I-M
(0x004e, 0x004e, 'rm', 0x2115), # N
(0x004f, 0x004f, 'rm', 0x1d546), # O
(0x0050, 0x0051, 'rm', 0x2119), # P-Q
(0x0052, 0x0052, 'rm', 0x211d), # R
(0x0053, 0x0059, 'rm', 0x1d54a), # S-Y
(0x005a, 0x005a, 'rm', 0x2124), # Z
(0x0061, 0x007a, 'rm', 0x1d552), # a-z
(0x0393, 0x0393, 'rm', 0x213e), # \Gamma
(0x03a0, 0x03a0, 'rm', 0x213f), # \Pi
(0x03a3, 0x03a3, 'rm', 0x2140), # \Sigma
(0x03b3, 0x03b3, 'rm', 0x213d), # \gamma
(0x03c0, 0x03c0, 'rm', 0x213c), # \pi
],
'it':
[
(0x0030, 0x0039, 'rm', 0x1d7d8), # 0-9
(0x0041, 0x0042, 'it', 0xe154), # A-B
(0x0043, 0x0043, 'it', 0x2102), # C
(0x0044, 0x0044, 'it', 0x2145), # D
(0x0045, 0x0047, 'it', 0xe156), # E-G
(0x0048, 0x0048, 'it', 0x210d), # H
(0x0049, 0x004d, 'it', 0xe159), # I-M
(0x004e, 0x004e, 'it', 0x2115), # N
(0x004f, 0x004f, 'it', 0xe15e), # O
(0x0050, 0x0051, 'it', 0x2119), # P-Q
(0x0052, 0x0052, 'it', 0x211d), # R
(0x0053, 0x0059, 'it', 0xe15f), # S-Y
(0x005a, 0x005a, 'it', 0x2124), # Z
(0x0061, 0x0063, 'it', 0xe166), # a-c
(0x0064, 0x0065, 'it', 0x2146), # d-e
(0x0066, 0x0068, 'it', 0xe169), # f-h
(0x0069, 0x006a, 'it', 0x2148), # i-j
(0x006b, 0x007a, 'it', 0xe16c), # k-z
(0x0393, 0x0393, 'it', 0x213e), # \Gamma (not in beta STIX fonts)
(0x03a0, 0x03a0, 'it', 0x213f), # \Pi
(0x03a3, 0x03a3, 'it', 0x2140), # \Sigma (not in beta STIX fonts)
(0x03b3, 0x03b3, 'it', 0x213d), # \gamma (not in beta STIX fonts)
(0x03c0, 0x03c0, 'it', 0x213c), # \pi
],
'bf':
[
(0x0030, 0x0039, 'rm', 0x1d7d8), # 0-9
(0x0041, 0x0042, 'bf', 0xe38a), # A-B
(0x0043, 0x0043, 'bf', 0x2102), # C
(0x0044, 0x0044, 'bf', 0x2145), # D
(0x0045, 0x0047, 'bf', 0xe38d), # E-G
(0x0048, 0x0048, 'bf', 0x210d), # H
(0x0049, 0x004d, 'bf', 0xe390), # I-M
(0x004e, 0x004e, 'bf', 0x2115), # N
(0x004f, 0x004f, 'bf', 0xe395), # O
(0x0050, 0x0051, 'bf', 0x2119), # P-Q
(0x0052, 0x0052, 'bf', 0x211d), # R
(0x0053, 0x0059, 'bf', 0xe396), # S-Y
(0x005a, 0x005a, 'bf', 0x2124), # Z
(0x0061, 0x0063, 'bf', 0xe39d), # a-c
(0x0064, 0x0065, 'bf', 0x2146), # d-e
(0x0066, 0x0068, 'bf', 0xe3a2), # f-h
(0x0069, 0x006a, 'bf', 0x2148), # i-j
(0x006b, 0x007a, 'bf', 0xe3a7), # k-z
(0x0393, 0x0393, 'bf', 0x213e), # \Gamma
(0x03a0, 0x03a0, 'bf', 0x213f), # \Pi
(0x03a3, 0x03a3, 'bf', 0x2140), # \Sigma
(0x03b3, 0x03b3, 'bf', 0x213d), # \gamma
(0x03c0, 0x03c0, 'bf', 0x213c), # \pi
],
},
'cal':
[
(0x0041, 0x005a, 'it', 0xe22d), # A-Z
],
'circled':
{
'rm':
[
(0x0030, 0x0030, 'rm', 0x24ea), # 0
(0x0031, 0x0039, 'rm', 0x2460), # 1-9
(0x0041, 0x005a, 'rm', 0x24b6), # A-Z
(0x0061, 0x007a, 'rm', 0x24d0) # a-z
],
'it':
[
(0x0030, 0x0030, 'rm', 0x24ea), # 0
(0x0031, 0x0039, 'rm', 0x2460), # 1-9
(0x0041, 0x005a, 'it', 0x24b6), # A-Z
(0x0061, 0x007a, 'it', 0x24d0) # a-z
],
'bf':
[
(0x0030, 0x0030, 'bf', 0x24ea), # 0
(0x0031, 0x0039, 'bf', 0x2460), # 1-9
(0x0041, 0x005a, 'bf', 0x24b6), # A-Z
(0x0061, 0x007a, 'bf', 0x24d0) # a-z
],
},
'frak':
{
'rm':
[
(0x0041, 0x0042, 'rm', 0x1d504), # A-B
(0x0043, 0x0043, 'rm', 0x212d), # C
(0x0044, 0x0047, 'rm', 0x1d507), # D-G
(0x0048, 0x0048, 'rm', 0x210c), # H
(0x0049, 0x0049, 'rm', 0x2111), # I
(0x004a, 0x0051, 'rm', 0x1d50d), # J-Q
(0x0052, 0x0052, 'rm', 0x211c), # R
(0x0053, 0x0059, 'rm', 0x1d516), # S-Y
(0x005a, 0x005a, 'rm', 0x2128), # Z
(0x0061, 0x007a, 'rm', 0x1d51e), # a-z
],
'it':
[
(0x0041, 0x0042, 'rm', 0x1d504), # A-B
(0x0043, 0x0043, 'rm', 0x212d), # C
(0x0044, 0x0047, 'rm', 0x1d507), # D-G
(0x0048, 0x0048, 'rm', 0x210c), # H
(0x0049, 0x0049, 'rm', 0x2111), # I
(0x004a, 0x0051, 'rm', 0x1d50d), # J-Q
(0x0052, 0x0052, 'rm', 0x211c), # R
(0x0053, 0x0059, 'rm', 0x1d516), # S-Y
(0x005a, 0x005a, 'rm', 0x2128), # Z
(0x0061, 0x007a, 'rm', 0x1d51e), # a-z
],
'bf':
[
(0x0041, 0x005a, 'bf', 0x1d56c), # A-Z
(0x0061, 0x007a, 'bf', 0x1d586), # a-z
],
},
'scr':
[
(0x0041, 0x0041, 'it', 0x1d49c), # A
(0x0042, 0x0042, 'it', 0x212c), # B
(0x0043, 0x0044, 'it', 0x1d49e), # C-D
(0x0045, 0x0046, 'it', 0x2130), # E-F
(0x0047, 0x0047, 'it', 0x1d4a2), # G
(0x0048, 0x0048, 'it', 0x210b), # H
(0x0049, 0x0049, 'it', 0x2110), # I
(0x004a, 0x004b, 'it', 0x1d4a5), # J-K
(0x004c, 0x004c, 'it', 0x2112), # L
(0x004d, 0x004d, 'it', 0x2133), # M
(0x004e, 0x0051, 'it', 0x1d4a9), # N-Q
(0x0052, 0x0052, 'it', 0x211b), # R
(0x0053, 0x005a, 'it', 0x1d4ae), # S-Z
(0x0061, 0x0064, 'it', 0x1d4b6), # a-d
(0x0065, 0x0065, 'it', 0x212f), # e
(0x0066, 0x0066, 'it', 0x1d4bb), # f
(0x0067, 0x0067, 'it', 0x210a), # g
(0x0068, 0x006e, 'it', 0x1d4bd), # h-n
(0x006f, 0x006f, 'it', 0x2134), # o
(0x0070, 0x007a, 'it', 0x1d4c5), # p-z
],
'sf':
{
'rm':
[
(0x0030, 0x0039, 'rm', 0x1d7e2), # 0-9
(0x0041, 0x005a, 'rm', 0x1d5a0), # A-Z
(0x0061, 0x007a, 'rm', 0x1d5ba), # a-z
(0x0391, 0x03a9, 'rm', 0xe17d), # \Alpha-\Omega
(0x03b1, 0x03c9, 'rm', 0xe196), # \alpha-\omega
(0x03d1, 0x03d1, 'rm', 0xe1b0), # theta variant
(0x03d5, 0x03d5, 'rm', 0xe1b1), # phi variant
(0x03d6, 0x03d6, 'rm', 0xe1b3), # pi variant
(0x03f1, 0x03f1, 'rm', 0xe1b2), # rho variant
(0x03f5, 0x03f5, 'rm', 0xe1af), # lunate epsilon
(0x2202, 0x2202, 'rm', 0xe17c), # partial differential
],
'it':
[
# These numerals are actually upright. We don't actually
# want italic numerals ever.
(0x0030, 0x0039, 'rm', 0x1d7e2), # 0-9
(0x0041, 0x005a, 'it', 0x1d608), # A-Z
(0x0061, 0x007a, 'it', 0x1d622), # a-z
(0x0391, 0x03a9, 'rm', 0xe17d), # \Alpha-\Omega
(0x03b1, 0x03c9, 'it', 0xe1d8), # \alpha-\omega
(0x03d1, 0x03d1, 'it', 0xe1f2), # theta variant
(0x03d5, 0x03d5, 'it', 0xe1f3), # phi variant
(0x03d6, 0x03d6, 'it', 0xe1f5), # pi variant
(0x03f1, 0x03f1, 'it', 0xe1f4), # rho variant
(0x03f5, 0x03f5, 'it', 0xe1f1), # lunate epsilon
],
'bf':
[
(0x0030, 0x0039, 'bf', 0x1d7ec), # 0-9
(0x0041, 0x005a, 'bf', 0x1d5d4), # A-Z
(0x0061, 0x007a, 'bf', 0x1d5ee), # a-z
(0x0391, 0x03a9, 'bf', 0x1d756), # \Alpha-\Omega
(0x03b1, 0x03c9, 'bf', 0x1d770), # \alpha-\omega
(0x03d1, 0x03d1, 'bf', 0x1d78b), # theta variant
(0x03d5, 0x03d5, 'bf', 0x1d78d), # phi variant
(0x03d6, 0x03d6, 'bf', 0x1d78f), # pi variant
(0x03f0, 0x03f0, 'bf', 0x1d78c), # kappa variant
(0x03f1, 0x03f1, 'bf', 0x1d78e), # rho variant
(0x03f5, 0x03f5, 'bf', 0x1d78a), # lunate epsilon
(0x2202, 0x2202, 'bf', 0x1d789), # partial differential
(0x2207, 0x2207, 'bf', 0x1d76f), # \Nabla
],
},
'tt':
[
(0x0030, 0x0039, 'rm', 0x1d7f6), # 0-9
(0x0041, 0x005a, 'rm', 0x1d670), # A-Z
(0x0061, 0x007a, 'rm', 0x1d68a) # a-z
],
}
|
6d000e5cf29f556a0190665b0b472445c95d80b27c78151ed88b13f1442981a6
|
"""
This module is to support *bbox_inches* option in savefig command.
"""
from matplotlib.transforms import Bbox, TransformedBbox, Affine2D
def adjust_bbox(fig, bbox_inches, fixed_dpi=None):
"""
Temporarily adjust the figure so that only the specified area
(bbox_inches) is saved.
It modifies fig.bbox, fig.bbox_inches,
fig.transFigure._boxout, and fig.patch. While the figure size
changes, the scale of the original figure is conserved. A
function which restores the original values are returned.
"""
origBbox = fig.bbox
origBboxInches = fig.bbox_inches
orig_tight_layout = fig.get_tight_layout()
_boxout = fig.transFigure._boxout
fig.set_tight_layout(False)
asp_list = []
locator_list = []
for ax in fig.axes:
pos = ax.get_position(original=False).frozen()
locator_list.append(ax.get_axes_locator())
asp_list.append(ax.get_aspect())
def _l(a, r, pos=pos):
return pos
ax.set_axes_locator(_l)
ax.set_aspect("auto")
def restore_bbox():
for ax, asp, loc in zip(fig.axes, asp_list, locator_list):
ax.set_aspect(asp)
ax.set_axes_locator(loc)
fig.bbox = origBbox
fig.bbox_inches = origBboxInches
fig.set_tight_layout(orig_tight_layout)
fig.transFigure._boxout = _boxout
fig.transFigure.invalidate()
fig.patch.set_bounds(0, 0, 1, 1)
if fixed_dpi is not None:
tr = Affine2D().scale(fixed_dpi)
dpi_scale = fixed_dpi / fig.dpi
else:
tr = Affine2D().scale(fig.dpi)
dpi_scale = 1.
_bbox = TransformedBbox(bbox_inches, tr)
fig.bbox_inches = Bbox.from_bounds(0, 0,
bbox_inches.width, bbox_inches.height)
x0, y0 = _bbox.x0, _bbox.y0
w1, h1 = fig.bbox.width * dpi_scale, fig.bbox.height * dpi_scale
fig.transFigure._boxout = Bbox.from_bounds(-x0, -y0, w1, h1)
fig.transFigure.invalidate()
fig.bbox = TransformedBbox(fig.bbox_inches, tr)
fig.patch.set_bounds(x0 / w1, y0 / h1,
fig.bbox.width / w1, fig.bbox.height / h1)
return restore_bbox
def process_figure_for_rasterizing(fig, bbox_inches_restore, fixed_dpi=None):
"""
This need to be called when figure dpi changes during the drawing
(e.g., rasterizing). It recovers the bbox and re-adjust it with
the new dpi.
"""
bbox_inches, restore_bbox = bbox_inches_restore
restore_bbox()
r = adjust_bbox(fig, bbox_inches, fixed_dpi)
return bbox_inches, r
|
8e90c1afa6ef9e58549cbc3c3975f5aada54ef0921da3373c480e70edcc0946f
|
r"""
This module supports embedded TeX expressions in matplotlib via dvipng
and dvips for the raster and postscript backends. The tex and
dvipng/dvips information is cached in ~/.matplotlib/tex.cache for reuse between
sessions
Requirements:
* latex
* \*Agg backends: dvipng>=1.6
* PS backend: psfrag, dvips, and Ghostscript>=8.60
Backends:
* \*Agg
* PS
* PDF
For raster output, you can get RGBA numpy arrays from TeX expressions
as follows::
texmanager = TexManager()
s = ('\TeX\ is Number '
'$\displaystyle\sum_{n=1}^\infty\frac{-e^{i\pi}}{2^n}$!')
Z = texmanager.get_rgba(s, fontsize=12, dpi=80, rgb=(1,0,0))
To enable tex rendering of all text in your matplotlib figure, set
:rc:`text.usetex` to True.
"""
import copy
import functools
import glob
import hashlib
import logging
import os
from pathlib import Path
import re
import subprocess
import numpy as np
import matplotlib as mpl
from matplotlib import cbook, dviread, rcParams
_log = logging.getLogger(__name__)
class TexManager(object):
"""
Convert strings to dvi files using TeX, caching the results to a directory.
Repeated calls to this constructor always return the same instance.
"""
cachedir = mpl.get_cachedir()
if cachedir is not None:
texcache = os.path.join(cachedir, 'tex.cache')
Path(texcache).mkdir(parents=True, exist_ok=True)
else:
# Should only happen in a restricted environment (such as Google App
# Engine). Deal with this gracefully by not creating a cache directory.
texcache = None
# Caches.
rgba_arrayd = {}
grey_arrayd = {}
serif = ('cmr', '')
sans_serif = ('cmss', '')
monospace = ('cmtt', '')
cursive = ('pzc', r'\usepackage{chancery}')
font_family = 'serif'
font_families = ('serif', 'sans-serif', 'cursive', 'monospace')
font_info = {
'new century schoolbook': ('pnc', r'\renewcommand{\rmdefault}{pnc}'),
'bookman': ('pbk', r'\renewcommand{\rmdefault}{pbk}'),
'times': ('ptm', r'\usepackage{mathptmx}'),
'palatino': ('ppl', r'\usepackage{mathpazo}'),
'zapf chancery': ('pzc', r'\usepackage{chancery}'),
'cursive': ('pzc', r'\usepackage{chancery}'),
'charter': ('pch', r'\usepackage{charter}'),
'serif': ('cmr', ''),
'sans-serif': ('cmss', ''),
'helvetica': ('phv', r'\usepackage{helvet}'),
'avant garde': ('pag', r'\usepackage{avant}'),
'courier': ('pcr', r'\usepackage{courier}'),
'monospace': ('cmtt', ''),
'computer modern roman': ('cmr', ''),
'computer modern sans serif': ('cmss', ''),
'computer modern typewriter': ('cmtt', '')}
_rc_cache = None
_rc_cache_keys = (
('text.latex.preamble', 'text.latex.unicode', 'text.latex.preview',
'font.family') + tuple('font.' + n for n in font_families))
@functools.lru_cache() # Always return the same instance.
def __new__(cls):
self = object.__new__(cls)
self._reinit()
return self
def _reinit(self):
if self.texcache is None:
raise RuntimeError('Cannot create TexManager, as there is no '
'cache directory available')
Path(self.texcache).mkdir(parents=True, exist_ok=True)
ff = rcParams['font.family']
if len(ff) == 1 and ff[0].lower() in self.font_families:
self.font_family = ff[0].lower()
elif isinstance(ff, str) and ff.lower() in self.font_families:
self.font_family = ff.lower()
else:
_log.info('font.family must be one of (%s) when text.usetex is '
'True. serif will be used by default.',
', '.join(self.font_families))
self.font_family = 'serif'
fontconfig = [self.font_family]
for font_family in self.font_families:
font_family_attr = font_family.replace('-', '_')
for font in rcParams['font.' + font_family]:
if font.lower() in self.font_info:
setattr(self, font_family_attr,
self.font_info[font.lower()])
_log.debug('family: %s, font: %s, info: %s',
font_family, font, self.font_info[font.lower()])
break
else:
_log.debug('%s font is not compatible with usetex.',
font_family)
else:
_log.info('No LaTeX-compatible font found for the %s font '
'family in rcParams. Using default.', font_family)
setattr(self, font_family_attr, self.font_info[font_family])
fontconfig.append(getattr(self, font_family_attr)[0])
# Add a hash of the latex preamble to self._fontconfig so that the
# correct png is selected for strings rendered with same font and dpi
# even if the latex preamble changes within the session
preamble_bytes = self.get_custom_preamble().encode('utf-8')
fontconfig.append(hashlib.md5(preamble_bytes).hexdigest())
self._fontconfig = ''.join(fontconfig)
# The following packages and commands need to be included in the latex
# file's preamble:
cmd = [self.serif[1], self.sans_serif[1], self.monospace[1]]
if self.font_family == 'cursive':
cmd.append(self.cursive[1])
self._font_preamble = '\n'.join(
[r'\usepackage{type1cm}'] + cmd + [r'\usepackage{textcomp}'])
def get_basefile(self, tex, fontsize, dpi=None):
"""
Return a filename based on a hash of the string, fontsize, and dpi.
"""
s = ''.join([tex, self.get_font_config(), '%f' % fontsize,
self.get_custom_preamble(), str(dpi or '')])
return os.path.join(
self.texcache, hashlib.md5(s.encode('utf-8')).hexdigest())
def get_font_config(self):
"""Reinitializes self if relevant rcParams on have changed."""
if self._rc_cache is None:
self._rc_cache = dict.fromkeys(self._rc_cache_keys)
changed = [par for par in self._rc_cache_keys
if rcParams[par] != self._rc_cache[par]]
if changed:
_log.debug('following keys changed: %s', changed)
for k in changed:
_log.debug('%-20s: %-10s -> %-10s',
k, self._rc_cache[k], rcParams[k])
# deepcopy may not be necessary, but feels more future-proof
self._rc_cache[k] = copy.deepcopy(rcParams[k])
_log.debug('RE-INIT\nold fontconfig: %s', self._fontconfig)
self._reinit()
_log.debug('fontconfig: %s', self._fontconfig)
return self._fontconfig
def get_font_preamble(self):
"""
Return a string containing font configuration for the tex preamble.
"""
return self._font_preamble
def get_custom_preamble(self):
"""Return a string containing user additions to the tex preamble."""
return rcParams['text.latex.preamble']
def make_tex(self, tex, fontsize):
"""
Generate a tex file to render the tex string at a specific font size.
Return the file name.
"""
basefile = self.get_basefile(tex, fontsize)
texfile = '%s.tex' % basefile
custom_preamble = self.get_custom_preamble()
fontcmd = {'sans-serif': r'{\sffamily %s}',
'monospace': r'{\ttfamily %s}'}.get(self.font_family,
r'{\rmfamily %s}')
tex = fontcmd % tex
if rcParams['text.latex.unicode']:
unicode_preamble = r"""
\usepackage[utf8]{inputenc}"""
else:
unicode_preamble = ''
s = r"""
\documentclass{article}
%s
%s
%s
\usepackage[papersize={72in,72in},body={70in,70in},margin={1in,1in}]{geometry}
\pagestyle{empty}
\begin{document}
\fontsize{%f}{%f}%s
\end{document}
""" % (self._font_preamble, unicode_preamble, custom_preamble,
fontsize, fontsize * 1.25, tex)
with open(texfile, 'wb') as fh:
if rcParams['text.latex.unicode']:
fh.write(s.encode('utf8'))
else:
try:
fh.write(s.encode('ascii'))
except UnicodeEncodeError as err:
_log.info("You are using unicode and latex, but have not "
"enabled the 'text.latex.unicode' rcParam.")
raise
return texfile
_re_vbox = re.compile(
r"MatplotlibBox:\(([\d.]+)pt\+([\d.]+)pt\)x([\d.]+)pt")
def make_tex_preview(self, tex, fontsize):
"""
Generate a tex file to render the tex string at a specific font size.
It uses the preview.sty to determine the dimension (width, height,
descent) of the output.
Return the file name.
"""
basefile = self.get_basefile(tex, fontsize)
texfile = '%s.tex' % basefile
custom_preamble = self.get_custom_preamble()
fontcmd = {'sans-serif': r'{\sffamily %s}',
'monospace': r'{\ttfamily %s}'}.get(self.font_family,
r'{\rmfamily %s}')
tex = fontcmd % tex
if rcParams['text.latex.unicode']:
unicode_preamble = r"""
\usepackage[utf8]{inputenc}"""
else:
unicode_preamble = ''
# newbox, setbox, immediate, etc. are used to find the box
# extent of the rendered text.
s = r"""
\documentclass{article}
%s
%s
%s
\usepackage[active,showbox,tightpage]{preview}
\usepackage[papersize={72in,72in},body={70in,70in},margin={1in,1in}]{geometry}
%% we override the default showbox as it is treated as an error and makes
%% the exit status not zero
\def\showbox#1%%
{\immediate\write16{MatplotlibBox:(\the\ht#1+\the\dp#1)x\the\wd#1}}
\begin{document}
\begin{preview}
{\fontsize{%f}{%f}%s}
\end{preview}
\end{document}
""" % (self._font_preamble, unicode_preamble, custom_preamble,
fontsize, fontsize * 1.25, tex)
with open(texfile, 'wb') as fh:
if rcParams['text.latex.unicode']:
fh.write(s.encode('utf8'))
else:
try:
fh.write(s.encode('ascii'))
except UnicodeEncodeError as err:
_log.info("You are using unicode and latex, but have not "
"enabled the 'text.latex.unicode' rcParam.")
raise
return texfile
def _run_checked_subprocess(self, command, tex):
_log.debug(command)
try:
report = subprocess.check_output(command,
cwd=self.texcache,
stderr=subprocess.STDOUT)
except FileNotFoundError as exc:
raise RuntimeError(
'Failed to process string with tex because {} could not be '
'found'.format(command[0])) from exc
except subprocess.CalledProcessError as exc:
raise RuntimeError(
'{prog} was not able to process the following string:\n'
'{tex!r}\n\n'
'Here is the full report generated by {prog}:\n'
'{exc}\n\n'.format(
prog=command[0],
tex=tex.encode('unicode_escape'),
exc=exc.output.decode('utf-8'))) from exc
_log.debug(report)
return report
def make_dvi(self, tex, fontsize):
"""
Generate a dvi file containing latex's layout of tex string.
Return the file name.
"""
if rcParams['text.latex.preview']:
return self.make_dvi_preview(tex, fontsize)
basefile = self.get_basefile(tex, fontsize)
dvifile = '%s.dvi' % basefile
if not os.path.exists(dvifile):
texfile = self.make_tex(tex, fontsize)
with cbook._lock_path(texfile):
self._run_checked_subprocess(
["latex", "-interaction=nonstopmode", "--halt-on-error",
texfile], tex)
for fname in glob.glob(basefile + '*'):
if not fname.endswith(('dvi', 'tex')):
try:
os.remove(fname)
except OSError:
pass
return dvifile
def make_dvi_preview(self, tex, fontsize):
"""
Generate a dvi file containing latex's layout of tex string.
It calls make_tex_preview() method and store the size information
(width, height, descent) in a separate file.
Return the file name.
"""
basefile = self.get_basefile(tex, fontsize)
dvifile = '%s.dvi' % basefile
baselinefile = '%s.baseline' % basefile
if not os.path.exists(dvifile) or not os.path.exists(baselinefile):
texfile = self.make_tex_preview(tex, fontsize)
report = self._run_checked_subprocess(
["latex", "-interaction=nonstopmode", "--halt-on-error",
texfile], tex)
# find the box extent information in the latex output
# file and store them in ".baseline" file
m = TexManager._re_vbox.search(report.decode("utf-8"))
with open(basefile + '.baseline', "w") as fh:
fh.write(" ".join(m.groups()))
for fname in glob.glob(basefile + '*'):
if not fname.endswith(('dvi', 'tex', 'baseline')):
try:
os.remove(fname)
except OSError:
pass
return dvifile
def make_png(self, tex, fontsize, dpi):
"""
Generate a png file containing latex's rendering of tex string.
Return the file name.
"""
basefile = self.get_basefile(tex, fontsize, dpi)
pngfile = '%s.png' % basefile
# see get_rgba for a discussion of the background
if not os.path.exists(pngfile):
dvifile = self.make_dvi(tex, fontsize)
self._run_checked_subprocess(
["dvipng", "-bg", "Transparent", "-D", str(dpi),
"-T", "tight", "-o", pngfile, dvifile], tex)
return pngfile
def get_grey(self, tex, fontsize=None, dpi=None):
"""Return the alpha channel."""
from matplotlib import _png
key = tex, self.get_font_config(), fontsize, dpi
alpha = self.grey_arrayd.get(key)
if alpha is None:
pngfile = self.make_png(tex, fontsize, dpi)
X = _png.read_png(os.path.join(self.texcache, pngfile))
self.grey_arrayd[key] = alpha = X[:, :, -1]
return alpha
def get_rgba(self, tex, fontsize=None, dpi=None, rgb=(0, 0, 0)):
"""Return latex's rendering of the tex string as an rgba array."""
if not fontsize:
fontsize = rcParams['font.size']
if not dpi:
dpi = rcParams['savefig.dpi']
r, g, b = rgb
key = tex, self.get_font_config(), fontsize, dpi, tuple(rgb)
Z = self.rgba_arrayd.get(key)
if Z is None:
alpha = self.get_grey(tex, fontsize, dpi)
Z = np.dstack([r, g, b, alpha])
self.rgba_arrayd[key] = Z
return Z
def get_text_width_height_descent(self, tex, fontsize, renderer=None):
"""Return width, height and descent of the text."""
if tex.strip() == '':
return 0, 0, 0
dpi_fraction = renderer.points_to_pixels(1.) if renderer else 1
if rcParams['text.latex.preview']:
# use preview.sty
basefile = self.get_basefile(tex, fontsize)
baselinefile = '%s.baseline' % basefile
if not os.path.exists(baselinefile):
dvifile = self.make_dvi_preview(tex, fontsize)
with open(baselinefile) as fh:
l = fh.read().split()
height, depth, width = [float(l1) * dpi_fraction for l1 in l]
return width, height + depth, depth
else:
# use dviread. It sometimes returns a wrong descent.
dvifile = self.make_dvi(tex, fontsize)
with dviread.Dvi(dvifile, 72 * dpi_fraction) as dvi:
page, = dvi
# A total height (including the descent) needs to be returned.
return page.width, page.height + page.descent, page.descent
|
5acd7815245c0f83f1e363b253dba791e8c5c13d0660fbdc5d81602af780a9cd
|
"""
Matplotlib provides sophisticated date plotting capabilities, standing on the
shoulders of python :mod:`datetime` and the add-on module :mod:`dateutil`.
.. _date-format:
Matplotlib date format
----------------------
Matplotlib represents dates using floating point numbers specifying the number
of days since 0001-01-01 UTC, plus 1. For example, 0001-01-01, 06:00 is 1.25,
not 0.25. Values < 1, i.e. dates before 0001-01-01 UTC are not supported.
There are a number of helper functions to convert between :mod:`datetime`
objects and Matplotlib dates:
.. currentmodule:: matplotlib.dates
.. autosummary::
:nosignatures:
datestr2num
date2num
num2date
num2timedelta
epoch2num
num2epoch
mx2num
drange
.. note::
Like Python's datetime, mpl uses the Gregorian calendar for all
conversions between dates and floating point numbers. This practice
is not universal, and calendar differences can cause confusing
differences between what Python and mpl give as the number of days
since 0001-01-01 and what other software and databases yield. For
example, the US Naval Observatory uses a calendar that switches
from Julian to Gregorian in October, 1582. Hence, using their
calculator, the number of days between 0001-01-01 and 2006-04-01 is
732403, whereas using the Gregorian calendar via the datetime
module we find::
In [1]: date(2006, 4, 1).toordinal() - date(1, 1, 1).toordinal()
Out[1]: 732401
All the Matplotlib date converters, tickers and formatters are timezone aware.
If no explicit timezone is provided, the rcParam ``timezone`` is assumed. If
you want to use a custom time zone, pass a :class:`datetime.tzinfo` instance
with the tz keyword argument to :func:`num2date`, :func:`.plot_date`, and any
custom date tickers or locators you create.
A wide range of specific and general purpose date tick locators and
formatters are provided in this module. See
:mod:`matplotlib.ticker` for general information on tick locators
and formatters. These are described below.
The dateutil_ module provides additional code to handle date ticking, making it
easy to place ticks on any kinds of dates. See examples below.
.. _dateutil: https://dateutil.readthedocs.io
Date tickers
------------
Most of the date tickers can locate single or multiple values. For
example::
# import constants for the days of the week
from matplotlib.dates import MO, TU, WE, TH, FR, SA, SU
# tick on mondays every week
loc = WeekdayLocator(byweekday=MO, tz=tz)
# tick on mondays and saturdays
loc = WeekdayLocator(byweekday=(MO, SA))
In addition, most of the constructors take an interval argument::
# tick on mondays every second week
loc = WeekdayLocator(byweekday=MO, interval=2)
The rrule locator allows completely general date ticking::
# tick every 5th easter
rule = rrulewrapper(YEARLY, byeaster=1, interval=5)
loc = RRuleLocator(rule)
Here are all the date tickers:
* :class:`MicrosecondLocator`: locate microseconds
* :class:`SecondLocator`: locate seconds
* :class:`MinuteLocator`: locate minutes
* :class:`HourLocator`: locate hours
* :class:`DayLocator`: locate specified days of the month
* :class:`WeekdayLocator`: Locate days of the week, e.g., MO, TU
* :class:`MonthLocator`: locate months, e.g., 7 for july
* :class:`YearLocator`: locate years that are multiples of base
* :class:`RRuleLocator`: locate using a `matplotlib.dates.rrulewrapper`.
`.rrulewrapper` is a simple wrapper around dateutil_'s `dateutil.rrule`
which allow almost arbitrary date tick specifications. See :doc:`rrule
example </gallery/ticks_and_spines/date_demo_rrule>`.
* :class:`AutoDateLocator`: On autoscale, this class picks the best
:class:`DateLocator` (e.g., :class:`RRuleLocator`)
to set the view limits and the tick
locations. If called with ``interval_multiples=True`` it will
make ticks line up with sensible multiples of the tick intervals. E.g.
if the interval is 4 hours, it will pick hours 0, 4, 8, etc as ticks.
This behaviour is not guaranteed by default.
Date formatters
---------------
Here all all the date formatters:
* :class:`AutoDateFormatter`: attempts to figure out the best format
to use. This is most useful when used with the :class:`AutoDateLocator`.
* :class:`ConciseDateFormatter`: also attempts to figure out the best
format to use, and to make the format as compact as possible while
still having complete date information. This is most useful when used
with the :class:`AutoDateLocator`.
* :class:`DateFormatter`: use :func:`strftime` format strings
* :class:`IndexDateFormatter`: date plots with implicit *x*
indexing.
"""
import datetime
import functools
import logging
import math
import re
import time
import warnings
from dateutil.rrule import (rrule, MO, TU, WE, TH, FR, SA, SU, YEARLY,
MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY,
SECONDLY)
from dateutil.relativedelta import relativedelta
import dateutil.parser
import dateutil.tz
import numpy as np
import matplotlib
from matplotlib import rcParams
import matplotlib.units as units
import matplotlib.cbook as cbook
import matplotlib.ticker as ticker
__all__ = ('datestr2num', 'date2num', 'num2date', 'num2timedelta', 'drange',
'epoch2num', 'num2epoch', 'mx2num', 'DateFormatter',
'ConciseDateFormatter', 'IndexDateFormatter', 'AutoDateFormatter',
'DateLocator', 'RRuleLocator', 'AutoDateLocator', 'YearLocator',
'MonthLocator', 'WeekdayLocator',
'DayLocator', 'HourLocator', 'MinuteLocator',
'SecondLocator', 'MicrosecondLocator',
'rrule', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU',
'YEARLY', 'MONTHLY', 'WEEKLY', 'DAILY',
'HOURLY', 'MINUTELY', 'SECONDLY', 'MICROSECONDLY', 'relativedelta',
'seconds', 'minutes', 'hours', 'weeks')
_log = logging.getLogger(__name__)
UTC = datetime.timezone.utc
def _get_rc_timezone():
"""Retrieve the preferred timezone from the rcParams dictionary."""
s = matplotlib.rcParams['timezone']
if s == 'UTC':
return UTC
return dateutil.tz.gettz(s)
"""
Time-related constants.
"""
EPOCH_OFFSET = float(datetime.datetime(1970, 1, 1).toordinal())
JULIAN_OFFSET = 1721424.5 # Julian date at 0001-01-01
MICROSECONDLY = SECONDLY + 1
HOURS_PER_DAY = 24.
MIN_PER_HOUR = 60.
SEC_PER_MIN = 60.
MONTHS_PER_YEAR = 12.
DAYS_PER_WEEK = 7.
DAYS_PER_MONTH = 30.
DAYS_PER_YEAR = 365.0
MINUTES_PER_DAY = MIN_PER_HOUR * HOURS_PER_DAY
SEC_PER_HOUR = SEC_PER_MIN * MIN_PER_HOUR
SEC_PER_DAY = SEC_PER_HOUR * HOURS_PER_DAY
SEC_PER_WEEK = SEC_PER_DAY * DAYS_PER_WEEK
MUSECONDS_PER_DAY = 1e6 * SEC_PER_DAY
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY = (
MO, TU, WE, TH, FR, SA, SU)
WEEKDAYS = (MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY)
def _to_ordinalf(dt):
"""
Convert :mod:`datetime` or :mod:`date` to the Gregorian date as UTC float
days, preserving hours, minutes, seconds and microseconds. Return value
is a :func:`float`.
"""
# Convert to UTC
tzi = getattr(dt, 'tzinfo', None)
if tzi is not None:
dt = dt.astimezone(UTC)
tzi = UTC
base = float(dt.toordinal())
# If it's sufficiently datetime-like, it will have a `date()` method
cdate = getattr(dt, 'date', lambda: None)()
if cdate is not None:
# Get a datetime object at midnight UTC
midnight_time = datetime.time(0, tzinfo=tzi)
rdt = datetime.datetime.combine(cdate, midnight_time)
# Append the seconds as a fraction of a day
base += (dt - rdt).total_seconds() / SEC_PER_DAY
return base
# a version of _to_ordinalf that can operate on numpy arrays
_to_ordinalf_np_vectorized = np.vectorize(_to_ordinalf)
def _dt64_to_ordinalf(d):
"""
Convert `numpy.datetime64` or an ndarray of those types to Gregorian
date as UTC float. Roundoff is via float64 precision. Practically:
microseconds for dates between 290301 BC, 294241 AD, milliseconds for
larger dates (see `numpy.datetime64`). Nanoseconds aren't possible
because we do times compared to ``0001-01-01T00:00:00`` (plus one day).
"""
# the "extra" ensures that we at least allow the dynamic range out to
# seconds. That should get out to +/-2e11 years.
extra = (d - d.astype('datetime64[s]')).astype('timedelta64[ns]')
t0 = np.datetime64('0001-01-01T00:00:00', 's')
dt = (d.astype('datetime64[s]') - t0).astype(np.float64)
dt += extra.astype(np.float64) / 1.0e9
dt = dt / SEC_PER_DAY + 1.0
NaT_int = np.datetime64('NaT').astype(np.int64)
d_int = d.astype(np.int64)
try:
dt[d_int == NaT_int] = np.nan
except TypeError:
if d_int == NaT_int:
dt = np.nan
return dt
def _from_ordinalf(x, tz=None):
"""
Convert Gregorian float of the date, preserving hours, minutes,
seconds and microseconds. Return value is a `.datetime`.
The input date *x* is a float in ordinal days at UTC, and the output will
be the specified `.datetime` object corresponding to that time in
timezone *tz*, or if *tz* is ``None``, in the timezone specified in
:rc:`timezone`.
"""
if tz is None:
tz = _get_rc_timezone()
ix, remainder = divmod(x, 1)
ix = int(ix)
if ix < 1:
raise ValueError('Cannot convert {} to a date. This often happens if '
'non-datetime values are passed to an axis that '
'expects datetime objects.'.format(ix))
dt = datetime.datetime.fromordinal(ix).replace(tzinfo=UTC)
# Since the input date `x` float is unable to preserve microsecond
# precision of time representation in non-antique years, the
# resulting datetime is rounded to the nearest multiple of
# `musec_prec`. A value of 20 is appropriate for current dates.
musec_prec = 20
remainder_musec = int(round(remainder * MUSECONDS_PER_DAY / musec_prec)
* musec_prec)
# For people trying to plot with full microsecond precision, enable
# an early-year workaround
if x < 30 * 365:
remainder_musec = int(round(remainder * MUSECONDS_PER_DAY))
# add hours, minutes, seconds, microseconds
dt += datetime.timedelta(microseconds=remainder_musec)
return dt.astimezone(tz)
# a version of _from_ordinalf that can operate on numpy arrays
_from_ordinalf_np_vectorized = np.vectorize(_from_ordinalf)
@cbook.deprecated(
"3.1", alternative="time.strptime or dateutil.parser.parse or datestr2num")
class strpdate2num(object):
"""
Use this class to parse date strings to matplotlib datenums when
you know the date format string of the date you are parsing.
"""
def __init__(self, fmt):
""" fmt: any valid strptime format is supported """
self.fmt = fmt
def __call__(self, s):
"""s : string to be converted
return value: a date2num float
"""
return date2num(datetime.datetime(*time.strptime(s, self.fmt)[:6]))
@cbook.deprecated(
"3.1", alternative="time.strptime or dateutil.parser.parse or datestr2num")
class bytespdate2num(strpdate2num):
"""
Use this class to parse date strings to matplotlib datenums when
you know the date format string of the date you are parsing. See
:doc:`/gallery/misc/load_converter.py`.
"""
def __init__(self, fmt, encoding='utf-8'):
"""
Args:
fmt: any valid strptime format is supported
encoding: encoding to use on byte input (default: 'utf-8')
"""
super().__init__(fmt)
self.encoding = encoding
def __call__(self, b):
"""
Args:
b: byte input to be converted
Returns:
A date2num float
"""
s = b.decode(self.encoding)
return super().__call__(s)
# a version of dateutil.parser.parse that can operate on numpy arrays
_dateutil_parser_parse_np_vectorized = np.vectorize(dateutil.parser.parse)
def datestr2num(d, default=None):
"""
Convert a date string to a datenum using :func:`dateutil.parser.parse`.
Parameters
----------
d : string or sequence of strings
The dates to convert.
default : datetime instance, optional
The default date to use when fields are missing in *d*.
"""
if isinstance(d, str):
dt = dateutil.parser.parse(d, default=default)
return date2num(dt)
else:
if default is not None:
d = [dateutil.parser.parse(s, default=default) for s in d]
d = np.asarray(d)
if not d.size:
return d
return date2num(_dateutil_parser_parse_np_vectorized(d))
def date2num(d):
"""
Convert datetime objects to Matplotlib dates.
Parameters
----------
d : `datetime.datetime` or `numpy.datetime64` or sequences of these
Returns
-------
float or sequence of floats
Number of days (fraction part represents hours, minutes, seconds, ms)
since 0001-01-01 00:00:00 UTC, plus one.
Notes
-----
The addition of one here is a historical artifact. Also, note that the
Gregorian calendar is assumed; this is not universal practice.
For details see the module docstring.
"""
if hasattr(d, "values"):
# this unpacks pandas series or dataframes...
d = d.values
if not np.iterable(d):
if (isinstance(d, np.datetime64) or
(isinstance(d, np.ndarray) and
np.issubdtype(d.dtype, np.datetime64))):
return _dt64_to_ordinalf(d)
return _to_ordinalf(d)
else:
d = np.asarray(d)
if np.issubdtype(d.dtype, np.datetime64):
return _dt64_to_ordinalf(d)
if not d.size:
return d
return _to_ordinalf_np_vectorized(d)
def julian2num(j):
"""
Convert a Julian date (or sequence) to a Matplotlib date (or sequence).
Parameters
----------
j : float or sequence of floats
Julian date(s)
Returns
-------
float or sequence of floats
Matplotlib date(s)
"""
if np.iterable(j):
j = np.asarray(j)
return j - JULIAN_OFFSET
def num2julian(n):
"""
Convert a Matplotlib date (or sequence) to a Julian date (or sequence).
Parameters
----------
n : float or sequence of floats
Matplotlib date(s)
Returns
-------
float or sequence of floats
Julian date(s)
"""
if np.iterable(n):
n = np.asarray(n)
return n + JULIAN_OFFSET
def num2date(x, tz=None):
"""
Convert Matplotlib dates to `~datetime.datetime` objects.
Parameters
----------
x : float or sequence of floats
Number of days (fraction part represents hours, minutes, seconds)
since 0001-01-01 00:00:00 UTC, plus one.
tz : string, optional
Timezone of *x* (defaults to rcparams ``timezone``).
Returns
-------
`~datetime.datetime` or sequence of `~datetime.datetime`
Dates are returned in timezone *tz*.
If *x* is a sequence, a sequence of :class:`datetime` objects will
be returned.
Notes
-----
The addition of one here is a historical artifact. Also, note that the
Gregorian calendar is assumed; this is not universal practice.
For details, see the module docstring.
"""
if tz is None:
tz = _get_rc_timezone()
if not np.iterable(x):
return _from_ordinalf(x, tz)
else:
x = np.asarray(x)
if not x.size:
return x
return _from_ordinalf_np_vectorized(x, tz).tolist()
def _ordinalf_to_timedelta(x):
return datetime.timedelta(days=x)
_ordinalf_to_timedelta_np_vectorized = np.vectorize(_ordinalf_to_timedelta)
def num2timedelta(x):
"""
Convert number of days to a `~datetime.timedelta` object.
If *x* is a sequence, a sequence of `~datetime.timedelta` objects will
be returned.
Parameters
----------
x : float, sequence of floats
Number of days. The fraction part represents hours, minutes, seconds.
Returns
-------
`datetime.timedelta` or list[`datetime.timedelta`]
"""
if not np.iterable(x):
return _ordinalf_to_timedelta(x)
else:
x = np.asarray(x)
if not x.size:
return x
return _ordinalf_to_timedelta_np_vectorized(x).tolist()
def drange(dstart, dend, delta):
"""
Return a sequence of equally spaced Matplotlib dates.
The dates start at *dstart* and reach up to, but not including *dend*.
They are spaced by *delta*.
Parameters
----------
dstart, dend : `~datetime.datetime`
The date limits.
delta : `datetime.timedelta`
Spacing of the dates.
Returns
-------
drange : `numpy.array`
A list floats representing Matplotlib dates.
"""
f1 = date2num(dstart)
f2 = date2num(dend)
step = delta.total_seconds() / SEC_PER_DAY
# calculate the difference between dend and dstart in times of delta
num = int(np.ceil((f2 - f1) / step))
# calculate end of the interval which will be generated
dinterval_end = dstart + num * delta
# ensure, that an half open interval will be generated [dstart, dend)
if dinterval_end >= dend:
# if the endpoint is greater than dend, just subtract one delta
dinterval_end -= delta
num -= 1
f2 = date2num(dinterval_end) # new float-endpoint
return np.linspace(f1, f2, num + 1)
## date tickers and formatters ###
class DateFormatter(ticker.Formatter):
"""
Tick location is seconds since the epoch. Use a :func:`strftime`
format string.
Python only supports :mod:`datetime` :func:`strftime` formatting
for years greater than 1900. Thanks to Andrew Dalke, Dalke
Scientific Software who contributed the :func:`strftime` code
below to include dates earlier than this year.
"""
illegal_s = re.compile(r"((^|[^%])(%%)*%s)")
def __init__(self, fmt, tz=None):
"""
*fmt* is a :func:`strftime` format string; *tz* is the
:class:`tzinfo` instance.
"""
if tz is None:
tz = _get_rc_timezone()
self.fmt = fmt
self.tz = tz
def __call__(self, x, pos=0):
if x == 0:
raise ValueError('DateFormatter found a value of x=0, which is '
'an illegal date; this usually occurs because '
'you have not informed the axis that it is '
'plotting dates, e.g., with ax.xaxis_date()')
return num2date(x, self.tz).strftime(self.fmt)
def set_tzinfo(self, tz):
self.tz = tz
@cbook.deprecated("3.0")
def _replace_common_substr(self, s1, s2, sub1, sub2, replacement):
"""Helper function for replacing substrings sub1 and sub2
located at the same indexes in strings s1 and s2 respectively,
with the string replacement. It is expected that sub1 and sub2
have the same length. Returns the pair s1, s2 after the
substitutions.
"""
# Find common indexes of substrings sub1 in s1 and sub2 in s2
# and make substitutions inplace. Because this is inplace,
# it is okay if len(replacement) != len(sub1), len(sub2).
i = 0
while True:
j = s1.find(sub1, i)
if j == -1:
break
i = j + 1
if s2[j:j + len(sub2)] != sub2:
continue
s1 = s1[:j] + replacement + s1[j + len(sub1):]
s2 = s2[:j] + replacement + s2[j + len(sub2):]
return s1, s2
@cbook.deprecated("3.0")
def strftime_pre_1900(self, dt, fmt=None):
"""Call time.strftime for years before 1900 by rolling
forward a multiple of 28 years.
*fmt* is a :func:`strftime` format string.
Dalke: I hope I did this math right. Every 28 years the
calendar repeats, except through century leap years excepting
the 400 year leap years. But only if you're using the Gregorian
calendar.
"""
if fmt is None:
fmt = self.fmt
# Since python's time module's strftime implementation does not
# support %f microsecond (but the datetime module does), use a
# regular expression substitution to replace instances of %f.
# Note that this can be useful since python's floating-point
# precision representation for datetime causes precision to be
# more accurate closer to year 0 (around the year 2000, precision
# can be at 10s of microseconds).
fmt = re.sub(r'((^|[^%])(%%)*)%f',
r'\g<1>{0:06d}'.format(dt.microsecond), fmt)
year = dt.year
# For every non-leap year century, advance by
# 6 years to get into the 28-year repeat cycle
delta = 2000 - year
off = 6 * (delta // 100 + delta // 400)
year = year + off
# Move to between the years 1973 and 2000
year1 = year + ((2000 - year) // 28) * 28
year2 = year1 + 28
timetuple = dt.timetuple()
# Generate timestamp string for year and year+28
s1 = time.strftime(fmt, (year1,) + timetuple[1:])
s2 = time.strftime(fmt, (year2,) + timetuple[1:])
# Replace instances of respective years (both 2-digit and 4-digit)
# that are located at the same indexes of s1, s2 with dt's year.
# Note that C++'s strftime implementation does not use padded
# zeros or padded whitespace for %y or %Y for years before 100, but
# uses padded zeros for %x. (For example, try the runnable examples
# with .tm_year in the interval [-1900, -1800] on
# http://en.cppreference.com/w/c/chrono/strftime.) For ease of
# implementation, we always use padded zeros for %y, %Y, and %x.
s1, s2 = self._replace_common_substr(s1, s2,
"{0:04d}".format(year1),
"{0:04d}".format(year2),
"{0:04d}".format(dt.year))
s1, s2 = self._replace_common_substr(s1, s2,
"{0:02d}".format(year1 % 100),
"{0:02d}".format(year2 % 100),
"{0:02d}".format(dt.year % 100))
return cbook.unicode_safe(s1)
@cbook.deprecated("3.0")
def strftime(self, dt, fmt=None):
"""
Refer to documentation for :meth:`datetime.datetime.strftime`
*fmt* is a :meth:`datetime.datetime.strftime` format string.
Warning: For years before 1900, depending upon the current
locale it is possible that the year displayed with %x might
be incorrect. For years before 100, %y and %Y will yield
zero-padded strings.
"""
if fmt is None:
fmt = self.fmt
fmt = self.illegal_s.sub(r"\1", fmt)
fmt = fmt.replace("%s", "s")
if dt.year >= 1900:
# Note: in python 3.3 this is okay for years >= 1000,
# refer to http://bugs.python.org/issue1777412
return cbook.unicode_safe(dt.strftime(fmt))
return self.strftime_pre_1900(dt, fmt)
class IndexDateFormatter(ticker.Formatter):
"""
Use with :class:`~matplotlib.ticker.IndexLocator` to cycle format
strings by index.
"""
def __init__(self, t, fmt, tz=None):
"""
*t* is a sequence of dates (floating point days). *fmt* is a
:func:`strftime` format string.
"""
if tz is None:
tz = _get_rc_timezone()
self.t = t
self.fmt = fmt
self.tz = tz
def __call__(self, x, pos=0):
'Return the label for time *x* at position *pos*'
ind = int(np.round(x))
if ind >= len(self.t) or ind <= 0:
return ''
return num2date(self.t[ind], self.tz).strftime(self.fmt)
class ConciseDateFormatter(ticker.Formatter):
"""
This class attempts to figure out the best format to use for the
date, and to make it as compact as possible, but still be complete. This is
most useful when used with the :class:`AutoDateLocator`::
>>> locator = AutoDateLocator()
>>> formatter = ConciseDateFormatter(locator)
Parameters
----------
locator : `.ticker.Locator`
Locator that this axis is using.
tz : string, optional
Passed to `.dates.date2num`.
formats : list of 6 strings, optional
Format strings for 6 levels of tick labelling: mostly years,
months, days, hours, minutes, and seconds. Strings use
the same format codes as `strftime`. Default is
``['%Y', '%b', '%d', '%H:%M', '%H:%M', '%S.%f']``
zero_formats : list of 6 strings, optional
Format strings for tick labels that are "zeros" for a given tick
level. For instance, if most ticks are months, ticks around 1 Jan 2005
will be labeled "Dec", "2005", "Feb". The default is
``['', '%Y', '%b', '%b-%d', '%H:%M', '%H:%M']``
offset_formats : list of 6 strings, optional
Format strings for the 6 levels that is applied to the "offset"
string found on the right side of an x-axis, or top of a y-axis.
Combined with the tick labels this should completely specify the
date. The default is::
['', '%Y', '%Y-%b', '%Y-%b-%d', '%Y-%b-%d', '%Y-%b-%d %H:%M']
show_offset : bool
Whether to show the offset or not. Default is ``True``.
Examples
--------
See :doc:`/gallery/ticks_and_spines/date_concise_formatter`
.. plot::
import datetime
import matplotlib.dates as mdates
base = datetime.datetime(2005, 2, 1)
dates = np.array([base + datetime.timedelta(hours=(2 * i))
for i in range(732)])
N = len(dates)
np.random.seed(19680801)
y = np.cumsum(np.random.randn(N))
fig, ax = plt.subplots(constrained_layout=True)
locator = mdates.AutoDateLocator()
formatter = mdates.ConciseDateFormatter(locator)
ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(formatter)
ax.plot(dates, y)
ax.set_title('Concise Date Formatter')
"""
def __init__(self, locator, tz=None, formats=None, offset_formats=None,
zero_formats=None, show_offset=True):
"""
Autoformat the date labels. The default format is used to form an
initial string, and then redundant elements are removed.
"""
self._locator = locator
self._tz = tz
self.defaultfmt = '%Y'
# there are 6 levels with each level getting a specific format
# 0: mostly years, 1: months, 2: days,
# 3: hours, 4: minutes, 5: seconds
if formats:
if len(formats) != 6:
raise ValueError('formats argument must be a list of '
'6 format strings (or None)')
self.formats = formats
else:
self.formats = ['%Y', # ticks are mostly years
'%b', # ticks are mostly months
'%d', # ticks are mostly days
'%H:%M', # hrs
'%H:%M', # min
'%S.%f', # secs
]
# fmt for zeros ticks at this level. These are
# ticks that should be labeled w/ info the level above.
# like 1 Jan can just be labled "Jan". 02:02:00 can
# just be labeled 02:02.
if zero_formats:
if len(formats) != 6:
raise ValueError('zero_formats argument must be a list of '
'6 format strings (or None)')
self.zero_formats = zero_formats
elif formats:
# use the users formats for the zero tick formats
self.zero_formats = [''] + self.formats[:-1]
else:
# make the defaults a bit nicer:
self.zero_formats = [''] + self.formats[:-1]
self.zero_formats[3] = '%b-%d'
if offset_formats:
if len(offset_formats) != 6:
raise ValueError('offsetfmts argument must be a list of '
'6 format strings (or None)')
self.offset_formats = offset_formats
else:
self.offset_formats = ['',
'%Y',
'%Y-%b',
'%Y-%b-%d',
'%Y-%b-%d',
'%Y-%b-%d %H:%M']
self.offset_string = ''
self.show_offset = show_offset
def __call__(self, x, pos=None):
formatter = DateFormatter(self.defaultfmt, self._tz)
return formatter(x, pos=pos)
def format_ticks(self, values):
tickdatetime = [num2date(value) for value in values]
tickdate = np.array([tdt.timetuple()[:6] for tdt in tickdatetime])
# basic algorithm:
# 1) only display a part of the date if it changes over the ticks.
# 2) don't display the smaller part of the date if:
# it is always the same or if it is the start of the
# year, month, day etc.
# fmt for most ticks at this level
fmts = self.formats
# format beginnings of days, months, years, etc...
zerofmts = self.zero_formats
# offset fmt are for the offset in the upper left of the
# or lower right of the axis.
offsetfmts = self.offset_formats
# determine the level we will label at:
# mostly 0: years, 1: months, 2: days,
# 3: hours, 4: minutes, 5: seconds, 6: microseconds
for level in range(5, -1, -1):
if len(np.unique(tickdate[:, level])) > 1:
break
# level is the basic level we will label at.
# now loop through and decide the actual ticklabels
zerovals = [0, 1, 1, 0, 0, 0, 0]
labels = [''] * len(tickdate)
for nn in range(len(tickdate)):
if level < 5:
if tickdate[nn][level] == zerovals[level]:
fmt = zerofmts[level]
else:
fmt = fmts[level]
else:
# special handling for seconds + microseconds
if (tickdatetime[nn].second == tickdatetime[nn].microsecond
== 0):
fmt = zerofmts[level]
else:
fmt = fmts[level]
labels[nn] = tickdatetime[nn].strftime(fmt)
# special handling of seconds and microseconds:
# strip extra zeros and decimal if possible.
# this is complicated by two factors. 1) we have some level-4 strings
# here (i.e. 03:00, '0.50000', '1.000') 2) we would like to have the
# same number of decimals for each string (i.e. 0.5 and 1.0).
if level >= 5:
trailing_zeros = min(
(len(s) - len(s.rstrip('0')) for s in labels if '.' in s),
default=None)
if trailing_zeros:
for nn in range(len(labels)):
if '.' in labels[nn]:
labels[nn] = labels[nn][:-trailing_zeros].rstrip('.')
if self.show_offset:
# set the offset string:
self.offset_string = tickdatetime[-1].strftime(offsetfmts[level])
return labels
def get_offset(self):
return self.offset_string
def format_data_short(self, value):
return num2date(value).strftime('%Y-%m-%d %H:%M:%S')
class AutoDateFormatter(ticker.Formatter):
"""
This class attempts to figure out the best format to use. This is
most useful when used with the :class:`AutoDateLocator`.
The AutoDateFormatter has a scale dictionary that maps the scale
of the tick (the distance in days between one major tick) and a
format string. The default looks like this::
self.scaled = {
DAYS_PER_YEAR: rcParams['date.autoformat.year'],
DAYS_PER_MONTH: rcParams['date.autoformat.month'],
1.0: rcParams['date.autoformat.day'],
1. / HOURS_PER_DAY: rcParams['date.autoformat.hour'],
1. / (MINUTES_PER_DAY): rcParams['date.autoformat.minute'],
1. / (SEC_PER_DAY): rcParams['date.autoformat.second'],
1. / (MUSECONDS_PER_DAY): rcParams['date.autoformat.microsecond'],
}
The algorithm picks the key in the dictionary that is >= the
current scale and uses that format string. You can customize this
dictionary by doing::
>>> locator = AutoDateLocator()
>>> formatter = AutoDateFormatter(locator)
>>> formatter.scaled[1/(24.*60.)] = '%M:%S' # only show min and sec
A custom :class:`~matplotlib.ticker.FuncFormatter` can also be used.
The following example shows how to use a custom format function to strip
trailing zeros from decimal seconds and adds the date to the first
ticklabel::
>>> def my_format_function(x, pos=None):
... x = matplotlib.dates.num2date(x)
... if pos == 0:
... fmt = '%D %H:%M:%S.%f'
... else:
... fmt = '%H:%M:%S.%f'
... label = x.strftime(fmt)
... label = label.rstrip("0")
... label = label.rstrip(".")
... return label
>>> from matplotlib.ticker import FuncFormatter
>>> formatter.scaled[1/(24.*60.)] = FuncFormatter(my_format_function)
"""
# This can be improved by providing some user-level direction on
# how to choose the best format (precedence, etc...)
# Perhaps a 'struct' that has a field for each time-type where a
# zero would indicate "don't show" and a number would indicate
# "show" with some sort of priority. Same priorities could mean
# show all with the same priority.
# Or more simply, perhaps just a format string for each
# possibility...
def __init__(self, locator, tz=None, defaultfmt='%Y-%m-%d'):
"""
Autoformat the date labels. The default format is the one to use
if none of the values in ``self.scaled`` are greater than the unit
returned by ``locator._get_unit()``.
"""
self._locator = locator
self._tz = tz
self.defaultfmt = defaultfmt
self._formatter = DateFormatter(self.defaultfmt, tz)
self.scaled = {DAYS_PER_YEAR: rcParams['date.autoformatter.year'],
DAYS_PER_MONTH: rcParams['date.autoformatter.month'],
1.0: rcParams['date.autoformatter.day'],
1. / HOURS_PER_DAY: rcParams['date.autoformatter.hour'],
1. / (MINUTES_PER_DAY):
rcParams['date.autoformatter.minute'],
1. / (SEC_PER_DAY):
rcParams['date.autoformatter.second'],
1. / (MUSECONDS_PER_DAY):
rcParams['date.autoformatter.microsecond']}
def _set_locator(self, locator):
self._locator = locator
def __call__(self, x, pos=None):
try:
locator_unit_scale = float(self._locator._get_unit())
except AttributeError:
locator_unit_scale = 1
# Pick the first scale which is greater than the locator unit.
fmt = next((fmt for scale, fmt in sorted(self.scaled.items())
if scale >= locator_unit_scale),
self.defaultfmt)
if isinstance(fmt, str):
self._formatter = DateFormatter(fmt, self._tz)
result = self._formatter(x, pos)
elif callable(fmt):
result = fmt(x, pos)
else:
raise TypeError('Unexpected type passed to {0!r}.'.format(self))
return result
class rrulewrapper(object):
def __init__(self, freq, tzinfo=None, **kwargs):
kwargs['freq'] = freq
self._base_tzinfo = tzinfo
self._update_rrule(**kwargs)
def set(self, **kwargs):
self._construct.update(kwargs)
self._update_rrule(**self._construct)
def _update_rrule(self, **kwargs):
tzinfo = self._base_tzinfo
# rrule does not play nicely with time zones - especially pytz time
# zones, it's best to use naive zones and attach timezones once the
# datetimes are returned
if 'dtstart' in kwargs:
dtstart = kwargs['dtstart']
if dtstart.tzinfo is not None:
if tzinfo is None:
tzinfo = dtstart.tzinfo
else:
dtstart = dtstart.astimezone(tzinfo)
kwargs['dtstart'] = dtstart.replace(tzinfo=None)
if 'until' in kwargs:
until = kwargs['until']
if until.tzinfo is not None:
if tzinfo is not None:
until = until.astimezone(tzinfo)
else:
raise ValueError('until cannot be aware if dtstart '
'is naive and tzinfo is None')
kwargs['until'] = until.replace(tzinfo=None)
self._construct = kwargs.copy()
self._tzinfo = tzinfo
self._rrule = rrule(**self._construct)
def _attach_tzinfo(self, dt, tzinfo):
# pytz zones are attached by "localizing" the datetime
if hasattr(tzinfo, 'localize'):
return tzinfo.localize(dt, is_dst=True)
return dt.replace(tzinfo=tzinfo)
def _aware_return_wrapper(self, f, returns_list=False):
"""Decorator function that allows rrule methods to handle tzinfo."""
# This is only necessary if we're actually attaching a tzinfo
if self._tzinfo is None:
return f
# All datetime arguments must be naive. If they are not naive, they are
# converted to the _tzinfo zone before dropping the zone.
def normalize_arg(arg):
if isinstance(arg, datetime.datetime) and arg.tzinfo is not None:
if arg.tzinfo is not self._tzinfo:
arg = arg.astimezone(self._tzinfo)
return arg.replace(tzinfo=None)
return arg
def normalize_args(args, kwargs):
args = tuple(normalize_arg(arg) for arg in args)
kwargs = {kw: normalize_arg(arg) for kw, arg in kwargs.items()}
return args, kwargs
# There are two kinds of functions we care about - ones that return
# dates and ones that return lists of dates.
if not returns_list:
def inner_func(*args, **kwargs):
args, kwargs = normalize_args(args, kwargs)
dt = f(*args, **kwargs)
return self._attach_tzinfo(dt, self._tzinfo)
else:
def inner_func(*args, **kwargs):
args, kwargs = normalize_args(args, kwargs)
dts = f(*args, **kwargs)
return [self._attach_tzinfo(dt, self._tzinfo) for dt in dts]
return functools.wraps(f)(inner_func)
def __getattr__(self, name):
if name in self.__dict__:
return self.__dict__[name]
f = getattr(self._rrule, name)
if name in {'after', 'before'}:
return self._aware_return_wrapper(f)
elif name in {'xafter', 'xbefore', 'between'}:
return self._aware_return_wrapper(f, returns_list=True)
else:
return f
def __setstate__(self, state):
self.__dict__.update(state)
class DateLocator(ticker.Locator):
"""
Determines the tick locations when plotting dates.
This class is subclassed by other Locators and
is not meant to be used on its own.
"""
hms0d = {'byhour': 0, 'byminute': 0, 'bysecond': 0}
def __init__(self, tz=None):
"""
*tz* is a :class:`tzinfo` instance.
"""
if tz is None:
tz = _get_rc_timezone()
self.tz = tz
def set_tzinfo(self, tz):
"""
Set time zone info.
"""
self.tz = tz
def datalim_to_dt(self):
"""
Convert axis data interval to datetime objects.
"""
dmin, dmax = self.axis.get_data_interval()
if dmin > dmax:
dmin, dmax = dmax, dmin
if dmin < 1:
raise ValueError('datalim minimum {} is less than 1 and '
'is an invalid Matplotlib date value. This often '
'happens if you pass a non-datetime '
'value to an axis that has datetime units'
.format(dmin))
return num2date(dmin, self.tz), num2date(dmax, self.tz)
def viewlim_to_dt(self):
"""
Converts the view interval to datetime objects.
"""
vmin, vmax = self.axis.get_view_interval()
if vmin > vmax:
vmin, vmax = vmax, vmin
if vmin < 1:
raise ValueError('view limit minimum {} is less than 1 and '
'is an invalid Matplotlib date value. This '
'often happens if you pass a non-datetime '
'value to an axis that has datetime units'
.format(vmin))
return num2date(vmin, self.tz), num2date(vmax, self.tz)
def _get_unit(self):
"""
Return how many days a unit of the locator is; used for
intelligent autoscaling.
"""
return 1
def _get_interval(self):
"""
Return the number of units for each tick.
"""
return 1
def nonsingular(self, vmin, vmax):
"""
Given the proposed upper and lower extent, adjust the range
if it is too close to being singular (i.e. a range of ~0).
"""
unit = self._get_unit()
interval = self._get_interval()
if abs(vmax - vmin) < 1e-6:
vmin -= 2 * unit * interval
vmax += 2 * unit * interval
return vmin, vmax
class RRuleLocator(DateLocator):
# use the dateutil rrule instance
def __init__(self, o, tz=None):
DateLocator.__init__(self, tz)
self.rule = o
def __call__(self):
# if no data have been set, this will tank with a ValueError
try:
dmin, dmax = self.viewlim_to_dt()
except ValueError:
return []
return self.tick_values(dmin, dmax)
def tick_values(self, vmin, vmax):
delta = relativedelta(vmax, vmin)
# We need to cap at the endpoints of valid datetime
try:
start = vmin - delta
except (ValueError, OverflowError):
start = _from_ordinalf(1.0)
try:
stop = vmax + delta
except (ValueError, OverflowError):
# The magic number!
stop = _from_ordinalf(3652059.9999999)
self.rule.set(dtstart=start, until=stop)
dates = self.rule.between(vmin, vmax, True)
if len(dates) == 0:
return date2num([vmin, vmax])
return self.raise_if_exceeds(date2num(dates))
def _get_unit(self):
"""
Return how many days a unit of the locator is; used for
intelligent autoscaling.
"""
freq = self.rule._rrule._freq
return self.get_unit_generic(freq)
@staticmethod
def get_unit_generic(freq):
if freq == YEARLY:
return DAYS_PER_YEAR
elif freq == MONTHLY:
return DAYS_PER_MONTH
elif freq == WEEKLY:
return DAYS_PER_WEEK
elif freq == DAILY:
return 1.0
elif freq == HOURLY:
return 1.0 / HOURS_PER_DAY
elif freq == MINUTELY:
return 1.0 / MINUTES_PER_DAY
elif freq == SECONDLY:
return 1.0 / SEC_PER_DAY
else:
# error
return -1 # or should this just return '1'?
def _get_interval(self):
return self.rule._rrule._interval
def autoscale(self):
"""
Set the view limits to include the data range.
"""
dmin, dmax = self.datalim_to_dt()
delta = relativedelta(dmax, dmin)
# We need to cap at the endpoints of valid datetime
try:
start = dmin - delta
except ValueError:
start = _from_ordinalf(1.0)
try:
stop = dmax + delta
except ValueError:
# The magic number!
stop = _from_ordinalf(3652059.9999999)
self.rule.set(dtstart=start, until=stop)
dmin, dmax = self.datalim_to_dt()
vmin = self.rule.before(dmin, True)
if not vmin:
vmin = dmin
vmax = self.rule.after(dmax, True)
if not vmax:
vmax = dmax
vmin = date2num(vmin)
vmax = date2num(vmax)
return self.nonsingular(vmin, vmax)
class AutoDateLocator(DateLocator):
"""
On autoscale, this class picks the best
:class:`DateLocator` to set the view limits and the tick
locations.
"""
def __init__(self, tz=None, minticks=5, maxticks=None,
interval_multiples=True):
"""
*minticks* is the minimum number of ticks desired, which is used to
select the type of ticking (yearly, monthly, etc.).
*maxticks* is the maximum number of ticks desired, which controls
any interval between ticks (ticking every other, every 3, etc.).
For really fine-grained control, this can be a dictionary mapping
individual rrule frequency constants (YEARLY, MONTHLY, etc.)
to their own maximum number of ticks. This can be used to keep
the number of ticks appropriate to the format chosen in
:class:`AutoDateFormatter`. Any frequency not specified in this
dictionary is given a default value.
*tz* is a :class:`tzinfo` instance.
*interval_multiples* is a boolean that indicates whether ticks
should be chosen to be multiple of the interval. This will lock
ticks to 'nicer' locations. For example, this will force the
ticks to be at hours 0,6,12,18 when hourly ticking is done at
6 hour intervals.
The AutoDateLocator has an interval dictionary that maps the
frequency of the tick (a constant from dateutil.rrule) and a
multiple allowed for that ticking. The default looks like this::
self.intervald = {
YEARLY : [1, 2, 4, 5, 10, 20, 40, 50, 100, 200, 400, 500,
1000, 2000, 4000, 5000, 10000],
MONTHLY : [1, 2, 3, 4, 6],
DAILY : [1, 2, 3, 7, 14],
HOURLY : [1, 2, 3, 4, 6, 12],
MINUTELY: [1, 5, 10, 15, 30],
SECONDLY: [1, 5, 10, 15, 30],
MICROSECONDLY: [1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000,
5000, 10000, 20000, 50000, 100000, 200000, 500000,
1000000],
}
The interval is used to specify multiples that are appropriate for
the frequency of ticking. For instance, every 7 days is sensible
for daily ticks, but for minutes/seconds, 15 or 30 make sense.
You can customize this dictionary by doing::
locator = AutoDateLocator()
locator.intervald[HOURLY] = [3] # only show every 3 hours
"""
DateLocator.__init__(self, tz)
self._locator = YearLocator(tz=tz)
self._freq = YEARLY
self._freqs = [YEARLY, MONTHLY, DAILY, HOURLY, MINUTELY,
SECONDLY, MICROSECONDLY]
self.minticks = minticks
self.maxticks = {YEARLY: 11, MONTHLY: 12, DAILY: 11, HOURLY: 12,
MINUTELY: 11, SECONDLY: 11, MICROSECONDLY: 8}
if maxticks is not None:
try:
self.maxticks.update(maxticks)
except TypeError:
# Assume we were given an integer. Use this as the maximum
# number of ticks for every frequency and create a
# dictionary for this
self.maxticks = dict.fromkeys(self._freqs, maxticks)
self.interval_multiples = interval_multiples
self.intervald = {
YEARLY: [1, 2, 4, 5, 10, 20, 40, 50, 100, 200, 400, 500,
1000, 2000, 4000, 5000, 10000],
MONTHLY: [1, 2, 3, 4, 6],
DAILY: [1, 2, 3, 7, 14, 21],
HOURLY: [1, 2, 3, 4, 6, 12],
MINUTELY: [1, 5, 10, 15, 30],
SECONDLY: [1, 5, 10, 15, 30],
MICROSECONDLY: [1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000,
5000, 10000, 20000, 50000, 100000, 200000, 500000,
1000000]}
if interval_multiples:
# Swap "3" for "4" in the DAILY list; If we use 3 we get bad
# tick loc for months w/ 31 days: 1, 4,..., 28, 31, 1
# If we use 4 then we get: 1, 5, ... 25, 29, 1
self.intervald[DAILY] = [1, 2, 4, 7, 14, 21]
self._byranges = [None, range(1, 13), range(1, 32),
range(0, 24), range(0, 60), range(0, 60), None]
def __call__(self):
'Return the locations of the ticks'
self.refresh()
return self._locator()
def tick_values(self, vmin, vmax):
return self.get_locator(vmin, vmax).tick_values(vmin, vmax)
def nonsingular(self, vmin, vmax):
# whatever is thrown at us, we can scale the unit.
# But default nonsingular date plots at an ~4 year period.
if vmin == vmax:
vmin = vmin - DAYS_PER_YEAR * 2
vmax = vmax + DAYS_PER_YEAR * 2
return vmin, vmax
def set_axis(self, axis):
DateLocator.set_axis(self, axis)
self._locator.set_axis(axis)
def refresh(self):
'Refresh internal information based on current limits.'
dmin, dmax = self.viewlim_to_dt()
self._locator = self.get_locator(dmin, dmax)
def _get_unit(self):
if self._freq in [MICROSECONDLY]:
return 1. / MUSECONDS_PER_DAY
else:
return RRuleLocator.get_unit_generic(self._freq)
def autoscale(self):
'Try to choose the view limits intelligently.'
dmin, dmax = self.datalim_to_dt()
self._locator = self.get_locator(dmin, dmax)
return self._locator.autoscale()
def get_locator(self, dmin, dmax):
'Pick the best locator based on a distance.'
delta = relativedelta(dmax, dmin)
tdelta = dmax - dmin
# take absolute difference
if dmin > dmax:
delta = -delta
tdelta = -tdelta
# The following uses a mix of calls to relativedelta and timedelta
# methods because there is incomplete overlap in the functionality of
# these similar functions, and it's best to avoid doing our own math
# whenever possible.
numYears = float(delta.years)
numMonths = numYears * MONTHS_PER_YEAR + delta.months
numDays = tdelta.days # Avoids estimates of days/month, days/year
numHours = numDays * HOURS_PER_DAY + delta.hours
numMinutes = numHours * MIN_PER_HOUR + delta.minutes
numSeconds = np.floor(tdelta.total_seconds())
numMicroseconds = np.floor(tdelta.total_seconds() * 1e6)
nums = [numYears, numMonths, numDays, numHours, numMinutes,
numSeconds, numMicroseconds]
use_rrule_locator = [True] * 6 + [False]
# Default setting of bymonth, etc. to pass to rrule
# [unused (for year), bymonth, bymonthday, byhour, byminute,
# bysecond, unused (for microseconds)]
byranges = [None, 1, 1, 0, 0, 0, None]
# Loop over all the frequencies and try to find one that gives at
# least a minticks tick positions. Once this is found, look for
# an interval from an list specific to that frequency that gives no
# more than maxticks tick positions. Also, set up some ranges
# (bymonth, etc.) as appropriate to be passed to rrulewrapper.
for i, (freq, num) in enumerate(zip(self._freqs, nums)):
# If this particular frequency doesn't give enough ticks, continue
if num < self.minticks:
# Since we're not using this particular frequency, set
# the corresponding by_ to None so the rrule can act as
# appropriate
byranges[i] = None
continue
# Find the first available interval that doesn't give too many
# ticks
for interval in self.intervald[freq]:
if num <= interval * (self.maxticks[freq] - 1):
break
else:
# We went through the whole loop without breaking, default to
# the last interval in the list and raise a warning
cbook._warn_external('AutoDateLocator was unable to pick an '
'appropriate interval for this date '
'range. It may be necessary to add an '
'interval value to the '
'AutoDateLocator\'s intervald '
'dictionary. Defaulting to {0}.'
.format(interval))
# Set some parameters as appropriate
self._freq = freq
if self._byranges[i] and self.interval_multiples:
byranges[i] = self._byranges[i][::interval]
if i in (DAILY, WEEKLY):
if interval == 14:
# just make first and 15th. Avoids 30th.
byranges[i] = [1, 15]
elif interval == 7:
byranges[i] = [1, 8, 15, 22]
interval = 1
else:
byranges[i] = self._byranges[i]
break
else:
raise ValueError('No sensible date limit could be found in the '
'AutoDateLocator.')
if (freq == YEARLY) and self.interval_multiples:
locator = YearLocator(interval, tz=self.tz)
elif use_rrule_locator[i]:
_, bymonth, bymonthday, byhour, byminute, bysecond, _ = byranges
rrule = rrulewrapper(self._freq, interval=interval,
dtstart=dmin, until=dmax,
bymonth=bymonth, bymonthday=bymonthday,
byhour=byhour, byminute=byminute,
bysecond=bysecond)
locator = RRuleLocator(rrule, self.tz)
else:
locator = MicrosecondLocator(interval, tz=self.tz)
if dmin.year > 20 and interval < 1000:
_log.warning('Plotting microsecond time intervals is not well '
'supported. Please see the MicrosecondLocator '
'documentation for details.')
locator.set_axis(self.axis)
if self.axis is not None:
locator.set_view_interval(*self.axis.get_view_interval())
locator.set_data_interval(*self.axis.get_data_interval())
return locator
class YearLocator(DateLocator):
"""
Make ticks on a given day of each year that is a multiple of base.
Examples::
# Tick every year on Jan 1st
locator = YearLocator()
# Tick every 5 years on July 4th
locator = YearLocator(5, month=7, day=4)
"""
def __init__(self, base=1, month=1, day=1, tz=None):
"""
Mark years that are multiple of base on a given month and day
(default jan 1).
"""
DateLocator.__init__(self, tz)
self.base = ticker._Edge_integer(base, 0)
self.replaced = {'month': month,
'day': day,
'hour': 0,
'minute': 0,
'second': 0,
}
if not hasattr(tz, 'localize'):
# if tz is pytz, we need to do this w/ the localize fcn,
# otherwise datetime.replace works fine...
self.replaced['tzinfo'] = tz
def __call__(self):
# if no data have been set, this will tank with a ValueError
try:
dmin, dmax = self.viewlim_to_dt()
except ValueError:
return []
return self.tick_values(dmin, dmax)
def tick_values(self, vmin, vmax):
ymin = self.base.le(vmin.year) * self.base.step
ymax = self.base.ge(vmax.year) * self.base.step
vmin = vmin.replace(year=ymin, **self.replaced)
if hasattr(self.tz, 'localize'):
# look after pytz
if not vmin.tzinfo:
vmin = self.tz.localize(vmin, is_dst=True)
ticks = [vmin]
while True:
dt = ticks[-1]
if dt.year >= ymax:
return date2num(ticks)
year = dt.year + self.base.step
dt = dt.replace(year=year, **self.replaced)
if hasattr(self.tz, 'localize'):
# look after pytz
if not dt.tzinfo:
dt = self.tz.localize(dt, is_dst=True)
ticks.append(dt)
def autoscale(self):
"""
Set the view limits to include the data range.
"""
dmin, dmax = self.datalim_to_dt()
ymin = self.base.le(dmin.year)
ymax = self.base.ge(dmax.year)
vmin = dmin.replace(year=ymin, **self.replaced)
vmin = vmin.astimezone(self.tz)
vmax = dmax.replace(year=ymax, **self.replaced)
vmax = vmax.astimezone(self.tz)
vmin = date2num(vmin)
vmax = date2num(vmax)
return self.nonsingular(vmin, vmax)
class MonthLocator(RRuleLocator):
"""
Make ticks on occurrences of each month, e.g., 1, 3, 12.
"""
def __init__(self, bymonth=None, bymonthday=1, interval=1, tz=None):
"""
Mark every month in *bymonth*; *bymonth* can be an int or
sequence. Default is ``range(1,13)``, i.e. every month.
*interval* is the interval between each iteration. For
example, if ``interval=2``, mark every second occurrence.
"""
if bymonth is None:
bymonth = range(1, 13)
elif isinstance(bymonth, np.ndarray):
# This fixes a bug in dateutil <= 2.3 which prevents the use of
# numpy arrays in (among other things) the bymonthday, byweekday
# and bymonth parameters.
bymonth = [x.item() for x in bymonth.astype(int)]
rule = rrulewrapper(MONTHLY, bymonth=bymonth, bymonthday=bymonthday,
interval=interval, **self.hms0d)
RRuleLocator.__init__(self, rule, tz)
class WeekdayLocator(RRuleLocator):
"""
Make ticks on occurrences of each weekday.
"""
def __init__(self, byweekday=1, interval=1, tz=None):
"""
Mark every weekday in *byweekday*; *byweekday* can be a number or
sequence.
Elements of *byweekday* must be one of MO, TU, WE, TH, FR, SA,
SU, the constants from :mod:`dateutil.rrule`, which have been
imported into the :mod:`matplotlib.dates` namespace.
*interval* specifies the number of weeks to skip. For example,
``interval=2`` plots every second week.
"""
if isinstance(byweekday, np.ndarray):
# This fixes a bug in dateutil <= 2.3 which prevents the use of
# numpy arrays in (among other things) the bymonthday, byweekday
# and bymonth parameters.
[x.item() for x in byweekday.astype(int)]
rule = rrulewrapper(DAILY, byweekday=byweekday,
interval=interval, **self.hms0d)
RRuleLocator.__init__(self, rule, tz)
class DayLocator(RRuleLocator):
"""
Make ticks on occurrences of each day of the month. For example,
1, 15, 30.
"""
def __init__(self, bymonthday=None, interval=1, tz=None):
"""
Mark every day in *bymonthday*; *bymonthday* can be an int or
sequence.
Default is to tick every day of the month: ``bymonthday=range(1,32)``
"""
if not interval == int(interval) or interval < 1:
raise ValueError("interval must be an integer greater than 0")
if bymonthday is None:
bymonthday = range(1, 32)
elif isinstance(bymonthday, np.ndarray):
# This fixes a bug in dateutil <= 2.3 which prevents the use of
# numpy arrays in (among other things) the bymonthday, byweekday
# and bymonth parameters.
bymonthday = [x.item() for x in bymonthday.astype(int)]
rule = rrulewrapper(DAILY, bymonthday=bymonthday,
interval=interval, **self.hms0d)
RRuleLocator.__init__(self, rule, tz)
class HourLocator(RRuleLocator):
"""
Make ticks on occurrences of each hour.
"""
def __init__(self, byhour=None, interval=1, tz=None):
"""
Mark every hour in *byhour*; *byhour* can be an int or sequence.
Default is to tick every hour: ``byhour=range(24)``
*interval* is the interval between each iteration. For
example, if ``interval=2``, mark every second occurrence.
"""
if byhour is None:
byhour = range(24)
rule = rrulewrapper(HOURLY, byhour=byhour, interval=interval,
byminute=0, bysecond=0)
RRuleLocator.__init__(self, rule, tz)
class MinuteLocator(RRuleLocator):
"""
Make ticks on occurrences of each minute.
"""
def __init__(self, byminute=None, interval=1, tz=None):
"""
Mark every minute in *byminute*; *byminute* can be an int or
sequence. Default is to tick every minute: ``byminute=range(60)``
*interval* is the interval between each iteration. For
example, if ``interval=2``, mark every second occurrence.
"""
if byminute is None:
byminute = range(60)
rule = rrulewrapper(MINUTELY, byminute=byminute, interval=interval,
bysecond=0)
RRuleLocator.__init__(self, rule, tz)
class SecondLocator(RRuleLocator):
"""
Make ticks on occurrences of each second.
"""
def __init__(self, bysecond=None, interval=1, tz=None):
"""
Mark every second in *bysecond*; *bysecond* can be an int or
sequence. Default is to tick every second: ``bysecond = range(60)``
*interval* is the interval between each iteration. For
example, if ``interval=2``, mark every second occurrence.
"""
if bysecond is None:
bysecond = range(60)
rule = rrulewrapper(SECONDLY, bysecond=bysecond, interval=interval)
RRuleLocator.__init__(self, rule, tz)
class MicrosecondLocator(DateLocator):
"""
Make ticks on regular intervals of one or more microsecond(s).
.. note::
Due to the floating point representation of time in days since
0001-01-01 UTC (plus 1), plotting data with microsecond time
resolution does not work well with current dates.
If you want microsecond resolution time plots, it is strongly
recommended to use floating point seconds, not datetime-like
time representation.
If you really must use datetime.datetime() or similar and still
need microsecond precision, your only chance is to use very
early years; using year 0001 is recommended.
"""
def __init__(self, interval=1, tz=None):
"""
*interval* is the interval between each iteration. For
example, if ``interval=2``, mark every second microsecond.
"""
self._interval = interval
self._wrapped_locator = ticker.MultipleLocator(interval)
self.tz = tz
def set_axis(self, axis):
self._wrapped_locator.set_axis(axis)
return DateLocator.set_axis(self, axis)
def set_view_interval(self, vmin, vmax):
self._wrapped_locator.set_view_interval(vmin, vmax)
return DateLocator.set_view_interval(self, vmin, vmax)
def set_data_interval(self, vmin, vmax):
self._wrapped_locator.set_data_interval(vmin, vmax)
return DateLocator.set_data_interval(self, vmin, vmax)
def __call__(self):
# if no data have been set, this will tank with a ValueError
try:
dmin, dmax = self.viewlim_to_dt()
except ValueError:
return []
return self.tick_values(dmin, dmax)
def tick_values(self, vmin, vmax):
nmin, nmax = date2num((vmin, vmax))
nmin *= MUSECONDS_PER_DAY
nmax *= MUSECONDS_PER_DAY
ticks = self._wrapped_locator.tick_values(nmin, nmax)
ticks = [tick / MUSECONDS_PER_DAY for tick in ticks]
return ticks
def _get_unit(self):
"""
Return how many days a unit of the locator is; used for
intelligent autoscaling.
"""
return 1. / MUSECONDS_PER_DAY
def _get_interval(self):
"""
Return the number of units for each tick.
"""
return self._interval
def epoch2num(e):
"""
Convert an epoch or sequence of epochs to the new date format,
that is days since 0001.
"""
return EPOCH_OFFSET + np.asarray(e) / SEC_PER_DAY
def num2epoch(d):
"""
Convert days since 0001 to epoch. *d* can be a number or sequence.
"""
return (np.asarray(d) - EPOCH_OFFSET) * SEC_PER_DAY
def mx2num(mxdates):
"""
Convert mx :class:`datetime` instance (or sequence of mx
instances) to the new date format.
"""
scalar = False
if not np.iterable(mxdates):
scalar = True
mxdates = [mxdates]
ret = epoch2num([m.ticks() for m in mxdates])
if scalar:
return ret[0]
else:
return ret
def date_ticker_factory(span, tz=None, numticks=5):
"""
Create a date locator with *numticks* (approx) and a date formatter
for *span* in days. Return value is (locator, formatter).
"""
if span == 0:
span = 1 / HOURS_PER_DAY
mins = span * MINUTES_PER_DAY
hrs = span * HOURS_PER_DAY
days = span
wks = span / DAYS_PER_WEEK
months = span / DAYS_PER_MONTH # Approx
years = span / DAYS_PER_YEAR # Approx
if years > numticks:
locator = YearLocator(int(years / numticks), tz=tz) # define
fmt = '%Y'
elif months > numticks:
locator = MonthLocator(tz=tz)
fmt = '%b %Y'
elif wks > numticks:
locator = WeekdayLocator(tz=tz)
fmt = '%a, %b %d'
elif days > numticks:
locator = DayLocator(interval=math.ceil(days / numticks), tz=tz)
fmt = '%b %d'
elif hrs > numticks:
locator = HourLocator(interval=math.ceil(hrs / numticks), tz=tz)
fmt = '%H:%M\n%b %d'
elif mins > numticks:
locator = MinuteLocator(interval=math.ceil(mins / numticks), tz=tz)
fmt = '%H:%M:%S'
else:
locator = MinuteLocator(tz=tz)
fmt = '%H:%M:%S'
formatter = DateFormatter(fmt, tz=tz)
return locator, formatter
@cbook.deprecated("3.1")
def seconds(s):
"""
Return seconds as days.
"""
return s / SEC_PER_DAY
@cbook.deprecated("3.1")
def minutes(m):
"""
Return minutes as days.
"""
return m / MINUTES_PER_DAY
@cbook.deprecated("3.1")
def hours(h):
"""
Return hours as days.
"""
return h / HOURS_PER_DAY
@cbook.deprecated("3.1")
def weeks(w):
"""
Return weeks as days.
"""
return w * DAYS_PER_WEEK
class DateConverter(units.ConversionInterface):
"""
Converter for datetime.date and datetime.datetime data,
or for date/time data represented as it would be converted
by :func:`date2num`.
The 'unit' tag for such data is None or a tzinfo instance.
"""
@staticmethod
def axisinfo(unit, axis):
"""
Return the :class:`~matplotlib.units.AxisInfo` for *unit*.
*unit* is a tzinfo instance or None.
The *axis* argument is required but not used.
"""
tz = unit
majloc = AutoDateLocator(tz=tz)
majfmt = AutoDateFormatter(majloc, tz=tz)
datemin = datetime.date(2000, 1, 1)
datemax = datetime.date(2010, 1, 1)
return units.AxisInfo(majloc=majloc, majfmt=majfmt, label='',
default_limits=(datemin, datemax))
@staticmethod
def convert(value, unit, axis):
"""
If *value* is not already a number or sequence of numbers,
convert it with :func:`date2num`.
The *unit* and *axis* arguments are not used.
"""
return date2num(value)
@staticmethod
def default_units(x, axis):
"""
Return the tzinfo instance of *x* or of its first element, or None
"""
if isinstance(x, np.ndarray):
x = x.ravel()
try:
x = cbook.safe_first_element(x)
except (TypeError, StopIteration):
pass
try:
return x.tzinfo
except AttributeError:
pass
return None
class ConciseDateConverter(DateConverter):
"""
Converter for datetime.date and datetime.datetime data,
or for date/time data represented as it would be converted
by :func:`date2num`.
The 'unit' tag for such data is None or a tzinfo instance.
"""
def __init__(self, formats=None, zero_formats=None, offset_formats=None,
show_offset=True):
self._formats = formats
self._zero_formats = zero_formats
self._offset_formats = offset_formats
self._show_offset = show_offset
super().__init__()
def axisinfo(self, unit, axis):
"""
Return the :class:`~matplotlib.units.AxisInfo` for *unit*.
*unit* is a tzinfo instance or None.
The *axis* argument is required but not used.
"""
tz = unit
majloc = AutoDateLocator(tz=tz)
majfmt = ConciseDateFormatter(majloc, tz=tz, formats=self._formats,
zero_formats=self._zero_formats,
offset_formats=self._offset_formats,
show_offset=self._show_offset)
datemin = datetime.date(2000, 1, 1)
datemax = datetime.date(2010, 1, 1)
return units.AxisInfo(majloc=majloc, majfmt=majfmt, label='',
default_limits=(datemin, datemax))
units.registry[np.datetime64] = DateConverter()
units.registry[datetime.date] = DateConverter()
units.registry[datetime.datetime] = DateConverter()
|
935fd029396c277842ba1886ac4d3c4954c79fe91e54607181237d00fdb79280
|
"""
Module for creating Sankey diagrams using Matplotlib.
"""
import logging
from types import SimpleNamespace
import numpy as np
from matplotlib.path import Path
from matplotlib.patches import PathPatch
from matplotlib.transforms import Affine2D
from matplotlib import docstring
from matplotlib import rcParams
_log = logging.getLogger(__name__)
__author__ = "Kevin L. Davies"
__credits__ = ["Yannick Copin"]
__license__ = "BSD"
__version__ = "2011/09/16"
# Angles [deg/90]
RIGHT = 0
UP = 1
# LEFT = 2
DOWN = 3
class Sankey(object):
"""
Sankey diagram.
Sankey diagrams are a specific type of flow diagram, in which
the width of the arrows is shown proportionally to the flow
quantity. They are typically used to visualize energy or
material or cost transfers between processes.
`Wikipedia (6/1/2011) <https://en.wikipedia.org/wiki/Sankey_diagram>`_
"""
def __init__(self, ax=None, scale=1.0, unit='', format='%G', gap=0.25,
radius=0.1, shoulder=0.03, offset=0.15, head_angle=100,
margin=0.4, tolerance=1e-6, **kwargs):
"""
Create a new Sankey instance.
Optional keyword arguments:
=============== ===================================================
Field Description
=============== ===================================================
*ax* axes onto which the data should be plotted
If *ax* isn't provided, new axes will be created.
*scale* scaling factor for the flows
*scale* sizes the width of the paths in order to
maintain proper layout. The same scale is applied
to all subdiagrams. The value should be chosen
such that the product of the scale and the sum of
the inputs is approximately 1.0 (and the product of
the scale and the sum of the outputs is
approximately -1.0).
*unit* string representing the physical unit associated
with the flow quantities
If *unit* is None, then none of the quantities are
labeled.
*format* a Python number formatting string to be used in
labeling the flow as a quantity (i.e., a number
times a unit, where the unit is given)
*gap* space between paths that break in/break away
to/from the top or bottom
*radius* inner radius of the vertical paths
*shoulder* size of the shoulders of output arrowS
*offset* text offset (from the dip or tip of the arrow)
*head_angle* angle of the arrow heads (and negative of the angle
of the tails) [deg]
*margin* minimum space between Sankey outlines and the edge
of the plot area
*tolerance* acceptable maximum of the magnitude of the sum of
flows
The magnitude of the sum of connected flows cannot
be greater than *tolerance*.
=============== ===================================================
The optional arguments listed above are applied to all subdiagrams so
that there is consistent alignment and formatting.
If :class:`Sankey` is instantiated with any keyword arguments other
than those explicitly listed above (``**kwargs``), they will be passed
to :meth:`add`, which will create the first subdiagram.
In order to draw a complex Sankey diagram, create an instance of
:class:`Sankey` by calling it without any kwargs::
sankey = Sankey()
Then add simple Sankey sub-diagrams::
sankey.add() # 1
sankey.add() # 2
#...
sankey.add() # n
Finally, create the full diagram::
sankey.finish()
Or, instead, simply daisy-chain those calls::
Sankey().add().add... .add().finish()
See Also
--------
Sankey.add
Sankey.finish
Examples
--------
.. plot:: gallery/specialty_plots/sankey_basics.py
"""
# Check the arguments.
if gap < 0:
raise ValueError(
"'gap' is negative, which is not allowed because it would "
"cause the paths to overlap")
if radius > gap:
raise ValueError(
"'radius' is greater than 'gap', which is not allowed because "
"it would cause the paths to overlap")
if head_angle < 0:
raise ValueError(
"'head_angle' is negative, which is not allowed because it "
"would cause inputs to look like outputs and vice versa")
if tolerance < 0:
raise ValueError(
"'tolerance' is negative, but it must be a magnitude")
# Create axes if necessary.
if ax is None:
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[])
self.diagrams = []
# Store the inputs.
self.ax = ax
self.unit = unit
self.format = format
self.scale = scale
self.gap = gap
self.radius = radius
self.shoulder = shoulder
self.offset = offset
self.margin = margin
self.pitch = np.tan(np.pi * (1 - head_angle / 180.0) / 2.0)
self.tolerance = tolerance
# Initialize the vertices of tight box around the diagram(s).
self.extent = np.array((np.inf, -np.inf, np.inf, -np.inf))
# If there are any kwargs, create the first subdiagram.
if len(kwargs):
self.add(**kwargs)
def _arc(self, quadrant=0, cw=True, radius=1, center=(0, 0)):
"""
Return the codes and vertices for a rotated, scaled, and translated
90 degree arc.
Optional keyword arguments:
=============== ==========================================
Keyword Description
=============== ==========================================
*quadrant* uses 0-based indexing (0, 1, 2, or 3)
*cw* if True, clockwise
*center* (x, y) tuple of the arc's center
=============== ==========================================
"""
# Note: It would be possible to use matplotlib's transforms to rotate,
# scale, and translate the arc, but since the angles are discrete,
# it's just as easy and maybe more efficient to do it here.
ARC_CODES = [Path.LINETO,
Path.CURVE4,
Path.CURVE4,
Path.CURVE4,
Path.CURVE4,
Path.CURVE4,
Path.CURVE4]
# Vertices of a cubic Bezier curve approximating a 90 deg arc
# These can be determined by Path.arc(0,90).
ARC_VERTICES = np.array([[1.00000000e+00, 0.00000000e+00],
[1.00000000e+00, 2.65114773e-01],
[8.94571235e-01, 5.19642327e-01],
[7.07106781e-01, 7.07106781e-01],
[5.19642327e-01, 8.94571235e-01],
[2.65114773e-01, 1.00000000e+00],
# Insignificant
# [6.12303177e-17, 1.00000000e+00]])
[0.00000000e+00, 1.00000000e+00]])
if quadrant == 0 or quadrant == 2:
if cw:
vertices = ARC_VERTICES
else:
vertices = ARC_VERTICES[:, ::-1] # Swap x and y.
elif quadrant == 1 or quadrant == 3:
# Negate x.
if cw:
# Swap x and y.
vertices = np.column_stack((-ARC_VERTICES[:, 1],
ARC_VERTICES[:, 0]))
else:
vertices = np.column_stack((-ARC_VERTICES[:, 0],
ARC_VERTICES[:, 1]))
if quadrant > 1:
radius = -radius # Rotate 180 deg.
return list(zip(ARC_CODES, radius * vertices +
np.tile(center, (ARC_VERTICES.shape[0], 1))))
def _add_input(self, path, angle, flow, length):
"""
Add an input to a path and return its tip and label locations.
"""
if angle is None:
return [0, 0], [0, 0]
else:
x, y = path[-1][1] # Use the last point as a reference.
dipdepth = (flow / 2) * self.pitch
if angle == RIGHT:
x -= length
dip = [x + dipdepth, y + flow / 2.0]
path.extend([(Path.LINETO, [x, y]),
(Path.LINETO, dip),
(Path.LINETO, [x, y + flow]),
(Path.LINETO, [x + self.gap, y + flow])])
label_location = [dip[0] - self.offset, dip[1]]
else: # Vertical
x -= self.gap
if angle == UP:
sign = 1
else:
sign = -1
dip = [x - flow / 2, y - sign * (length - dipdepth)]
if angle == DOWN:
quadrant = 2
else:
quadrant = 1
# Inner arc isn't needed if inner radius is zero
if self.radius:
path.extend(self._arc(quadrant=quadrant,
cw=angle == UP,
radius=self.radius,
center=(x + self.radius,
y - sign * self.radius)))
else:
path.append((Path.LINETO, [x, y]))
path.extend([(Path.LINETO, [x, y - sign * length]),
(Path.LINETO, dip),
(Path.LINETO, [x - flow, y - sign * length])])
path.extend(self._arc(quadrant=quadrant,
cw=angle == DOWN,
radius=flow + self.radius,
center=(x + self.radius,
y - sign * self.radius)))
path.append((Path.LINETO, [x - flow, y + sign * flow]))
label_location = [dip[0], dip[1] - sign * self.offset]
return dip, label_location
def _add_output(self, path, angle, flow, length):
"""
Append an output to a path and return its tip and label locations.
.. note:: *flow* is negative for an output.
"""
if angle is None:
return [0, 0], [0, 0]
else:
x, y = path[-1][1] # Use the last point as a reference.
tipheight = (self.shoulder - flow / 2) * self.pitch
if angle == RIGHT:
x += length
tip = [x + tipheight, y + flow / 2.0]
path.extend([(Path.LINETO, [x, y]),
(Path.LINETO, [x, y + self.shoulder]),
(Path.LINETO, tip),
(Path.LINETO, [x, y - self.shoulder + flow]),
(Path.LINETO, [x, y + flow]),
(Path.LINETO, [x - self.gap, y + flow])])
label_location = [tip[0] + self.offset, tip[1]]
else: # Vertical
x += self.gap
if angle == UP:
sign = 1
else:
sign = -1
tip = [x - flow / 2.0, y + sign * (length + tipheight)]
if angle == UP:
quadrant = 3
else:
quadrant = 0
# Inner arc isn't needed if inner radius is zero
if self.radius:
path.extend(self._arc(quadrant=quadrant,
cw=angle == UP,
radius=self.radius,
center=(x - self.radius,
y + sign * self.radius)))
else:
path.append((Path.LINETO, [x, y]))
path.extend([(Path.LINETO, [x, y + sign * length]),
(Path.LINETO, [x - self.shoulder,
y + sign * length]),
(Path.LINETO, tip),
(Path.LINETO, [x + self.shoulder - flow,
y + sign * length]),
(Path.LINETO, [x - flow, y + sign * length])])
path.extend(self._arc(quadrant=quadrant,
cw=angle == DOWN,
radius=self.radius - flow,
center=(x - self.radius,
y + sign * self.radius)))
path.append((Path.LINETO, [x - flow, y + sign * flow]))
label_location = [tip[0], tip[1] + sign * self.offset]
return tip, label_location
def _revert(self, path, first_action=Path.LINETO):
"""
A path is not simply reversible by path[::-1] since the code
specifies an action to take from the **previous** point.
"""
reverse_path = []
next_code = first_action
for code, position in path[::-1]:
reverse_path.append((next_code, position))
next_code = code
return reverse_path
# This might be more efficient, but it fails because 'tuple' object
# doesn't support item assignment:
# path[1] = path[1][-1:0:-1]
# path[1][0] = first_action
# path[2] = path[2][::-1]
# return path
@docstring.dedent_interpd
def add(self, patchlabel='', flows=None, orientations=None, labels='',
trunklength=1.0, pathlengths=0.25, prior=None, connect=(0, 0),
rotation=0, **kwargs):
"""
Add a simple Sankey diagram with flows at the same hierarchical level.
Parameters
----------
patchlabel : str
Label to be placed at the center of the diagram.
Note that *label* (not *patchlabel*) can be passed as keyword
argument to create an entry in the legend.
flows : list of float
Array of flow values. By convention, inputs are positive and
outputs are negative.
Flows are placed along the top of the diagram from the inside out
in order of their index within *flows*. They are placed along the
sides of the diagram from the top down and along the bottom from
the outside in.
If the sum of the inputs and outputs is
nonzero, the discrepancy will appear as a cubic Bezier curve along
the top and bottom edges of the trunk.
orientations : list of {-1, 0, 1}
List of orientations of the flows (or a single orientation to be
used for all flows). Valid values are 0 (inputs from
the left, outputs to the right), 1 (from and to the top) or -1
(from and to the bottom).
labels : list of (str or None)
List of labels for the flows (or a single label to be used for all
flows). Each label may be *None* (no label), or a labeling string.
If an entry is a (possibly empty) string, then the quantity for the
corresponding flow will be shown below the string. However, if
the *unit* of the main diagram is None, then quantities are never
shown, regardless of the value of this argument.
trunklength : float
Length between the bases of the input and output groups (in
data-space units).
pathlengths : list of float
List of lengths of the vertical arrows before break-in or after
break-away. If a single value is given, then it will be applied to
the first (inside) paths on the top and bottom, and the length of
all other arrows will be justified accordingly. The *pathlengths*
are not applied to the horizontal inputs and outputs.
prior : int
Index of the prior diagram to which this diagram should be
connected.
connect : (int, int)
A (prior, this) tuple indexing the flow of the prior diagram and
the flow of this diagram which should be connected. If this is the
first diagram or *prior* is *None*, *connect* will be ignored.
rotation : float
Angle of rotation of the diagram in degrees. The interpretation of
the *orientations* argument will be rotated accordingly (e.g., if
*rotation* == 90, an *orientations* entry of 1 means to/from the
left). *rotation* is ignored if this diagram is connected to an
existing one (using *prior* and *connect*).
Returns
-------
Sankey
The current `.Sankey` instance.
Other Parameters
----------------
**kwargs
Additional keyword arguments set `matplotlib.patches.PathPatch`
properties, listed below. For example, one may want to use
``fill=False`` or ``label="A legend entry"``.
%(Patch)s
See Also
--------
Sankey.finish
"""
# Check and preprocess the arguments.
if flows is None:
flows = np.array([1.0, -1.0])
else:
flows = np.array(flows)
n = flows.shape[0] # Number of flows
if rotation is None:
rotation = 0
else:
# In the code below, angles are expressed in deg/90.
rotation /= 90.0
if orientations is None:
orientations = 0
try:
orientations = np.broadcast_to(orientations, n)
except ValueError:
raise ValueError(
f"The shapes of 'flows' {np.shape(flows)} and 'orientations' "
f"{np.shape(orientations)} are incompatible"
) from None
try:
labels = np.broadcast_to(labels, n)
except ValueError:
raise ValueError(
f"The shapes of 'flows' {np.shape(flows)} and 'labels' "
f"{np.shape(labels)} are incompatible"
) from None
if trunklength < 0:
raise ValueError(
"'trunklength' is negative, which is not allowed because it "
"would cause poor layout")
if np.abs(np.sum(flows)) > self.tolerance:
_log.info("The sum of the flows is nonzero (%f; patchlabel=%r); "
"is the system not at steady state?",
np.sum(flows), patchlabel)
scaled_flows = self.scale * flows
gain = sum(max(flow, 0) for flow in scaled_flows)
loss = sum(min(flow, 0) for flow in scaled_flows)
if prior is not None:
if prior < 0:
raise ValueError("The index of the prior diagram is negative")
if min(connect) < 0:
raise ValueError(
"At least one of the connection indices is negative")
if prior >= len(self.diagrams):
raise ValueError(
f"The index of the prior diagram is {prior}, but there "
f"are only {len(self.diagrams)} other diagrams")
if connect[0] >= len(self.diagrams[prior].flows):
raise ValueError(
"The connection index to the source diagram is {}, but "
"that diagram has only {} flows".format(
connect[0], len(self.diagrams[prior].flows)))
if connect[1] >= n:
raise ValueError(
f"The connection index to this diagram is {connect[1]}, "
f"but this diagram has only {n} flows")
if self.diagrams[prior].angles[connect[0]] is None:
raise ValueError(
f"The connection cannot be made, which may occur if the "
f"magnitude of flow {connect[0]} of diagram {prior} is "
f"less than the specified tolerance")
flow_error = (self.diagrams[prior].flows[connect[0]] +
flows[connect[1]])
if abs(flow_error) >= self.tolerance:
raise ValueError(
f"The scaled sum of the connected flows is {flow_error}, "
f"which is not within the tolerance ({self.tolerance})")
# Determine if the flows are inputs.
are_inputs = [None] * n
for i, flow in enumerate(flows):
if flow >= self.tolerance:
are_inputs[i] = True
elif flow <= -self.tolerance:
are_inputs[i] = False
else:
_log.info(
"The magnitude of flow %d (%f) is below the tolerance "
"(%f).\nIt will not be shown, and it cannot be used in a "
"connection.", i, flow, self.tolerance)
# Determine the angles of the arrows (before rotation).
angles = [None] * n
for i, (orient, is_input) in enumerate(zip(orientations, are_inputs)):
if orient == 1:
if is_input:
angles[i] = DOWN
elif not is_input:
# Be specific since is_input can be None.
angles[i] = UP
elif orient == 0:
if is_input is not None:
angles[i] = RIGHT
else:
if orient != -1:
raise ValueError(
f"The value of orientations[{i}] is {orient}, "
f"but it must be -1, 0, or 1")
if is_input:
angles[i] = UP
elif not is_input:
angles[i] = DOWN
# Justify the lengths of the paths.
if np.iterable(pathlengths):
if len(pathlengths) != n:
raise ValueError(
f"The lengths of 'flows' ({n}) and 'pathlengths' "
f"({len(pathlengths)}) are incompatible")
else: # Make pathlengths into a list.
urlength = pathlengths
ullength = pathlengths
lrlength = pathlengths
lllength = pathlengths
d = dict(RIGHT=pathlengths)
pathlengths = [d.get(angle, 0) for angle in angles]
# Determine the lengths of the top-side arrows
# from the middle outwards.
for i, (angle, is_input, flow) in enumerate(zip(angles, are_inputs,
scaled_flows)):
if angle == DOWN and is_input:
pathlengths[i] = ullength
ullength += flow
elif angle == UP and not is_input:
pathlengths[i] = urlength
urlength -= flow # Flow is negative for outputs.
# Determine the lengths of the bottom-side arrows
# from the middle outwards.
for i, (angle, is_input, flow) in enumerate(reversed(list(zip(
angles, are_inputs, scaled_flows)))):
if angle == UP and is_input:
pathlengths[n - i - 1] = lllength
lllength += flow
elif angle == DOWN and not is_input:
pathlengths[n - i - 1] = lrlength
lrlength -= flow
# Determine the lengths of the left-side arrows
# from the bottom upwards.
has_left_input = False
for i, (angle, is_input, spec) in enumerate(reversed(list(zip(
angles, are_inputs, zip(scaled_flows, pathlengths))))):
if angle == RIGHT:
if is_input:
if has_left_input:
pathlengths[n - i - 1] = 0
else:
has_left_input = True
# Determine the lengths of the right-side arrows
# from the top downwards.
has_right_output = False
for i, (angle, is_input, spec) in enumerate(zip(
angles, are_inputs, list(zip(scaled_flows, pathlengths)))):
if angle == RIGHT:
if not is_input:
if has_right_output:
pathlengths[i] = 0
else:
has_right_output = True
# Begin the subpaths, and smooth the transition if the sum of the flows
# is nonzero.
urpath = [(Path.MOVETO, [(self.gap - trunklength / 2.0), # Upper right
gain / 2.0]),
(Path.LINETO, [(self.gap - trunklength / 2.0) / 2.0,
gain / 2.0]),
(Path.CURVE4, [(self.gap - trunklength / 2.0) / 8.0,
gain / 2.0]),
(Path.CURVE4, [(trunklength / 2.0 - self.gap) / 8.0,
-loss / 2.0]),
(Path.LINETO, [(trunklength / 2.0 - self.gap) / 2.0,
-loss / 2.0]),
(Path.LINETO, [(trunklength / 2.0 - self.gap),
-loss / 2.0])]
llpath = [(Path.LINETO, [(trunklength / 2.0 - self.gap), # Lower left
loss / 2.0]),
(Path.LINETO, [(trunklength / 2.0 - self.gap) / 2.0,
loss / 2.0]),
(Path.CURVE4, [(trunklength / 2.0 - self.gap) / 8.0,
loss / 2.0]),
(Path.CURVE4, [(self.gap - trunklength / 2.0) / 8.0,
-gain / 2.0]),
(Path.LINETO, [(self.gap - trunklength / 2.0) / 2.0,
-gain / 2.0]),
(Path.LINETO, [(self.gap - trunklength / 2.0),
-gain / 2.0])]
lrpath = [(Path.LINETO, [(trunklength / 2.0 - self.gap), # Lower right
loss / 2.0])]
ulpath = [(Path.LINETO, [self.gap - trunklength / 2.0, # Upper left
gain / 2.0])]
# Add the subpaths and assign the locations of the tips and labels.
tips = np.zeros((n, 2))
label_locations = np.zeros((n, 2))
# Add the top-side inputs and outputs from the middle outwards.
for i, (angle, is_input, spec) in enumerate(zip(
angles, are_inputs, list(zip(scaled_flows, pathlengths)))):
if angle == DOWN and is_input:
tips[i, :], label_locations[i, :] = self._add_input(
ulpath, angle, *spec)
elif angle == UP and not is_input:
tips[i, :], label_locations[i, :] = self._add_output(
urpath, angle, *spec)
# Add the bottom-side inputs and outputs from the middle outwards.
for i, (angle, is_input, spec) in enumerate(reversed(list(zip(
angles, are_inputs, list(zip(scaled_flows, pathlengths)))))):
if angle == UP and is_input:
tip, label_location = self._add_input(llpath, angle, *spec)
tips[n - i - 1, :] = tip
label_locations[n - i - 1, :] = label_location
elif angle == DOWN and not is_input:
tip, label_location = self._add_output(lrpath, angle, *spec)
tips[n - i - 1, :] = tip
label_locations[n - i - 1, :] = label_location
# Add the left-side inputs from the bottom upwards.
has_left_input = False
for i, (angle, is_input, spec) in enumerate(reversed(list(zip(
angles, are_inputs, list(zip(scaled_flows, pathlengths)))))):
if angle == RIGHT and is_input:
if not has_left_input:
# Make sure the lower path extends
# at least as far as the upper one.
if llpath[-1][1][0] > ulpath[-1][1][0]:
llpath.append((Path.LINETO, [ulpath[-1][1][0],
llpath[-1][1][1]]))
has_left_input = True
tip, label_location = self._add_input(llpath, angle, *spec)
tips[n - i - 1, :] = tip
label_locations[n - i - 1, :] = label_location
# Add the right-side outputs from the top downwards.
has_right_output = False
for i, (angle, is_input, spec) in enumerate(zip(
angles, are_inputs, list(zip(scaled_flows, pathlengths)))):
if angle == RIGHT and not is_input:
if not has_right_output:
# Make sure the upper path extends
# at least as far as the lower one.
if urpath[-1][1][0] < lrpath[-1][1][0]:
urpath.append((Path.LINETO, [lrpath[-1][1][0],
urpath[-1][1][1]]))
has_right_output = True
tips[i, :], label_locations[i, :] = self._add_output(
urpath, angle, *spec)
# Trim any hanging vertices.
if not has_left_input:
ulpath.pop()
llpath.pop()
if not has_right_output:
lrpath.pop()
urpath.pop()
# Concatenate the subpaths in the correct order (clockwise from top).
path = (urpath + self._revert(lrpath) + llpath + self._revert(ulpath) +
[(Path.CLOSEPOLY, urpath[0][1])])
# Create a patch with the Sankey outline.
codes, vertices = zip(*path)
vertices = np.array(vertices)
def _get_angle(a, r):
if a is None:
return None
else:
return a + r
if prior is None:
if rotation != 0: # By default, none of this is needed.
angles = [_get_angle(angle, rotation) for angle in angles]
rotate = Affine2D().rotate_deg(rotation * 90).transform_affine
tips = rotate(tips)
label_locations = rotate(label_locations)
vertices = rotate(vertices)
text = self.ax.text(0, 0, s=patchlabel, ha='center', va='center')
else:
rotation = (self.diagrams[prior].angles[connect[0]] -
angles[connect[1]])
angles = [_get_angle(angle, rotation) for angle in angles]
rotate = Affine2D().rotate_deg(rotation * 90).transform_affine
tips = rotate(tips)
offset = self.diagrams[prior].tips[connect[0]] - tips[connect[1]]
translate = Affine2D().translate(*offset).transform_affine
tips = translate(tips)
label_locations = translate(rotate(label_locations))
vertices = translate(rotate(vertices))
kwds = dict(s=patchlabel, ha='center', va='center')
text = self.ax.text(*offset, **kwds)
if rcParams['_internal.classic_mode']:
fc = kwargs.pop('fc', kwargs.pop('facecolor', '#bfd1d4'))
lw = kwargs.pop('lw', kwargs.pop('linewidth', 0.5))
else:
fc = kwargs.pop('fc', kwargs.pop('facecolor', None))
lw = kwargs.pop('lw', kwargs.pop('linewidth', None))
if fc is None:
fc = next(self.ax._get_patches_for_fill.prop_cycler)['color']
patch = PathPatch(Path(vertices, codes), fc=fc, lw=lw, **kwargs)
self.ax.add_patch(patch)
# Add the path labels.
texts = []
for number, angle, label, location in zip(flows, angles, labels,
label_locations):
if label is None or angle is None:
label = ''
elif self.unit is not None:
quantity = self.format % abs(number) + self.unit
if label != '':
label += "\n"
label += quantity
texts.append(self.ax.text(x=location[0], y=location[1],
s=label,
ha='center', va='center'))
# Text objects are placed even they are empty (as long as the magnitude
# of the corresponding flow is larger than the tolerance) in case the
# user wants to provide labels later.
# Expand the size of the diagram if necessary.
self.extent = (min(np.min(vertices[:, 0]),
np.min(label_locations[:, 0]),
self.extent[0]),
max(np.max(vertices[:, 0]),
np.max(label_locations[:, 0]),
self.extent[1]),
min(np.min(vertices[:, 1]),
np.min(label_locations[:, 1]),
self.extent[2]),
max(np.max(vertices[:, 1]),
np.max(label_locations[:, 1]),
self.extent[3]))
# Include both vertices _and_ label locations in the extents; there are
# where either could determine the margins (e.g., arrow shoulders).
# Add this diagram as a subdiagram.
self.diagrams.append(
SimpleNamespace(patch=patch, flows=flows, angles=angles, tips=tips,
text=text, texts=texts))
# Allow a daisy-chained call structure (see docstring for the class).
return self
def finish(self):
"""
Adjust the axes and return a list of information about the Sankey
subdiagram(s).
Return value is a list of subdiagrams represented with the following
fields:
=============== ===================================================
Field Description
=============== ===================================================
*patch* Sankey outline (an instance of
:class:`~matplotlib.patches.PathPatch`)
*flows* values of the flows (positive for input, negative
for output)
*angles* list of angles of the arrows [deg/90]
For example, if the diagram has not been rotated,
an input to the top side will have an angle of 3
(DOWN), and an output from the top side will have
an angle of 1 (UP). If a flow has been skipped
(because its magnitude is less than *tolerance*),
then its angle will be *None*.
*tips* array in which each row is an [x, y] pair
indicating the positions of the tips (or "dips") of
the flow paths
If the magnitude of a flow is less the *tolerance*
for the instance of :class:`Sankey`, the flow is
skipped and its tip will be at the center of the
diagram.
*text* :class:`~matplotlib.text.Text` instance for the
label of the diagram
*texts* list of :class:`~matplotlib.text.Text` instances
for the labels of flows
=============== ===================================================
See Also
--------
Sankey.add
"""
self.ax.axis([self.extent[0] - self.margin,
self.extent[1] + self.margin,
self.extent[2] - self.margin,
self.extent[3] + self.margin])
self.ax.set_aspect('equal', adjustable='datalim')
return self.diagrams
|
3e62926da3d9c965627a63ce785581bc1d624f80fc87d11a25d067a47a5a0ea8
|
import contextlib
import functools
import inspect
import math
from numbers import Number
import textwrap
import numpy as np
import matplotlib as mpl
from . import artist, cbook, colors, docstring, lines as mlines, transforms
from .bezier import (
NonIntersectingPathException, concatenate_paths, get_cos_sin,
get_intersection, get_parallels, inside_circle, make_path_regular,
make_wedged_bezier2, split_bezier_intersecting_with_closedpath,
split_path_inout)
from .path import Path
@cbook._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
validCap = ('butt', 'round', 'projecting')
validJoin = ('miter', 'round', 'bevel')
# 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,
**kwargs):
"""
The following kwarg properties are supported
%(Patch)s
"""
artist.Artist.__init__(self)
if linewidth is None:
linewidth = mpl.rcParams['patch.linewidth']
if linestyle is None:
linestyle = "solid"
if capstyle is None:
capstyle = 'butt'
if joinstyle is None:
joinstyle = 'miter'
if antialiased is None:
antialiased = mpl.rcParams['patch.antialiased']
self._hatch_color = colors.to_rgba(mpl.rcParams['hatch.color'])
self._fill = True # needed for set_facecolor call
if color is not None:
if edgecolor is not None or facecolor is not None:
cbook._warn_external(
"Setting the 'color' property will override"
"the edgecolor or facecolor properties.")
self.set_color(color)
else:
self.set_edgecolor(edgecolor)
self.set_facecolor(facecolor)
# unscaled dashes. Needed to scale dash patterns by lw
self._us_dashes = None
self._linewidth = 0
self.set_fill(fill)
self.set_linestyle(linestyle)
self.set_linewidth(linewidth)
self.set_antialiased(antialiased)
self.set_hatch(hatch)
self.set_capstyle(capstyle)
self.set_joinstyle(joinstyle)
if len(kwargs):
self.update(kwargs)
def get_verts(self):
"""
Return a copy of the vertices used in this patch
If the patch contains Bezier curves, the curves will be
interpolated by line segments. To access the curves as
curves, use :meth:`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.
Returns T/F, {}
"""
if self._contains is not None:
return self._contains(self, mouseevent)
radius = self._process_radius(radius)
codes = self.get_path().codes
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:]
return any(
subpath.contains_point(
(mouseevent.x, mouseevent.y), self.get_transform(), radius)
for subpath in map(
Path, np.split(vertices, idxs), np.split(codes, idxs))), {}
def contains_point(self, point, radius=None):
"""
Returns ``True`` if the given *point* is inside the path
(transformed with its transform attribute).
*radius* allows the path to be made slightly larger or smaller.
"""
radius = self._process_radius(radius)
return self.get_path().contains_point(point,
self.get_transform(),
radius)
def contains_points(self, points, radius=None):
"""
Returns a bool array which is ``True`` if the (closed) path
contains the corresponding point.
(transformed with its transform attribute).
*points* must be Nx2 array.
*radius* allows the path to be made slightly larger or smaller.
"""
radius = self._process_radius(radius)
return self.get_path().contains_points(points,
self.get_transform(),
radius)
def update_from(self, other):
"""
Updates this :class:`Patch` from the properties of *other*.
"""
artist.Artist.update_from(self, 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
# copy the unscaled dash pattern
self._us_dashes = other._us_dashes
self.set_linewidth(other._linewidth) # also sets dash properties
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 :class:`~matplotlib.transforms.Transform` instance which
maps data coordinates to physical coordinates.
"""
return artist.Artist.get_transform(self)
def get_patch_transform(self):
"""
Return the :class:`~matplotlib.transforms.Transform` instance which
takes 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):
"""
Returns True if the :class:`Patch` is to be drawn with antialiasing.
"""
return self._antialiased
def get_edgecolor(self):
"""
Return the edge color of the :class:`Patch`.
"""
return self._edgecolor
def get_facecolor(self):
"""
Return the face color of the :class:`Patch`.
"""
return self._facecolor
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
----------
b : bool or None
"""
if aa is None:
aa = mpl.rcParams['patch.antialiased']
self._antialiased = aa
self.stale = True
def _set_edgecolor(self, color):
set_hatch_color = True
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'
set_hatch_color = False
self._edgecolor = colors.to_rgba(color, self._alpha)
if set_hatch_color:
self._hatch_color = self._edgecolor
self.stale = True
def set_edgecolor(self, color):
"""
Set the patch edge color.
Parameters
----------
color : color or None or 'auto'
"""
self._original_edgecolor = color
self._set_edgecolor(color)
def _set_facecolor(self, color):
if color is None:
color = mpl.rcParams['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 : 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 : color
See Also
--------
Patch.set_facecolor, Patch.set_edgecolor
For setting the edge or face color individually.
"""
self.set_facecolor(c)
self.set_edgecolor(c)
def set_alpha(self, alpha):
# docstring inherited
super().set_alpha(alpha)
self._set_facecolor(self._original_facecolor)
self._set_edgecolor(self._original_edgecolor)
# stale is already True
def set_linewidth(self, w):
"""
Set the patch linewidth in points.
Parameters
----------
w : float or None
"""
if w is None:
w = mpl.rcParams['patch.linewidth']
if w is None:
w = mpl.rcParams['axes.linewidth']
self._linewidth = float(w)
# scale the dash pattern by the linewidth
offset, ls = self._us_dashes
self._dashoffset, self._dashes = mlines._scale_dashes(
offset, ls, self._linewidth)
self.stale = True
def set_linestyle(self, ls):
"""
Set the patch linestyle.
=========================== =================
linestyle description
=========================== =================
``'-'`` or ``'solid'`` solid line
``'--'`` or ``'dashed'`` dashed line
``'-.'`` or ``'dashdot'`` dash-dotted line
``':'`` or ``'dotted'`` dotted line
=========================== =================
Alternatively a dash tuple of the following form can be provided::
(offset, onoffseq),
where ``onoffseq`` is an even length tuple of on and off ink in points.
Parameters
----------
ls : {'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
The line style.
"""
if ls is None:
ls = "solid"
self._linestyle = ls
# get the unscaled dash pattern
offset, ls = self._us_dashes = mlines._get_dash_pattern(ls)
# scale the dash pattern by the linewidth
self._dashoffset, self._dashes = mlines._scale_dashes(
offset, ls, 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.stale = True
def get_fill(self):
'return whether fill is set'
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)
def set_capstyle(self, s):
"""
Set the patch capstyle
Parameters
----------
s : {'butt', 'round', 'projecting'}
"""
s = s.lower()
if s not in self.validCap:
raise ValueError('set_capstyle passed "%s";\n' % (s,) +
'valid capstyles are %s' % (self.validCap,))
self._capstyle = s
self.stale = True
def get_capstyle(self):
"Return the current capstyle"
return self._capstyle
def set_joinstyle(self, s):
"""
Set the patch joinstyle
Parameters
----------
s : {'miter', 'round', 'bevel'}
"""
s = s.lower()
if s not in self.validJoin:
raise ValueError('set_joinstyle passed "%s";\n' % (s,) +
'valid joinstyles are %s' % (self.validJoin,))
self._joinstyle = s
self.stale = True
def get_joinstyle(self):
"Return the current joinstyle"
return self._joinstyle
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.
Hatching is supported in the PostScript, PDF, SVG and Agg
backends only.
Parameters
----------
hatch : {'/', '\\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
"""
self._hatch = hatch
self.stale = True
def get_hatch(self):
'Return the current hatching pattern'
return self._hatch
@contextlib.contextmanager
def _bind_draw_path_function(self, renderer):
"""
``draw()`` helper factored out for sharing with `FancyArrowPatch`.
Yields a callable ``dp`` such that calling ``dp(*args, **kwargs)`` is
equivalent to calling ``renderer1.draw_path(gc, *args, **kwargs)``
where ``renderer1`` and ``gc`` have been suitably set from ``renderer``
and the artist's properties.
"""
renderer.open_group('patch', self.get_gid())
gc = renderer.new_gc()
gc.set_foreground(self._edgecolor, isRGBA=True)
lw = self._linewidth
if self._edgecolor[3] == 0:
lw = 0
gc.set_linewidth(lw)
gc.set_dashes(self._dashoffset, self._dashes)
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)
try:
gc.set_hatch_color(self._hatch_color)
except AttributeError:
# if we end up with a GC that does not have this method
cbook.warn_deprecated(
"3.1", message="Your backend does not support setting the "
"hatch color; such backends will become unsupported in "
"Matplotlib 3.3.")
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)
# In `with _bind_draw_path_function(renderer) as draw_path: ...`
# (in the implementations of `draw()` below), calls to `draw_path(...)`
# will occur as if they took place here with `gc` inserted as
# additional first argument.
yield functools.partial(renderer.draw_path, gc)
gc.restore()
renderer.close_group('patch')
self.stale = False
@artist.allow_rasterization
def draw(self, renderer):
'Draw the :class:`Patch` to the given *renderer*.'
if not self.get_visible():
return
# Patch has traditionally ignored the dashoffset.
with cbook._setattr_cm(self, _dashoffset=0), \
self._bind_draw_path_function(renderer) as draw_path:
path = self.get_path()
transform = self.get_transform()
tpath = transform.transform_path_non_affine(path)
affine = transform.get_affine()
draw_path(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)
patchdoc = artist.kwdoc(Patch)
for k in ('Rectangle', 'Circle', 'RegularPolygon', 'Polygon', 'Wedge', 'Arrow',
'FancyArrow', 'YAArrow', 'CirclePolygon', 'Ellipse', 'Arc',
'FancyBboxPatch', 'Patch'):
docstring.interpd.update({k: patchdoc})
# define Patch.__init__ docstring after the class has been added to interpd
docstring.dedent_interpd(Patch.__init__)
class Shadow(Patch):
def __str__(self):
return "Shadow(%s)" % (str(self.patch))
@docstring.dedent_interpd
def __init__(self, patch, ox, oy, props=None, **kwargs):
"""
Create a shadow of the given *patch* offset by *ox*, *oy*.
*props*, if not *None*, is a patch property update dictionary.
If *None*, the shadow will have have the same color as the face,
but darkened.
kwargs are
%(Patch)s
"""
Patch.__init__(self)
self.patch = patch
self.props = props
self._ox, self._oy = ox, oy
self._shadow_transform = transforms.Affine2D()
self._update()
def _update(self):
self.update_from(self.patch)
# Place the shadow patch directly behind the inherited patch.
self.set_zorder(np.nextafter(self.patch.zorder, -np.inf))
if self.props is not None:
self.update(self.props)
else:
color = .3 * np.asarray(colors.to_rgb(self.patch.get_facecolor()))
self.set_facecolor(color)
self.set_edgecolor(color)
self.set_alpha(0.5)
def _update_transform(self, renderer):
ox = renderer.points_to_pixels(self._ox)
oy = renderer.points_to_pixels(self._oy)
self._shadow_transform.clear().translate(ox, oy)
def _get_ox(self):
return self._ox
def _set_ox(self, ox):
self._ox = ox
def _get_oy(self):
return self._oy
def _set_oy(self, oy):
self._oy = oy
def get_path(self):
return self.patch.get_path()
def get_patch_transform(self):
return self.patch.get_patch_transform() + self._shadow_transform
def draw(self, renderer):
self._update_transform(renderer)
Patch.draw(self, renderer)
class Rectangle(Patch):
"""
Draw a rectangle with lower left at *xy* = (*x*, *y*) with
specified *width*, *height* and rotation *angle*.
"""
def __str__(self):
pars = self._x0, self._y0, self._width, self._height, self.angle
fmt = "Rectangle(xy=(%g, %g), width=%g, height=%g, angle=%g)"
return fmt % pars
@docstring.dedent_interpd
def __init__(self, xy, width, height, angle=0.0, **kwargs):
"""
Parameters
----------
xy : (float, float)
The bottom and left rectangle coordinates
width : float
Rectangle width
height : float
Rectangle height
angle : float, optional
rotation in degrees anti-clockwise about *xy* (default is 0.0)
fill : bool, optional
Whether to fill the rectangle (default is ``True``)
Notes
-----
Valid kwargs are:
%(Patch)s
"""
Patch.__init__(self, **kwargs)
self._x0 = xy[0]
self._y0 = xy[1]
self._width = width
self._height = height
self._x1 = self._x0 + self._width
self._y1 = self._y0 + self._height
self.angle = float(angle)
# Note: This cannot be calculated until this is added to an Axes
self._rect_transform = transforms.IdentityTransform()
def get_path(self):
"""
Return the vertices of the rectangle.
"""
return Path.unit_rectangle()
def _update_patch_transform(self):
"""NOTE: This cannot be called until after this has been added
to an Axes, otherwise unit conversion will fail. This
makes it very important to call the accessor method and
not directly access the transformation member variable.
"""
x0, y0, x1, y1 = self._convert_units()
bbox = transforms.Bbox.from_extents(x0, y0, x1, y1)
rot_trans = transforms.Affine2D()
rot_trans.rotate_deg_around(x0, y0, self.angle)
self._rect_transform = transforms.BboxTransformTo(bbox)
self._rect_transform += rot_trans
def _update_x1(self):
self._x1 = self._x0 + self._width
def _update_y1(self):
self._y1 = self._y0 + self._height
def _convert_units(self):
"""
Convert bounds of the rectangle.
"""
x0 = self.convert_xunits(self._x0)
y0 = self.convert_yunits(self._y0)
x1 = self.convert_xunits(self._x1)
y1 = self.convert_yunits(self._y1)
return x0, y0, x1, y1
def get_patch_transform(self):
self._update_patch_transform()
return self._rect_transform
def get_x(self):
"Return the left coord of the rectangle."
return self._x0
def get_y(self):
"Return the bottom coord of the rectangle."
return self._y0
def get_xy(self):
"Return the left and bottom coords of the rectangle."
return self._x0, self._y0
def get_width(self):
"Return the width of the rectangle."
return self._width
def get_height(self):
"Return the height of the rectangle."
return self._height
def set_x(self, x):
"Set the left coord of the rectangle."
self._x0 = x
self._update_x1()
self.stale = True
def set_y(self, y):
"Set the bottom coord of the rectangle."
self._y0 = y
self._update_y1()
self.stale = True
def set_xy(self, xy):
"""
Set the left and bottom coords of the rectangle.
Parameters
----------
xy : (float, float)
"""
self._x0, self._y0 = xy
self._update_x1()
self._update_y1()
self.stale = True
def set_width(self, w):
"Set the width of the rectangle."
self._width = w
self._update_x1()
self.stale = True
def set_height(self, h):
"Set the height of the rectangle."
self._height = h
self._update_y1()
self.stale = True
def set_bounds(self, *args):
"""
Set the bounds of the rectangle: l,b,w,h
ACCEPTS: (left, bottom, width, height)
"""
if len(args) == 1:
l, b, w, h = args[0]
else:
l, b, w, h = args
self._x0 = l
self._y0 = b
self._width = w
self._height = h
self._update_x1()
self._update_y1()
self.stale = True
def get_bbox(self):
x0, y0, x1, y1 = self._convert_units()
return transforms.Bbox.from_extents(x0, y0, x1, y1)
xy = property(get_xy, set_xy)
class RegularPolygon(Patch):
"""
A regular polygon patch.
"""
def __str__(self):
s = "RegularPolygon((%g, %g), %d, radius=%g, orientation=%g)"
return s % (self._xy[0], self._xy[1], self._numVertices, self._radius,
self._orientation)
@docstring.dedent_interpd
def __init__(self, xy, numVertices, radius=5, orientation=0,
**kwargs):
"""
Constructor arguments:
*xy*
A length 2 tuple (*x*, *y*) of the center.
*numVertices*
the number of vertices.
*radius*
The distance from the center to each of the vertices.
*orientation*
rotates the polygon (in radians).
Valid kwargs are:
%(Patch)s
"""
self._xy = xy
self._numVertices = numVertices
self._orientation = orientation
self._radius = radius
self._path = Path.unit_regular_polygon(numVertices)
self._poly_transform = transforms.Affine2D()
self._update_transform()
Patch.__init__(self, **kwargs)
def _update_transform(self):
self._poly_transform.clear() \
.scale(self.radius) \
.rotate(self.orientation) \
.translate(*self.xy)
@property
def xy(self):
return self._xy
@xy.setter
def xy(self, xy):
self._xy = xy
self._update_transform()
@property
def orientation(self):
return self._orientation
@orientation.setter
def orientation(self, orientation):
self._orientation = orientation
self._update_transform()
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, radius):
self._radius = radius
self._update_transform()
@property
def numvertices(self):
return self._numVertices
@numvertices.setter
def numvertices(self, numVertices):
self._numVertices = numVertices
def get_path(self):
return self._path
def get_patch_transform(self):
self._update_transform()
return self._poly_transform
class PathPatch(Patch):
"""
A general polycurve path patch.
"""
_edge_default = True
def __str__(self):
s = "PathPatch%d((%g, %g) ...)"
return s % (len(self._path.vertices), *tuple(self._path.vertices[0]))
@docstring.dedent_interpd
def __init__(self, path, **kwargs):
"""
*path* is a :class:`matplotlib.path.Path` object.
Valid kwargs are:
%(Patch)s
"""
Patch.__init__(self, **kwargs)
self._path = path
def get_path(self):
return self._path
class Polygon(Patch):
"""
A general polygon patch.
"""
def __str__(self):
s = "Polygon%d((%g, %g) ...)"
return s % (len(self._path.vertices), *tuple(self._path.vertices[0]))
@docstring.dedent_interpd
def __init__(self, xy, closed=True, **kwargs):
"""
*xy* is a numpy array with shape Nx2.
If *closed* is *True*, the polygon will be closed so the
starting and ending points are the same.
Valid kwargs are:
%(Patch)s
"""
Patch.__init__(self, **kwargs)
self._closed = closed
self.set_xy(xy)
def get_path(self):
"""
Get the path of the polygon
Returns
-------
path : Path
The `~.path.Path` object for the polygon.
"""
return self._path
def get_closed(self):
"""
Returns if the polygon is closed
Returns
-------
closed : bool
If the path is closed
"""
return self._closed
def set_closed(self, closed):
"""
Set if the polygon is closed
Parameters
----------
closed : bool
True if the polygon is closed
"""
if self._closed == bool(closed):
return
self._closed = bool(closed)
self.set_xy(self.get_xy())
self.stale = True
def get_xy(self):
"""
Get the vertices of the path.
Returns
-------
vertices : (N, 2) numpy array
The coordinates of the vertices.
"""
return self._path.vertices
def set_xy(self, xy):
"""
Set the vertices of the polygon.
Parameters
----------
xy : (N, 2) array-like
The coordinates of the vertices.
"""
xy = np.asarray(xy)
if self._closed:
if len(xy) and (xy[0] != xy[-1]).any():
xy = np.concatenate([xy, [xy[0]]])
else:
if len(xy) > 2 and (xy[0] == xy[-1]).all():
xy = xy[:-1]
self._path = Path(xy, closed=self._closed)
self.stale = True
_get_xy = get_xy
_set_xy = set_xy
xy = property(get_xy, set_xy,
doc='The vertices of the path as (N, 2) numpy array.')
class Wedge(Patch):
"""
Wedge shaped patch.
"""
def __str__(self):
pars = (self.center[0], self.center[1], self.r,
self.theta1, self.theta2, self.width)
fmt = "Wedge(center=(%g, %g), r=%g, theta1=%g, theta2=%g, width=%s)"
return fmt % pars
@docstring.dedent_interpd
def __init__(self, center, r, theta1, theta2, width=None, **kwargs):
"""
Draw a wedge centered at *x*, *y* center with radius *r* that
sweeps *theta1* to *theta2* (in degrees). If *width* is given,
then a partial wedge is drawn from inner radius *r* - *width*
to outer radius *r*.
Valid kwargs are:
%(Patch)s
"""
Patch.__init__(self, **kwargs)
self.center = center
self.r, self.width = r, width
self.theta1, self.theta2 = theta1, theta2
self._patch_transform = transforms.IdentityTransform()
self._recompute_path()
def _recompute_path(self):
# Inner and outer rings are connected unless the annulus is complete
if abs((self.theta2 - self.theta1) - 360) <= 1e-12:
theta1, theta2 = 0, 360
connector = Path.MOVETO
else:
theta1, theta2 = self.theta1, self.theta2
connector = Path.LINETO
# Form the outer ring
arc = Path.arc(theta1, theta2)
if self.width is not None:
# Partial annulus needs to draw the outer ring
# followed by a reversed and scaled inner ring
v1 = arc.vertices
v2 = arc.vertices[::-1] * (self.r - self.width) / self.r
v = np.vstack([v1, v2, v1[0, :], (0, 0)])
c = np.hstack([arc.codes, arc.codes, connector, Path.CLOSEPOLY])
c[len(arc.codes)] = connector
else:
# Wedge doesn't need an inner ring
v = np.vstack([arc.vertices, [(0, 0), arc.vertices[0, :], (0, 0)]])
c = np.hstack([arc.codes, [connector, connector, Path.CLOSEPOLY]])
# Shift and scale the wedge to the final location.
v *= self.r
v += np.asarray(self.center)
self._path = Path(v, c)
def set_center(self, center):
self._path = None
self.center = center
self.stale = True
def set_radius(self, radius):
self._path = None
self.r = radius
self.stale = True
def set_theta1(self, theta1):
self._path = None
self.theta1 = theta1
self.stale = True
def set_theta2(self, theta2):
self._path = None
self.theta2 = theta2
self.stale = True
def set_width(self, width):
self._path = None
self.width = width
self.stale = True
def get_path(self):
if self._path is None:
self._recompute_path()
return self._path
# COVERAGE NOTE: Not used internally or from examples
class Arrow(Patch):
"""
An arrow patch.
"""
def __str__(self):
return "Arrow()"
_path = Path([[0.0, 0.1], [0.0, -0.1],
[0.8, -0.1], [0.8, -0.3],
[1.0, 0.0], [0.8, 0.3],
[0.8, 0.1], [0.0, 0.1]],
closed=True)
@docstring.dedent_interpd
def __init__(self, x, y, dx, dy, width=1.0, **kwargs):
"""
Draws an arrow from (*x*, *y*) to (*x* + *dx*, *y* + *dy*).
The width of the arrow is scaled by *width*.
Parameters
----------
x : scalar
x coordinate of the arrow tail
y : scalar
y coordinate of the arrow tail
dx : scalar
Arrow length in the x direction
dy : scalar
Arrow length in the y direction
width : scalar, optional (default: 1)
Scale factor for the width of the arrow. With a default value of
1, the tail width is 0.2 and head width is 0.6.
**kwargs
Keyword arguments control the `Patch` properties:
%(Patch)s
See Also
--------
:class:`FancyArrow` :
Patch that allows independent control of the head and tail
properties
"""
Patch.__init__(self, **kwargs)
L = np.hypot(dx, dy)
if L != 0:
cx = dx / L
sx = dy / L
else:
# Account for division by zero
cx, sx = 0, 1
trans1 = transforms.Affine2D().scale(L, width)
trans2 = transforms.Affine2D.from_values(cx, sx, -sx, cx, 0.0, 0.0)
trans3 = transforms.Affine2D().translate(x, y)
trans = trans1 + trans2 + trans3
self._patch_transform = trans.frozen()
def get_path(self):
return self._path
def get_patch_transform(self):
return self._patch_transform
class FancyArrow(Polygon):
"""
Like Arrow, but lets you set head width and head height independently.
"""
_edge_default = True
def __str__(self):
return "FancyArrow()"
@docstring.dedent_interpd
def __init__(self, x, y, dx, dy, width=0.001, length_includes_head=False,
head_width=None, head_length=None, shape='full', overhang=0,
head_starts_at_zero=False, **kwargs):
"""
Constructor arguments
*width*: float (default: 0.001)
width of full arrow tail
*length_includes_head*: bool (default: False)
True if head is to be counted in calculating the length.
*head_width*: float or None (default: 3*width)
total width of the full arrow head
*head_length*: float or None (default: 1.5 * head_width)
length of arrow head
*shape*: ['full', 'left', 'right'] (default: 'full')
draw the left-half, right-half, or full arrow
*overhang*: float (default: 0)
fraction that the arrow is swept back (0 overhang means
triangular shape). Can be negative or greater than one.
*head_starts_at_zero*: bool (default: False)
if True, the head starts being drawn at coordinate 0
instead of ending at coordinate 0.
Other valid kwargs (inherited from :class:`Patch`) are:
%(Patch)s
"""
if head_width is None:
head_width = 3 * width
if head_length is None:
head_length = 1.5 * head_width
distance = np.hypot(dx, dy)
if length_includes_head:
length = distance
else:
length = distance + head_length
if not length:
verts = np.empty([0, 2]) # display nothing if empty
else:
# start by drawing horizontal arrow, point at (0,0)
hw, hl, hs, lw = head_width, head_length, overhang, width
left_half_arrow = np.array([
[0.0, 0.0], # tip
[-hl, -hw / 2], # leftmost
[-hl * (1 - hs), -lw / 2], # meets stem
[-length, -lw / 2], # bottom left
[-length, 0],
])
# if we're not including the head, shift up by head length
if not length_includes_head:
left_half_arrow += [head_length, 0]
# if the head starts at 0, shift up by another head length
if head_starts_at_zero:
left_half_arrow += [head_length / 2, 0]
# figure out the shape, and complete accordingly
if shape == 'left':
coords = left_half_arrow
else:
right_half_arrow = left_half_arrow * [1, -1]
if shape == 'right':
coords = right_half_arrow
elif shape == 'full':
# The half-arrows contain the midpoint of the stem,
# which we can omit from the full arrow. Including it
# twice caused a problem with xpdf.
coords = np.concatenate([left_half_arrow[:-1],
right_half_arrow[-2::-1]])
else:
raise ValueError("Got unknown shape: %s" % shape)
if distance != 0:
cx = dx / distance
sx = dy / distance
else:
# Account for division by zero
cx, sx = 0, 1
M = [[cx, sx], [-sx, cx]]
verts = np.dot(coords, M) + (x + dx, y + dy)
super().__init__(verts, closed=True, **kwargs)
docstring.interpd.update({"FancyArrow": FancyArrow.__init__.__doc__})
@cbook.deprecated("3.0", alternative="FancyArrowPatch")
class YAArrow(Patch):
"""
Yet another arrow class.
This is an arrow that is defined in display space and has a tip at
*x1*, *y1* and a base at *x2*, *y2*.
"""
def __str__(self):
return "YAArrow()"
@docstring.dedent_interpd
def __init__(self, figure, xytip, xybase,
width=4, frac=0.1, headwidth=12, **kwargs):
"""
Constructor arguments:
*xytip*
(*x*, *y*) location of arrow tip
*xybase*
(*x*, *y*) location the arrow base mid point
*figure*
The `Figure` instance (used to get the dpi setting).
*width*
The width of the arrow in points
*frac*
The fraction of the arrow length occupied by the head
*headwidth*
The width of the base of the arrow head in points
Valid kwargs are:
%(Patch)s
"""
self.xytip = xytip
self.xybase = xybase
self.width = width
self.frac = frac
self.headwidth = headwidth
Patch.__init__(self, **kwargs)
# Set self.figure after Patch.__init__, since it sets self.figure to
# None
self.figure = figure
def get_path(self):
# Since this is dpi dependent, we need to recompute the path
# every time.
# the base vertices
x1, y1 = self.xytip
x2, y2 = self.xybase
k1 = self.width * self.figure.dpi / 72. / 2.
k2 = self.headwidth * self.figure.dpi / 72. / 2.
xb1, yb1, xb2, yb2 = self.getpoints(x1, y1, x2, y2, k1)
# a point on the segment 20% of the distance from the tip to the base
xm = x1 + self.frac * (x2 - x1)
ym = y1 + self.frac * (y2 - y1)
xc1, yc1, xc2, yc2 = self.getpoints(x1, y1, xm, ym, k1)
xd1, yd1, xd2, yd2 = self.getpoints(x1, y1, xm, ym, k2)
xs = self.convert_xunits([xb1, xb2, xc2, xd2, x1, xd1, xc1, xb1])
ys = self.convert_yunits([yb1, yb2, yc2, yd2, y1, yd1, yc1, yb1])
return Path(np.column_stack([xs, ys]), closed=True)
def get_patch_transform(self):
return transforms.IdentityTransform()
def getpoints(self, x1, y1, x2, y2, k):
"""
For line segment defined by (*x1*, *y1*) and (*x2*, *y2*)
return the points on the line that is perpendicular to the
line and intersects (*x2*, *y2*) and the distance from (*x2*,
*y2*) of the returned points is *k*.
"""
x1, y1, x2, y2, k = map(float, (x1, y1, x2, y2, k))
if y2 - y1 == 0:
return x2, y2 + k, x2, y2 - k
elif x2 - x1 == 0:
return x2 + k, y2, x2 - k, y2
m = (y2 - y1) / (x2 - x1)
pm = -1. / m
a = 1
b = -2 * y2
c = y2 ** 2. - k ** 2. * pm ** 2. / (1. + pm ** 2.)
y3a = (-b + math.sqrt(b ** 2 - 4 * a * c)) / (2 * a)
x3a = (y3a - y2) / pm + x2
y3b = (-b - math.sqrt(b ** 2 - 4 * a * c)) / (2 * a)
x3b = (y3b - y2) / pm + x2
return x3a, y3a, x3b, y3b
class CirclePolygon(RegularPolygon):
"""
A polygon-approximation of a circle patch.
"""
def __str__(self):
s = "CirclePolygon((%g, %g), radius=%g, resolution=%d)"
return s % (self._xy[0], self._xy[1], self._radius, self._numVertices)
@docstring.dedent_interpd
def __init__(self, xy, radius=5,
resolution=20, # the number of vertices
** kwargs):
"""
Create a circle at *xy* = (*x*, *y*) with given *radius*.
This circle is approximated by a regular polygon with
*resolution* sides. For a smoother circle drawn with splines,
see :class:`~matplotlib.patches.Circle`.
Valid kwargs are:
%(Patch)s
"""
RegularPolygon.__init__(self, xy,
resolution,
radius,
orientation=0,
**kwargs)
class Ellipse(Patch):
"""
A scale-free ellipse.
"""
def __str__(self):
pars = (self._center[0], self._center[1],
self.width, self.height, self.angle)
fmt = "Ellipse(xy=(%s, %s), width=%s, height=%s, angle=%s)"
return fmt % pars
@docstring.dedent_interpd
def __init__(self, xy, width, height, angle=0, **kwargs):
"""
Parameters
----------
xy : (float, float)
xy coordinates of ellipse centre.
width : float
Total length (diameter) of horizontal axis.
height : float
Total length (diameter) of vertical axis.
angle : scalar, optional
Rotation in degrees anti-clockwise.
Notes
-----
Valid keyword arguments are
%(Patch)s
"""
Patch.__init__(self, **kwargs)
self._center = xy
self.width, self.height = width, height
self.angle = angle
self._path = Path.unit_circle()
# Note: This cannot be calculated until this is added to an Axes
self._patch_transform = transforms.IdentityTransform()
def _recompute_transform(self):
"""NOTE: This cannot be called until after this has been added
to an Axes, otherwise unit conversion will fail. This
makes it very important to call the accessor method and
not directly access the transformation member variable.
"""
center = (self.convert_xunits(self._center[0]),
self.convert_yunits(self._center[1]))
width = self.convert_xunits(self.width)
height = self.convert_yunits(self.height)
self._patch_transform = transforms.Affine2D() \
.scale(width * 0.5, height * 0.5) \
.rotate_deg(self.angle) \
.translate(*center)
def get_path(self):
"""
Return the vertices of the rectangle
"""
return self._path
def get_patch_transform(self):
self._recompute_transform()
return self._patch_transform
def set_center(self, xy):
"""
Set the center of the ellipse.
Parameters
----------
xy : (float, float)
"""
self._center = xy
self.stale = True
def get_center(self):
"""
Return the center of the ellipse
"""
return self._center
center = property(get_center, set_center)
class Circle(Ellipse):
"""
A circle patch.
"""
def __str__(self):
pars = self.center[0], self.center[1], self.radius
fmt = "Circle(xy=(%g, %g), radius=%g)"
return fmt % pars
@docstring.dedent_interpd
def __init__(self, xy, radius=5, **kwargs):
"""
Create true circle at center *xy* = (*x*, *y*) with given
*radius*. Unlike :class:`~matplotlib.patches.CirclePolygon`
which is a polygonal approximation, this uses Bezier splines
and is much closer to a scale-free circle.
Valid kwargs are:
%(Patch)s
"""
Ellipse.__init__(self, xy, radius * 2, radius * 2, **kwargs)
self.radius = radius
def set_radius(self, radius):
"""
Set the radius of the circle
Parameters
----------
radius : float
"""
self.width = self.height = 2 * radius
self.stale = True
def get_radius(self):
"""
Return the radius of the circle
"""
return self.width / 2.
radius = property(get_radius, set_radius)
class Arc(Ellipse):
"""
An elliptical arc, i.e. a segment of an ellipse.
Due to internal optimizations, there are certain restrictions on using Arc:
- The arc cannot be filled.
- The arc must be used in an :class:`~.axes.Axes` instance---it can not be
added directly to a `.Figure`---because it is optimized to only render
the segments that are inside the axes bounding box with high resolution.
"""
def __str__(self):
pars = (self.center[0], self.center[1], self.width,
self.height, self.angle, self.theta1, self.theta2)
fmt = ("Arc(xy=(%g, %g), width=%g, "
"height=%g, angle=%g, theta1=%g, theta2=%g)")
return fmt % pars
@docstring.dedent_interpd
def __init__(self, xy, width, height, angle=0.0,
theta1=0.0, theta2=360.0, **kwargs):
"""
Parameters
----------
xy : (float, float)
The center of the ellipse.
width : float
The length of the horizontal axis.
height : float
The length of the vertical axis.
angle : float
Rotation of the ellipse in degrees (counterclockwise).
theta1, theta2 : float, optional
Starting and ending angles of the arc in degrees. These values
are relative to *angle*, e.g. if *angle* = 45 and *theta1* = 90
the absolute starting angle is 135.
Default *theta1* = 0, *theta2* = 360, i.e. a complete ellipse.
The arc is drawn in the counterclockwise direction.
Angles greater than or equal to 360, or smaller than 0, are
represented by an equivalent angle in the range [0, 360), by
taking the input value mod 360.
Other Parameters
----------------
**kwargs : `.Patch` properties
Most `.Patch` properties are supported as keyword arguments,
with the exception of *fill* and *facecolor* because filling is
not supported.
%(Patch)s
"""
fill = kwargs.setdefault('fill', False)
if fill:
raise ValueError("Arc objects can not be filled")
Ellipse.__init__(self, xy, width, height, angle, **kwargs)
self.theta1 = theta1
self.theta2 = theta2
@artist.allow_rasterization
def draw(self, renderer):
"""
Draw the arc to the given *renderer*.
Notes
-----
Ellipses are normally drawn using an approximation that uses
eight cubic Bezier splines. The error of this approximation
is 1.89818e-6, according to this unverified source:
Lancaster, Don. *Approximating a Circle or an Ellipse Using
Four Bezier Cubic Splines.*
http://www.tinaja.com/glib/ellipse4.pdf
There is a use case where very large ellipses must be drawn
with very high accuracy, and it is too expensive to render the
entire ellipse with enough segments (either splines or line
segments). Therefore, in the case where either radius of the
ellipse is large enough that the error of the spline
approximation will be visible (greater than one pixel offset
from the ideal), a different technique is used.
In that case, only the visible parts of the ellipse are drawn,
with each visible arc using a fixed number of spline segments
(8). The algorithm proceeds as follows:
1. The points where the ellipse intersects the axes bounding
box are located. (This is done be performing an inverse
transformation on the axes bbox such that it is relative
to the unit circle -- this makes the intersection
calculation much easier than doing rotated ellipse
intersection directly).
This uses the "line intersecting a circle" algorithm
from:
Vince, John. *Geometry for Computer Graphics: Formulae,
Examples & Proofs.* London: Springer-Verlag, 2005.
2. The angles of each of the intersection points are
calculated.
3. Proceeding counterclockwise starting in the positive
x-direction, each of the visible arc-segments between the
pairs of vertices are drawn using the Bezier arc
approximation technique implemented in
:meth:`matplotlib.path.Path.arc`.
"""
if not hasattr(self, 'axes'):
raise RuntimeError('Arcs can only be used in Axes instances')
self._recompute_transform()
width = self.convert_xunits(self.width)
height = self.convert_yunits(self.height)
# If the width and height of ellipse are not equal, take into account
# stretching when calculating angles to draw between
def theta_stretch(theta, scale):
theta = np.deg2rad(theta)
x = np.cos(theta)
y = np.sin(theta)
return np.rad2deg(np.arctan2(scale * y, x))
theta1 = theta_stretch(self.theta1, width / height)
theta2 = theta_stretch(self.theta2, width / height)
# Get width and height in pixels
width, height = self.get_transform().transform_point((width, height))
inv_error = (1.0 / 1.89818e-6) * 0.5
if width < inv_error and height < inv_error:
self._path = Path.arc(theta1, theta2)
return Patch.draw(self, renderer)
def iter_circle_intersect_on_line(x0, y0, x1, y1):
dx = x1 - x0
dy = y1 - y0
dr2 = dx * dx + dy * dy
D = x0 * y1 - x1 * y0
D2 = D * D
discrim = dr2 - D2
# Single (tangential) intersection
if discrim == 0.0:
x = (D * dy) / dr2
y = (-D * dx) / dr2
yield x, y
elif discrim > 0.0:
# The definition of "sign" here is different from
# np.sign: we never want to get 0.0
if dy < 0.0:
sign_dy = -1.0
else:
sign_dy = 1.0
sqrt_discrim = np.sqrt(discrim)
for sign in (1., -1.):
x = (D * dy + sign * sign_dy * dx * sqrt_discrim) / dr2
y = (-D * dx + sign * np.abs(dy) * sqrt_discrim) / dr2
yield x, y
def iter_circle_intersect_on_line_seg(x0, y0, x1, y1):
epsilon = 1e-9
if x1 < x0:
x0e, x1e = x1, x0
else:
x0e, x1e = x0, x1
if y1 < y0:
y0e, y1e = y1, y0
else:
y0e, y1e = y0, y1
x0e -= epsilon
y0e -= epsilon
x1e += epsilon
y1e += epsilon
for x, y in iter_circle_intersect_on_line(x0, y0, x1, y1):
if x0e <= x <= x1e and y0e <= y <= y1e:
yield x, y
# Transforms the axes box_path so that it is relative to the unit
# circle in the same way that it is relative to the desired
# ellipse.
box_path = Path.unit_rectangle()
box_path_transform = transforms.BboxTransformTo(self.axes.bbox) + \
self.get_transform().inverted()
box_path = box_path.transformed(box_path_transform)
thetas = set()
# For each of the point pairs, there is a line segment
for p0, p1 in zip(box_path.vertices[:-1], box_path.vertices[1:]):
x0, y0 = p0
x1, y1 = p1
for x, y in iter_circle_intersect_on_line_seg(x0, y0, x1, y1):
theta = np.arccos(x)
if y < 0:
theta = 2 * np.pi - theta
# Convert radians to angles
theta = np.rad2deg(theta)
if theta1 < theta < theta2:
thetas.add(theta)
thetas = sorted(thetas) + [theta2]
last_theta = theta1
theta1_rad = np.deg2rad(theta1)
inside = box_path.contains_point((np.cos(theta1_rad),
np.sin(theta1_rad)))
# save original path
path_original = self._path
for theta in thetas:
if inside:
self._path = Path.arc(last_theta, theta, 8)
Patch.draw(self, renderer)
inside = False
else:
inside = True
last_theta = theta
# restore original path
self._path = path_original
def bbox_artist(artist, renderer, props=None, fill=True):
"""
This is a debug function to draw a rectangle around the bounding
box returned by
:meth:`~matplotlib.artist.Artist.get_window_extent` of an artist,
to test whether the artist is returning the correct bbox.
*props* is a dict of rectangle props with the additional property
'pad' that sets the padding around the bbox in points.
"""
if props is None:
props = {}
props = props.copy() # don't want to alter the pad externally
pad = props.pop('pad', 4)
pad = renderer.points_to_pixels(pad)
bbox = artist.get_window_extent(renderer)
l, b, w, h = bbox.bounds
l -= pad / 2.
b -= pad / 2.
w += pad
h += pad
r = Rectangle(xy=(l, b),
width=w,
height=h,
fill=fill,
)
r.set_transform(transforms.IdentityTransform())
r.set_clip_on(False)
r.update(props)
r.draw(renderer)
def draw_bbox(bbox, renderer, color='k', trans=None):
"""
This is a debug function to draw a rectangle around the bounding
box returned by
:meth:`~matplotlib.artist.Artist.get_window_extent` of an artist,
to test whether the artist is returning the correct bbox.
"""
l, b, w, h = bbox.bounds
r = Rectangle(xy=(l, b),
width=w,
height=h,
edgecolor=color,
fill=False,
)
if trans is not None:
r.set_transform(trans)
r.set_clip_on(False)
r.draw(renderer)
def _pprint_table(table, leadingspace=2):
"""
Given the list of list of strings, return a string of REST table format.
"""
col_len = [max(len(cell) for cell in column) for column in zip(*table)]
table_formatstr = ' '.join('=' * cl for cl in col_len)
lines = [
'',
table_formatstr,
' '.join(cell.ljust(cl) for cell, cl in zip(table[0], col_len)),
table_formatstr,
*[' '.join(cell.ljust(cl) for cell, cl in zip(row, col_len))
for row in table[1:]],
table_formatstr,
'',
]
return textwrap.indent('\n'.join(lines), ' ' * leadingspace)
def _pprint_styles(_styles):
"""
A helper function for the _Style class. Given the dictionary of
{stylename: styleclass}, return a formatted string listing all the
styles. Used to update the documentation.
"""
import inspect
_table = [["Class", "Name", "Attrs"]]
for name, cls in sorted(_styles.items()):
spec = inspect.getfullargspec(cls.__init__)
if spec.defaults:
argstr = ", ".join(map(
"{}={}".format, spec.args[-len(spec.defaults):], spec.defaults
))
else:
argstr = 'None'
# adding ``quotes`` since - and | have special meaning in reST
_table.append([cls.__name__, "``%s``" % name, argstr])
return _pprint_table(_table)
def _simpleprint_styles(_styles):
"""
A helper function for the _Style class. Given the dictionary of
{stylename: styleclass}, return a string rep of the list of keys.
Used to update the documentation.
"""
return "[{}]".format("|".join(map(" '{}' ".format, sorted(_styles))))
class _Style(object):
"""
A base class for the Styles. It is meant to be a container class,
where actual styles are declared as subclass of it, and it
provides some helper functions.
"""
def __new__(cls, stylename, **kw):
"""
return the instance of the subclass with the given style name.
"""
# The "class" should have the _style_list attribute, which is a mapping
# of style names to style classes.
_list = stylename.replace(" ", "").split(",")
_name = _list[0].lower()
try:
_cls = cls._style_list[_name]
except KeyError:
raise ValueError("Unknown style : %s" % stylename)
try:
_args_pair = [cs.split("=") for cs in _list[1:]]
_args = {k: float(v) for k, v in _args_pair}
except ValueError:
raise ValueError("Incorrect style argument : %s" % stylename)
_args.update(kw)
return _cls(**_args)
@classmethod
def get_styles(cls):
"""
A class method which returns a dictionary of available styles.
"""
return cls._style_list
@classmethod
def pprint_styles(cls):
"""
A class method which returns a string of the available styles.
"""
return _pprint_styles(cls._style_list)
@classmethod
def register(cls, name, style):
"""
Register a new style.
"""
if not issubclass(style, cls._Base):
raise ValueError("%s must be a subclass of %s" % (style,
cls._Base))
cls._style_list[name] = style
def _register_style(style_list, cls=None, *, name=None):
"""Class decorator that stashes a class in a (style) dictionary."""
if cls is None:
return functools.partial(_register_style, style_list, name=name)
style_list[name or cls.__name__.lower()] = cls
return cls
class BoxStyle(_Style):
"""
:class:`BoxStyle` is a container class which defines several
boxstyle classes, which are used for :class:`FancyBboxPatch`.
A style object can be created as::
BoxStyle.Round(pad=0.2)
or::
BoxStyle("Round", pad=0.2)
or::
BoxStyle("Round, pad=0.2")
Following boxstyle classes are defined.
%(AvailableBoxstyles)s
An instance of any boxstyle class is an callable object,
whose call signature is::
__call__(self, x0, y0, width, height, mutation_size, aspect_ratio=1.)
and returns a :class:`Path` instance. *x0*, *y0*, *width* and
*height* specify the location and size of the box to be
drawn. *mutation_scale* determines the overall size of the
mutation (by which I mean the transformation of the rectangle to
the fancy box). *mutation_aspect* determines the aspect-ratio of
the mutation.
"""
_style_list = {}
class _Base(object):
"""
:class:`BBoxTransmuterBase` and its derivatives are used to make a
fancy box around a given rectangle. The :meth:`__call__` method
returns the :class:`~matplotlib.path.Path` of the fancy box. This
class is not an artist and actual drawing of the fancy box is done
by the :class:`FancyBboxPatch` 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.
def transmute(self, x0, y0, width, height, mutation_size):
"""
The transmute method is a very core of the
:class:`BboxTransmuter` class and must be overridden in the
subclasses. It receives the location and size of the
rectangle, and the mutation_size, with which the amount of
padding and etc. will be scaled. It returns a
:class:`~matplotlib.path.Path` instance.
"""
raise NotImplementedError('Derived must override')
def __call__(self, x0, y0, width, height, mutation_size,
aspect_ratio=1.):
"""
Given the location and size of the box, return the path of
the box around it.
- *x0*, *y0*, *width*, *height* : location and size of the box
- *mutation_size* : a reference scale for the mutation.
- *aspect_ratio* : aspect-ration for the mutation.
"""
# The __call__ method is a thin wrapper around the transmute method
# and takes care of the aspect.
if aspect_ratio is not None:
# Squeeze the given height by the aspect_ratio
y0, height = y0 / aspect_ratio, height / aspect_ratio
# call transmute method with squeezed height.
path = self.transmute(x0, y0, width, height, mutation_size)
vertices, codes = path.vertices, path.codes
# Restore the height
vertices[:, 1] = vertices[:, 1] * aspect_ratio
return Path(vertices, codes)
else:
return self.transmute(x0, y0, width, height, mutation_size)
@_register_style(_style_list)
class Square(_Base):
"""
A simple square box.
"""
def __init__(self, pad=0.3):
"""
*pad*
amount of padding
"""
self.pad = pad
super().__init__()
def transmute(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
vertices = [(x0, y0), (x1, y0), (x1, y1), (x0, y1), (x0, y0)]
codes = [Path.MOVETO] + [Path.LINETO] * 3 + [Path.CLOSEPOLY]
return Path(vertices, codes)
@_register_style(_style_list)
class Circle(_Base):
"""A simple circle box."""
def __init__(self, pad=0.3):
"""
Parameters
----------
pad : float
The amount of padding around the original box.
"""
self.pad = pad
super().__init__()
def transmute(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 LArrow(_Base):
"""
(left) Arrow Box
"""
def __init__(self, pad=0.3):
self.pad = pad
super().__init__()
def transmute(self, x0, y0, width, height, mutation_size):
# padding
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
dx = (y1 - y0) / 2.
dxx = dx * .5
# adjust x0. 1.4 <- sqrt(2)
x0 = x0 + pad / 1.4
cp = [(x0 + dxx, y0), (x1, y0), (x1, y1), (x0 + dxx, y1),
(x0 + dxx, y1 + dxx), (x0 - dx, y0 + dx),
(x0 + dxx, y0 - dxx), # arrow
(x0 + dxx, y0), (x0 + dxx, y0)]
com = [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO,
Path.LINETO, Path.LINETO, Path.LINETO,
Path.LINETO, Path.CLOSEPOLY]
path = Path(cp, com)
return path
@_register_style(_style_list)
class RArrow(LArrow):
"""
(right) Arrow Box
"""
def __init__(self, pad=0.3):
super().__init__(pad)
def transmute(self, x0, y0, width, height, mutation_size):
p = BoxStyle.LArrow.transmute(self, x0, y0,
width, height, mutation_size)
p.vertices[:, 0] = 2 * x0 + width - p.vertices[:, 0]
return p
@_register_style(_style_list)
class DArrow(_Base):
"""
(Double) Arrow Box
"""
# This source is copied from LArrow,
# modified to add a right arrow to the bbox.
def __init__(self, pad=0.3):
self.pad = pad
super().__init__()
def transmute(self, x0, y0, width, height, mutation_size):
# padding
pad = mutation_size * self.pad
# width and height with padding added.
# The width is padded by the arrows, so we don't need to pad it.
height = height + 2. * pad
# boundary of the padded box
x0, y0 = x0 - pad, y0 - pad
x1, y1 = x0 + width, y0 + height
dx = (y1 - y0) / 2
dxx = dx * .5
# adjust x0. 1.4 <- sqrt(2)
x0 = x0 + pad / 1.4
cp = [(x0 + dxx, y0), (x1, y0), # bot-segment
(x1, y0 - dxx), (x1 + dx + dxx, y0 + dx),
(x1, y1 + dxx), # right-arrow
(x1, y1), (x0 + dxx, y1), # top-segment
(x0 + dxx, y1 + dxx), (x0 - dx, y0 + dx),
(x0 + dxx, y0 - dxx), # left-arrow
(x0 + dxx, y0), (x0 + dxx, y0)] # close-poly
com = [Path.MOVETO, Path.LINETO,
Path.LINETO, Path.LINETO,
Path.LINETO,
Path.LINETO, Path.LINETO,
Path.LINETO, Path.LINETO,
Path.LINETO,
Path.LINETO, Path.CLOSEPOLY]
path = Path(cp, com)
return path
@_register_style(_style_list)
class Round(_Base):
"""
A box with round corners.
"""
def __init__(self, pad=0.3, rounding_size=None):
"""
*pad*
amount of padding
*rounding_size*
rounding radius of corners. *pad* if None
"""
self.pad = pad
self.rounding_size = rounding_size
super().__init__()
def transmute(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]
path = Path(cp, com)
return path
@_register_style(_style_list)
class Round4(_Base):
"""
Another box with round edges.
"""
def __init__(self, pad=0.3, rounding_size=None):
"""
*pad*
amount of padding
*rounding_size*
rounding size of edges. *pad* if None
"""
self.pad = pad
self.rounding_size = rounding_size
super().__init__()
def transmute(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, height = (width + 2. * pad - 2 * dr,
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]
path = Path(cp, com)
return path
@_register_style(_style_list)
class Sawtooth(_Base):
"""
A sawtooth box.
"""
def __init__(self, pad=0.3, tooth_size=None):
"""
*pad*
amount of padding
*tooth_size*
size of the sawtooth. pad* if None
"""
self.pad = pad
self.tooth_size = tooth_size
super().__init__()
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
tooth_size2 = tooth_size / 2.
width, height = (width + 2. * pad - tooth_size,
height + 2. * pad - tooth_size)
# the sizes of the vertical and horizontal sawtooth are
# separately adjusted to fit the given box size.
dsx_n = int(np.round((width - tooth_size) / (tooth_size * 2))) * 2
dsx = (width - tooth_size) / dsx_n
dsy_n = int(np.round((height - tooth_size) / (tooth_size * 2))) * 2
dsy = (height - tooth_size) / dsy_n
x0, y0 = x0 - pad + tooth_size2, y0 - pad + tooth_size2
x1, y1 = x0 + width, y0 + height
bottom_saw_x = [
x0,
*(x0 + tooth_size2 + dsx * .5 * np.arange(dsx_n * 2)),
x1 - tooth_size2,
]
bottom_saw_y = [
y0,
*([y0 - tooth_size2, y0, y0 + tooth_size2, y0] * dsx_n),
y0 - tooth_size2,
]
right_saw_x = [
x1,
*([x1 + tooth_size2, x1, x1 - tooth_size2, x1] * dsx_n),
x1 + tooth_size2,
]
right_saw_y = [
y0,
*(y0 + tooth_size2 + dsy * .5 * np.arange(dsy_n * 2)),
y1 - tooth_size2,
]
top_saw_x = [
x1,
*(x1 - tooth_size2 - dsx * .5 * np.arange(dsx_n * 2)),
x0 + tooth_size2,
]
top_saw_y = [
y1,
*([y1 + tooth_size2, y1, y1 - tooth_size2, y1] * dsx_n),
y1 + tooth_size2,
]
left_saw_x = [
x0,
*([x0 - tooth_size2, x0, x0 + tooth_size2, x0] * dsy_n),
x0 - tooth_size2,
]
left_saw_y = [
y1,
*(y1 - tooth_size2 - dsy * .5 * np.arange(dsy_n * 2)),
y0 + tooth_size2,
]
saw_vertices = [*zip(bottom_saw_x, bottom_saw_y),
*zip(right_saw_x, right_saw_y),
*zip(top_saw_x, top_saw_y),
*zip(left_saw_x, left_saw_y),
(bottom_saw_x[0], bottom_saw_y[0])]
return saw_vertices
def transmute(self, x0, y0, width, height, mutation_size):
saw_vertices = self._get_sawtooth_vertices(x0, y0, width,
height, mutation_size)
path = Path(saw_vertices, closed=True)
return path
@_register_style(_style_list)
class Roundtooth(Sawtooth):
"""A rounded tooth box."""
def __init__(self, pad=0.3, tooth_size=None):
"""
*pad*
amount of padding
*tooth_size*
size of the sawtooth. pad* if None
"""
super().__init__(pad, tooth_size)
def transmute(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([np.array(saw_vertices),
[saw_vertices[0]]], axis=0)
codes = ([Path.MOVETO] +
[Path.CURVE3, Path.CURVE3] * ((len(saw_vertices)-1)//2) +
[Path.CLOSEPOLY])
return Path(saw_vertices, codes)
if __doc__: # __doc__ could be None if -OO optimization is enabled
__doc__ = inspect.cleandoc(__doc__) % {
"AvailableBoxstyles": _pprint_styles(_style_list)}
docstring.interpd.update(
AvailableBoxstyles=_pprint_styles(BoxStyle._style_list),
ListBoxstyles=_simpleprint_styles(BoxStyle._style_list))
class FancyBboxPatch(Patch):
"""
Draw a fancy box around a rectangle with lower left at *xy*=(*x*,
*y*) with specified width and height.
:class:`FancyBboxPatch` class is similar to :class:`Rectangle`
class, but it draws a fancy box around the rectangle. The
transformation of the rectangle box to the fancy box is delegated
to the :class:`BoxTransmuterBase` and its derived classes.
"""
_edge_default = True
def __str__(self):
s = self.__class__.__name__ + "((%g, %g), width=%g, height=%g)"
return s % (self._x, self._y, self._width, self._height)
@docstring.dedent_interpd
def __init__(self, xy, width, height,
boxstyle="round",
bbox_transmuter=None,
mutation_scale=1.,
mutation_aspect=None,
**kwargs):
"""
*xy* = lower left corner
*width*, *height*
*boxstyle* determines what kind of fancy box will be drawn. It
can be a string of the style name with a comma separated
attribute, or an instance of :class:`BoxStyle`. Following box
styles are available.
%(AvailableBoxstyles)s
*mutation_scale* : a value with which attributes of boxstyle
(e.g., pad) will be scaled. default=1.
*mutation_aspect* : The height of the rectangle will be
squeezed by this value before the mutation and the mutated
box will be stretched by the inverse of it. default=None.
Valid kwargs are:
%(Patch)s
"""
Patch.__init__(self, **kwargs)
self._x = xy[0]
self._y = xy[1]
self._width = width
self._height = height
if boxstyle == "custom":
if bbox_transmuter is None:
raise ValueError("bbox_transmuter argument is needed with "
"custom boxstyle")
self._bbox_transmuter = bbox_transmuter
else:
self.set_boxstyle(boxstyle)
self._mutation_scale = mutation_scale
self._mutation_aspect = mutation_aspect
self.stale = True
@docstring.dedent_interpd
def set_boxstyle(self, boxstyle=None, **kw):
"""
Set the box style.
*boxstyle* can be a string with boxstyle name with optional
comma-separated attributes. Alternatively, the attrs can
be provided as keywords::
set_boxstyle("round,pad=0.2")
set_boxstyle("round", pad=0.2)
Old attrs simply are forgotten.
Without argument (or with *boxstyle* = None), it returns
available box styles.
The following boxstyles are available:
%(AvailableBoxstyles)s
ACCEPTS: %(ListBoxstyles)s
"""
if boxstyle is None:
return BoxStyle.pprint_styles()
if isinstance(boxstyle, BoxStyle._Base) or callable(boxstyle):
self._bbox_transmuter = boxstyle
else:
self._bbox_transmuter = BoxStyle(boxstyle, **kw)
self.stale = True
def set_mutation_scale(self, scale):
"""
Set the mutation scale.
Parameters
----------
scale : float
"""
self._mutation_scale = scale
self.stale = True
def get_mutation_scale(self):
"""
Return the mutation scale.
"""
return self._mutation_scale
def set_mutation_aspect(self, aspect):
"""
Set the aspect ratio of the bbox mutation.
Parameters
----------
aspect : float
"""
self._mutation_aspect = aspect
self.stale = True
def get_mutation_aspect(self):
"""
Return the aspect ratio of the bbox mutation.
"""
return self._mutation_aspect
def get_boxstyle(self):
"Return the boxstyle object"
return self._bbox_transmuter
def get_path(self):
"""
Return the mutated path of the rectangle
"""
_path = self.get_boxstyle()(self._x, self._y,
self._width, self._height,
self.get_mutation_scale(),
self.get_mutation_aspect())
return _path
# Following methods are borrowed from the Rectangle class.
def get_x(self):
"Return the left coord of the rectangle"
return self._x
def get_y(self):
"Return the bottom coord of the rectangle"
return self._y
def get_width(self):
"Return the width of the rectangle"
return self._width
def get_height(self):
"Return the height of the rectangle"
return self._height
def set_x(self, x):
"""
Set the left coord of the rectangle.
Parameters
----------
x : float
"""
self._x = x
self.stale = True
def set_y(self, y):
"""
Set the bottom coord of the rectangle.
Parameters
----------
y : float
"""
self._y = y
self.stale = True
def set_width(self, w):
"""
Set the rectangle width.
Parameters
----------
w : float
"""
self._width = w
self.stale = True
def set_height(self, h):
"""
Set the rectangle height.
Parameters
----------
h : float
"""
self._height = h
self.stale = True
def set_bounds(self, *args):
"""
Set the bounds of the rectangle: l,b,w,h
ACCEPTS: (left, bottom, width, height)
"""
if len(args) == 1:
l, b, w, h = args[0]
else:
l, b, w, h = args
self._x = l
self._y = b
self._width = w
self._height = h
self.stale = True
def get_bbox(self):
return transforms.Bbox.from_bounds(self._x, self._y,
self._width, self._height)
class ConnectionStyle(_Style):
"""
:class:`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
:class:`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
%(AvailableConnectorstyles)s
An instance of any connection style class is an callable object,
whose call signature is::
__call__(self, posA, posB,
patchA=None, patchB=None,
shrinkA=2., shrinkB=2.)
and it returns a :class:`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(object):
"""
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.
"""
class SimpleEvent:
def __init__(self, xy):
self.x, self.y = xy
def _clip(self, path, patchA, patchB):
"""
Clip the path to the boundary of the patchA and patchB.
The starting point of the path needed to be inside of the
patchA and the end point inside the patch B. The *contains*
methods of each patch object is utilized to test if the point
is inside the path.
"""
if patchA:
def insideA(xy_display):
xy_event = ConnectionStyle._Base.SimpleEvent(xy_display)
return patchA.contains(xy_event)[0]
try:
left, right = split_path_inout(path, insideA)
except ValueError:
right = path
path = right
if patchB:
def insideB(xy_display):
xy_event = ConnectionStyle._Base.SimpleEvent(xy_display)
return patchB.contains(xy_event)[0]
try:
left, right = split_path_inout(path, insideB)
except ValueError:
left = path
path = left
return path
def _shrink(self, path, shrinkA, shrinkB):
"""
Shrink the path by fixed size (in points) with shrinkA and shrinkB.
"""
if shrinkA:
insideA = inside_circle(*path.vertices[0], shrinkA)
try:
left, path = split_path_inout(path, insideA)
except ValueError:
pass
if shrinkB:
insideB = inside_circle(*path.vertices[-1], shrinkB)
try:
path, right = split_path_inout(path, insideB)
except ValueError:
pass
return path
def __call__(self, posA, posB,
shrinkA=2., shrinkB=2., patchA=None, patchB=None):
"""
Calls the *connect* method to create a path between *posA*
and *posB*. The path is clipped and shrunken.
"""
path = self.connect(posA, posB)
clipped_path = self._clip(path, patchA, patchB)
shrunk_path = self._shrink(clipped_path, shrinkA, shrinkB)
return shrunk_path
@_register_style(_style_list)
class Arc3(_Base):
"""
Creates a simple quadratic Bezier 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.):
"""
*rad*
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 Bezier curve between two
points. The middle control points 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):
"""
*angleA*
starting angle of the path
*angleB*
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 Bezier 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.):
"""
*angleA*
starting angle of the path
*angleB*
ending angle of the path
*rad*
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 Bezier 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.):
"""
*angleA* :
starting angle of the path
*angleB* :
ending angle of the path
*armA* :
length of the starting arm
*armB* :
length of the ending arm
*rad* :
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)
if __doc__:
__doc__ = inspect.cleandoc(__doc__) % {
"AvailableConnectorstyles": _pprint_styles(_style_list)}
def _point_along_a_line(x0, y0, x1, y1, d):
"""
find a point along a 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
class ArrowStyle(_Style):
"""
:class:`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 :class:`FancyArrowPatch`.
A 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
%(AvailableArrowstyles)s
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 :class:`Path` instance and a boolean
value. *path* is a :class:`Path` instance along which the arrow
will be drawn. *mutation_size* and *aspect_ratio* have the same
meaning as in :class:`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.
"""
_style_list = {}
class _Base(object):
"""
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 class only works with a simple quadratic Bezier
curve (created with Arc3Connection or Angle3Connector). This static
method is to check if the provided path is a simple quadratic
Bezier 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 a
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.
"""
path = make_path_regular(path)
if aspect_ratio is not None:
# Squeeze the given height by the aspect_ratio
vertices, codes = path.vertices[:], path.codes[:]
# Squeeze the height
vertices[:, 1] = vertices[:, 1] / aspect_ratio
path_shrunk = Path(vertices, codes)
# call transmute method with squeezed height.
path_mutated, fillable = self.transmute(path_shrunk,
linewidth,
mutation_size)
if np.iterable(fillable):
path_list = []
for p in zip(path_mutated):
v, c = p.vertices, p.codes
# Restore the height
v[:, 1] = v[:, 1] * aspect_ratio
path_list.append(Path(v, c))
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 simply concatenation of the original path + at
most two paths representing the arrow head at the begin point and the
at the end point. The arrow heads can be either open or closed.
"""
def __init__(self, beginarrow=None, endarrow=None,
fillbegin=False, fillend=False,
head_length=.2, head_width=.1):
"""
The arrows are drawn if *beginarrow* and/or *endarrow* are
true. *head_length* and *head_width* determines the size
of the arrow relative to the *mutation scale*. The
arrowhead at the begin (or end) is closed if fillbegin (or
fillend) is True.
"""
self.beginarrow, self.endarrow = beginarrow, endarrow
self.head_length, self.head_width = head_length, head_width
self.fillbegin, self.fillend = fillbegin, fillend
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 transmute(self, path, mutation_size, linewidth):
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
# 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 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 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.
_path = [Path(np.concatenate([[(x0 + ddxA, y0 + ddyA)],
path.vertices[1:-1],
[(x3 + ddxB, y3 + ddyB)]]),
path.codes)]
_fillable = [False]
if has_begin_arrow:
if self.fillbegin:
p = np.concatenate([verticesA, [verticesA[0],
verticesA[0]], ])
c = np.concatenate([codesA, [Path.LINETO, Path.CLOSEPOLY]])
_path.append(Path(p, c))
_fillable.append(True)
else:
_path.append(Path(verticesA, codesA))
_fillable.append(False)
if has_end_arrow:
if self.fillend:
_fillable.append(True)
p = np.concatenate([verticesB, [verticesB[0],
verticesB[0]], ])
c = np.concatenate([codesB, [Path.LINETO, Path.CLOSEPOLY]])
_path.append(Path(p, c))
else:
_fillable.append(False)
_path.append(Path(verticesB, codesB))
return _path, _fillable
@_register_style(_style_list, name="-")
class Curve(_Curve):
"""
A simple curve without any arrow head.
"""
def __init__(self):
super().__init__(beginarrow=False, endarrow=False)
@_register_style(_style_list, name="<-")
class CurveA(_Curve):
"""
An arrow with a head at its begin point.
"""
def __init__(self, head_length=.4, head_width=.2):
"""
Parameters
----------
head_length : float, optional, default : 0.4
Length of the arrow head
head_width : float, optional, default : 0.2
Width of the arrow head
"""
super().__init__(beginarrow=True, endarrow=False,
head_length=head_length, head_width=head_width)
@_register_style(_style_list, name="->")
class CurveB(_Curve):
"""
An arrow with a head at its end point.
"""
def __init__(self, head_length=.4, head_width=.2):
"""
Parameters
----------
head_length : float, optional, default : 0.4
Length of the arrow head
head_width : float, optional, default : 0.2
Width of the arrow head
"""
super().__init__(beginarrow=False, endarrow=True,
head_length=head_length, head_width=head_width)
@_register_style(_style_list, name="<->")
class CurveAB(_Curve):
"""
An arrow with heads both at the begin and the end point.
"""
def __init__(self, head_length=.4, head_width=.2):
"""
Parameters
----------
head_length : float, optional, default : 0.4
Length of the arrow head
head_width : float, optional, default : 0.2
Width of the arrow head
"""
super().__init__(beginarrow=True, endarrow=True,
head_length=head_length, head_width=head_width)
@_register_style(_style_list, name="<|-")
class CurveFilledA(_Curve):
"""
An arrow with filled triangle head at the begin.
"""
def __init__(self, head_length=.4, head_width=.2):
"""
Parameters
----------
head_length : float, optional, default : 0.4
Length of the arrow head
head_width : float, optional, default : 0.2
Width of the arrow head
"""
super().__init__(beginarrow=True, endarrow=False,
fillbegin=True, fillend=False,
head_length=head_length, head_width=head_width)
@_register_style(_style_list, name="-|>")
class CurveFilledB(_Curve):
"""
An arrow with filled triangle head at the end.
"""
def __init__(self, head_length=.4, head_width=.2):
"""
Parameters
----------
head_length : float, optional, default : 0.4
Length of the arrow head
head_width : float, optional, default : 0.2
Width of the arrow head
"""
super().__init__(beginarrow=False, endarrow=True,
fillbegin=False, fillend=True,
head_length=head_length, head_width=head_width)
@_register_style(_style_list, name="<|-|>")
class CurveFilledAB(_Curve):
"""
An arrow with filled triangle heads at both ends.
"""
def __init__(self, head_length=.4, head_width=.2):
"""
Parameters
----------
head_length : float, optional, default : 0.4
Length of the arrow head
head_width : float, optional, default : 0.2
Width of the arrow head
"""
super().__init__(beginarrow=True, endarrow=True,
fillbegin=True, fillend=True,
head_length=head_length, head_width=head_width)
class _Bracket(_Base):
def __init__(self, bracketA=None, bracketB=None,
widthA=1., widthB=1.,
lengthA=0.2, lengthB=0.2,
angleA=None, angleB=None,
scaleA=None, scaleB=None):
self.bracketA, self.bracketB = bracketA, bracketB
self.widthA, self.widthB = widthA, widthB
self.lengthA, self.lengthB = lengthA, lengthB
self.angleA, self.angleB = angleA, angleB
self.scaleA, self.scaleB = scaleA, scaleB
def _get_bracket(self, x0, y0,
cos_t, sin_t, width, length):
# 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]
return vertices_arrow, codes_arrow
def transmute(self, path, mutation_size, linewidth):
if self.scaleA is None:
scaleA = mutation_size
else:
scaleA = self.scaleA
if self.scaleB is None:
scaleB = mutation_size
else:
scaleB = self.scaleB
vertices_list, codes_list = [], []
if self.bracketA:
x0, y0 = path.vertices[0]
x1, y1 = path.vertices[1]
cos_t, sin_t = get_cos_sin(x1, y1, x0, y0)
verticesA, codesA = self._get_bracket(x0, y0, cos_t, sin_t,
self.widthA * scaleA,
self.lengthA * scaleA)
vertices_list.append(verticesA)
codes_list.append(codesA)
vertices_list.append(path.vertices)
codes_list.append(path.codes)
if self.bracketB:
x0, y0 = path.vertices[-1]
x1, y1 = path.vertices[-2]
cos_t, sin_t = get_cos_sin(x1, y1, x0, y0)
verticesB, codesB = self._get_bracket(x0, y0, cos_t, sin_t,
self.widthB * scaleB,
self.lengthB * scaleB)
vertices_list.append(verticesB)
codes_list.append(codesB)
vertices = np.concatenate(vertices_list)
codes = np.concatenate(codes_list)
p = Path(vertices, codes)
return p, False
@_register_style(_style_list, name="]-[")
class BracketAB(_Bracket):
"""
An arrow with a bracket(]) at both ends.
"""
def __init__(self,
widthA=1., lengthA=0.2, angleA=None,
widthB=1., lengthB=0.2, angleB=None):
"""
Parameters
----------
widthA : float, optional, default : 1.0
Width of the bracket
lengthA : float, optional, default : 0.2
Length of the bracket
angleA : float, optional, default : None
Angle between the bracket and the line
widthB : float, optional, default : 1.0
Width of the bracket
lengthB : float, optional, default : 0.2
Length of the bracket
angleB : float, optional, default : None
Angle between the bracket and the line
"""
super().__init__(True, True,
widthA=widthA, lengthA=lengthA, angleA=angleA,
widthB=widthB, lengthB=lengthB, angleB=angleB)
@_register_style(_style_list, name="]-")
class BracketA(_Bracket):
"""
An arrow with a bracket(]) at its end.
"""
def __init__(self, widthA=1., lengthA=0.2, angleA=None):
"""
Parameters
----------
widthA : float, optional, default : 1.0
Width of the bracket
lengthA : float, optional, default : 0.2
Length of the bracket
angleA : float, optional, default : None
Angle between the bracket and the line
"""
super().__init__(True, None,
widthA=widthA, lengthA=lengthA, angleA=angleA)
@_register_style(_style_list, name="-[")
class BracketB(_Bracket):
"""
An arrow with a bracket([) at its end.
"""
def __init__(self, widthB=1., lengthB=0.2, angleB=None):
"""
Parameters
----------
widthB : float, optional, default : 1.0
Width of the bracket
lengthB : float, optional, default : 0.2
Length of the bracket
angleB : float, optional, default : None
Angle between the bracket and the line
"""
super().__init__(None, True,
widthB=widthB, lengthB=lengthB, angleB=angleB)
@_register_style(_style_list, name="|-|")
class BarAB(_Bracket):
"""
An arrow with a bar(|) at both ends.
"""
def __init__(self,
widthA=1., angleA=None,
widthB=1., angleB=None):
"""
Parameters
----------
widthA : float, optional, default : 1.0
Width of the bracket
angleA : float, optional, default : None
Angle between the bracket and the line
widthB : float, optional, default : 1.0
Width of the bracket
angleB : float, optional, default : None
Angle between the bracket and the line
"""
super().__init__(True, True,
widthA=widthA, lengthA=0, angleA=angleA,
widthB=widthB, lengthB=0, angleB=angleB)
@_register_style(_style_list)
class Simple(_Base):
"""
A simple arrow. Only works with a quadratic Bezier curve.
"""
def __init__(self, head_length=.5, head_width=.5, tail_width=.2):
"""
Parameters
----------
head_length : float, optional, default : 0.5
Length of the arrow head
head_width : float, optional, default : 0.5
Width of the arrow head
tail_width : float, optional, default : 0.2
Width of the arrow tail
"""
self.head_length, self.head_width, self.tail_width = \
head_length, head_width, tail_width
super().__init__()
def transmute(self, path, mutation_size, linewidth):
x0, y0, x1, y1, x2, y2 = self.ensure_quadratic_bezier(path)
# divide the path into a head and a tail
head_length = self.head_length * mutation_size
in_f = inside_circle(x2, y2, head_length)
arrow_path = [(x0, y0), (x1, y1), (x2, y2)]
try:
arrow_out, arrow_in = \
split_bezier_intersecting_with_closedpath(
arrow_path, in_f, tolerance=0.01)
except NonIntersectingPathException:
# if this happens, make a straight line of the head_length
# long.
x0, y0 = _point_along_a_line(x2, y2, x1, y1, head_length)
x1n, y1n = 0.5 * (x0 + x2), 0.5 * (y0 + y2)
arrow_in = [(x0, y0), (x1n, y1n), (x2, y2)]
arrow_out = None
# head
head_width = self.head_width * mutation_size
head_left, head_right = make_wedged_bezier2(arrow_in,
head_width / 2., wm=.5)
# tail
if arrow_out is not None:
tail_width = self.tail_width * mutation_size
tail_left, tail_right = get_parallels(arrow_out,
tail_width / 2.)
patch_path = [(Path.MOVETO, tail_right[0]),
(Path.CURVE3, tail_right[1]),
(Path.CURVE3, tail_right[2]),
(Path.LINETO, head_right[0]),
(Path.CURVE3, head_right[1]),
(Path.CURVE3, head_right[2]),
(Path.CURVE3, head_left[1]),
(Path.CURVE3, head_left[0]),
(Path.LINETO, tail_left[2]),
(Path.CURVE3, tail_left[1]),
(Path.CURVE3, tail_left[0]),
(Path.LINETO, tail_right[0]),
(Path.CLOSEPOLY, tail_right[0]),
]
else:
patch_path = [(Path.MOVETO, head_right[0]),
(Path.CURVE3, head_right[1]),
(Path.CURVE3, head_right[2]),
(Path.CURVE3, head_left[1]),
(Path.CURVE3, head_left[0]),
(Path.CLOSEPOLY, head_left[0]),
]
path = Path([p for c, p in patch_path], [c for c, p in patch_path])
return path, True
@_register_style(_style_list)
class Fancy(_Base):
"""
A fancy arrow. Only works with a quadratic Bezier curve.
"""
def __init__(self, head_length=.4, head_width=.4, tail_width=.4):
"""
Parameters
----------
head_length : float, optional, default : 0.4
Length of the arrow head
head_width : float, optional, default : 0.4
Width of the arrow head
tail_width : float, optional, default : 0.4
Width of the arrow tail
"""
self.head_length, self.head_width, self.tail_width = \
head_length, head_width, tail_width
super().__init__()
def transmute(self, path, mutation_size, linewidth):
x0, y0, x1, y1, x2, y2 = self.ensure_quadratic_bezier(path)
# divide the path into a head and a tail
head_length = self.head_length * mutation_size
arrow_path = [(x0, y0), (x1, y1), (x2, y2)]
# path for head
in_f = inside_circle(x2, y2, head_length)
try:
path_out, path_in = split_bezier_intersecting_with_closedpath(
arrow_path, in_f, tolerance=0.01)
except NonIntersectingPathException:
# if this happens, make a straight line of the head_length
# long.
x0, y0 = _point_along_a_line(x2, y2, x1, y1, head_length)
x1n, y1n = 0.5 * (x0 + x2), 0.5 * (y0 + y2)
arrow_path = [(x0, y0), (x1n, y1n), (x2, y2)]
path_head = arrow_path
else:
path_head = path_in
# path for head
in_f = inside_circle(x2, y2, head_length * .8)
path_out, path_in = split_bezier_intersecting_with_closedpath(
arrow_path, in_f, tolerance=0.01)
path_tail = path_out
# head
head_width = self.head_width * mutation_size
head_l, head_r = make_wedged_bezier2(path_head,
head_width / 2.,
wm=.6)
# tail
tail_width = self.tail_width * mutation_size
tail_left, tail_right = make_wedged_bezier2(path_tail,
tail_width * .5,
w1=1., wm=0.6, w2=0.3)
# path for head
in_f = inside_circle(x0, y0, tail_width * .3)
path_in, path_out = split_bezier_intersecting_with_closedpath(
arrow_path, in_f, tolerance=0.01)
tail_start = path_in[-1]
head_right, head_left = head_r, head_l
patch_path = [(Path.MOVETO, tail_start),
(Path.LINETO, tail_right[0]),
(Path.CURVE3, tail_right[1]),
(Path.CURVE3, tail_right[2]),
(Path.LINETO, head_right[0]),
(Path.CURVE3, head_right[1]),
(Path.CURVE3, head_right[2]),
(Path.CURVE3, head_left[1]),
(Path.CURVE3, head_left[0]),
(Path.LINETO, tail_left[2]),
(Path.CURVE3, tail_left[1]),
(Path.CURVE3, tail_left[0]),
(Path.LINETO, tail_start),
(Path.CLOSEPOLY, tail_start),
]
path = Path([p for c, p in patch_path], [c for c, p in patch_path])
return path, True
@_register_style(_style_list)
class Wedge(_Base):
"""
Wedge(?) shape. Only works with a quadratic Bezier curve. The
begin point has a width of the tail_width and the end point has a
width of 0. At the middle, the width is shrink_factor*tail_width.
"""
def __init__(self, tail_width=.3, shrink_factor=0.5):
"""
Parameters
----------
tail_width : float, optional, default : 0.3
Width of the tail
shrink_factor : float, optional, default : 0.5
Fraction of the arrow width at the middle point
"""
self.tail_width = tail_width
self.shrink_factor = shrink_factor
super().__init__()
def transmute(self, path, mutation_size, linewidth):
x0, y0, x1, y1, x2, y2 = self.ensure_quadratic_bezier(path)
arrow_path = [(x0, y0), (x1, y1), (x2, y2)]
b_plus, b_minus = make_wedged_bezier2(
arrow_path,
self.tail_width * mutation_size / 2.,
wm=self.shrink_factor)
patch_path = [(Path.MOVETO, b_plus[0]),
(Path.CURVE3, b_plus[1]),
(Path.CURVE3, b_plus[2]),
(Path.LINETO, b_minus[2]),
(Path.CURVE3, b_minus[1]),
(Path.CURVE3, b_minus[0]),
(Path.CLOSEPOLY, b_minus[0]),
]
path = Path([p for c, p in patch_path], [c for c, p in patch_path])
return path, True
if __doc__:
__doc__ = inspect.cleandoc(__doc__) % {
"AvailableArrowstyles": _pprint_styles(_style_list)}
docstring.interpd.update(
AvailableArrowstyles=_pprint_styles(ArrowStyle._style_list),
AvailableConnectorstyles=_pprint_styles(ConnectionStyle._style_list),
)
class FancyArrowPatch(Patch):
"""
A fancy arrow patch. It draws an arrow using the :class:`ArrowStyle`.
The head and tail positions are fixed at the specified start and end points
of the arrow, but the size and shape (in display coordinates) of the arrow
does not change when the axis is moved or zoomed.
"""
_edge_default = True
def __str__(self):
if self._posA_posB is not None:
(x1, y1), (x2, y2) = self._posA_posB
return self.__class__.__name__ \
+ "((%g, %g)->(%g, %g))" % (x1, y1, x2, y2)
else:
return self.__class__.__name__ \
+ "(%s)" % (str(self._path_original),)
@docstring.dedent_interpd
def __init__(self, posA=None, posB=None,
path=None,
arrowstyle="simple",
arrow_transmuter=None,
connectionstyle="arc3",
connector=None,
patchA=None,
patchB=None,
shrinkA=2,
shrinkB=2,
mutation_scale=1,
mutation_aspect=None,
dpi_cor=1,
**kwargs):
"""
There are two ways for defining an arrow:
- If *posA* and *posB* are given, a path connecting two points is
created according to *connectionstyle*. The path will be
clipped with *patchA* and *patchB* and further shrunken by
*shrinkA* and *shrinkB*. An arrow is drawn along this
resulting path using the *arrowstyle* parameter.
- Alternatively if *path* is provided, an arrow is drawn along this
path and *patchA*, *patchB*, *shrinkA*, and *shrinkB* are ignored.
Parameters
----------
posA, posB : (float, float), optional (default: None)
(x,y) coordinates of arrow tail and arrow head respectively.
path : `~matplotlib.path.Path`, optional (default: None)
If provided, an arrow is drawn along this path and *patchA*,
*patchB*, *shrinkA*, and *shrinkB* are ignored.
arrowstyle : str or `.ArrowStyle`, optional (default: 'simple')
Describes how the fancy arrow will be
drawn. It can be string of the available arrowstyle names,
with optional comma-separated attributes, or an
:class:`ArrowStyle` instance. The optional attributes are meant to
be scaled with the *mutation_scale*. The following arrow styles are
available:
%(AvailableArrowstyles)s
arrow_transmuter
Ignored.
connectionstyle : str or `.ConnectionStyle` or None, optional \
(default: 'arc3')
Describes how *posA* and *posB* are connected. It can be an
instance of the :class:`ConnectionStyle` class or a string of the
connectionstyle name, with optional comma-separated attributes. The
following connection styles are available:
%(AvailableConnectorstyles)s
connector
Ignored.
patchA, patchB : `.Patch`, optional (default: None)
Head and tail patch respectively. :class:`matplotlib.patch.Patch`
instance.
shrinkA, shrinkB : float, optional (default: 2)
Shrinking factor of the tail and head of the arrow respectively.
mutation_scale : float, optional (default: 1)
Value with which attributes of *arrowstyle* (e.g., *head_length*)
will be scaled.
mutation_aspect : None or float, optional (default: None)
The height of the rectangle will be squeezed by this value before
the mutation and the mutated box will be stretched by the inverse
of it.
dpi_cor : float, optional (default: 1)
dpi_cor is currently used for linewidth-related things and shrink
factor. Mutation scale is affected by this.
Other Parameters
----------------
**kwargs : `.Patch` properties, optional
Here is a list of available `.Patch` properties:
%(Patch)s
In contrast to other patches, the default ``capstyle`` and
``joinstyle`` for `FancyArrowPatch` are set to ``"round"``.
"""
if arrow_transmuter is not None:
cbook.warn_deprecated(
3.0,
message=('The "arrow_transmuter" keyword argument is not used,'
' and will be removed in Matplotlib 3.1'),
name='arrow_transmuter',
obj_type='keyword argument')
if connector is not None:
cbook.warn_deprecated(
3.0,
message=('The "connector" keyword argument is not used,'
' and will be removed in Matplotlib 3.1'),
name='connector',
obj_type='keyword argument')
# Traditionally, the cap- and joinstyle for FancyArrowPatch are round
kwargs.setdefault("joinstyle", "round")
kwargs.setdefault("capstyle", "round")
Patch.__init__(self, **kwargs)
if posA is not None and posB is not None and path is None:
self._posA_posB = [posA, posB]
if connectionstyle is None:
connectionstyle = "arc3"
self.set_connectionstyle(connectionstyle)
elif posA is None and posB is None and path is not None:
self._posA_posB = None
else:
raise ValueError("either posA and posB, or path need to provided")
self.patchA = patchA
self.patchB = patchB
self.shrinkA = shrinkA
self.shrinkB = shrinkB
self._path_original = path
self.set_arrowstyle(arrowstyle)
self._mutation_scale = mutation_scale
self._mutation_aspect = mutation_aspect
self.set_dpi_cor(dpi_cor)
def set_dpi_cor(self, dpi_cor):
"""
dpi_cor is currently used for linewidth-related things and
shrink factor. Mutation scale is affected by this.
Parameters
----------
dpi_cor : scalar
"""
self._dpi_cor = dpi_cor
self.stale = True
def get_dpi_cor(self):
"""
dpi_cor is currently used for linewidth-related things and
shrink factor. Mutation scale is affected by this.
Returns
-------
dpi_cor : scalar
"""
return self._dpi_cor
def set_positions(self, posA, posB):
"""
Set the begin and end positions of the connecting path.
Parameters
----------
posA, posB : None, tuple
(x,y) coordinates of arrow tail and arrow head respectively. If
`None` use current value.
"""
if posA is not None:
self._posA_posB[0] = posA
if posB is not None:
self._posA_posB[1] = posB
self.stale = True
def set_patchA(self, patchA):
"""
Set the tail patch.
Parameters
----------
patchA : Patch
:class:`matplotlib.patch.Patch` instance.
"""
self.patchA = patchA
self.stale = True
def set_patchB(self, patchB):
"""
Set the head patch.
Parameters
----------
patchB : Patch
:class:`matplotlib.patch.Patch` instance.
"""
self.patchB = patchB
self.stale = True
def set_connectionstyle(self, connectionstyle, **kw):
"""
Set the connection style. Old attributes are forgotten.
Parameters
----------
connectionstyle : None, ConnectionStyle instance, or string
Can be a string with connectionstyle name with
optional comma-separated attributes, e.g.::
set_connectionstyle("arc,angleA=0,armA=30,rad=10")
Alternatively, the attributes can be provided as keywords, e.g.::
set_connectionstyle("arc", angleA=0,armA=30,rad=10)
Without any arguments (or with ``connectionstyle=None``), return
available styles as a list of strings.
"""
if connectionstyle is None:
return ConnectionStyle.pprint_styles()
if (isinstance(connectionstyle, ConnectionStyle._Base) or
callable(connectionstyle)):
self._connector = connectionstyle
else:
self._connector = ConnectionStyle(connectionstyle, **kw)
self.stale = True
def get_connectionstyle(self):
"""
Return the :class:`ConnectionStyle` instance.
"""
return self._connector
def set_arrowstyle(self, arrowstyle=None, **kw):
"""
Set the arrow style. Old attributes are forgotten. Without arguments
(or with ``arrowstyle=None``) returns available box styles as a list of
strings.
Parameters
----------
arrowstyle : None, ArrowStyle, str, optional (default: None)
Can be a string with arrowstyle name with optional comma-separated
attributes, e.g.::
set_arrowstyle("Fancy,head_length=0.2")
Alternatively attributes can be provided as keywords, e.g.::
set_arrowstyle("fancy", head_length=0.2)
"""
if arrowstyle is None:
return ArrowStyle.pprint_styles()
if isinstance(arrowstyle, ArrowStyle._Base):
self._arrow_transmuter = arrowstyle
else:
self._arrow_transmuter = ArrowStyle(arrowstyle, **kw)
self.stale = True
def get_arrowstyle(self):
"""
Return the arrowstyle object.
"""
return self._arrow_transmuter
def set_mutation_scale(self, scale):
"""
Set the mutation scale.
Parameters
----------
scale : scalar
"""
self._mutation_scale = scale
self.stale = True
def get_mutation_scale(self):
"""
Return the mutation scale.
Returns
-------
scale : scalar
"""
return self._mutation_scale
def set_mutation_aspect(self, aspect):
"""
Set the aspect ratio of the bbox mutation.
Parameters
----------
aspect : scalar
"""
self._mutation_aspect = aspect
self.stale = True
def get_mutation_aspect(self):
"""
Return the aspect ratio of the bbox mutation.
"""
return self._mutation_aspect
def get_path(self):
"""
Return the path of the arrow in the data coordinates. Use
get_path_in_displaycoord() method to retrieve the arrow path
in display coordinates.
"""
_path, fillable = self.get_path_in_displaycoord()
if np.iterable(fillable):
_path = concatenate_paths(_path)
return self.get_transform().inverted().transform_path(_path)
def get_path_in_displaycoord(self):
"""
Return the mutated path of the arrow in display coordinates.
"""
dpi_cor = self.get_dpi_cor()
if self._posA_posB is not None:
posA = self._convert_xy_units(self._posA_posB[0])
posB = self._convert_xy_units(self._posA_posB[1])
posA = self.get_transform().transform_point(posA)
posB = self.get_transform().transform_point(posB)
_path = self.get_connectionstyle()(posA, posB,
patchA=self.patchA,
patchB=self.patchB,
shrinkA=self.shrinkA * dpi_cor,
shrinkB=self.shrinkB * dpi_cor
)
else:
_path = self.get_transform().transform_path(self._path_original)
_path, fillable = self.get_arrowstyle()(
_path,
self.get_mutation_scale() * dpi_cor,
self.get_linewidth() * dpi_cor,
self.get_mutation_aspect())
# if not fillable:
# self._fill = False
return _path, fillable
def draw(self, renderer):
if not self.get_visible():
return
with self._bind_draw_path_function(renderer) as draw_path:
# FIXME : dpi_cor is for the dpi-dependency of the linewidth. There
# could be room for improvement.
self.set_dpi_cor(renderer.points_to_pixels(1.))
path, fillable = self.get_path_in_displaycoord()
if not np.iterable(fillable):
path = [path]
fillable = [fillable]
affine = transforms.IdentityTransform()
for p, f in zip(path, fillable):
draw_path(
p, affine,
self._facecolor if f and self._facecolor[3] else None)
class ConnectionPatch(FancyArrowPatch):
"""
A :class:`~matplotlib.patches.ConnectionPatch` class is to make
connecting lines between two points (possibly in different axes).
"""
def __str__(self):
return "ConnectionPatch((%g, %g), (%g, %g))" % \
(self.xy1[0], self.xy1[1], self.xy2[0], self.xy2[1])
@docstring.dedent_interpd
def __init__(self, xyA, xyB, coordsA, coordsB=None,
axesA=None, axesB=None,
arrowstyle="-",
arrow_transmuter=None,
connectionstyle="arc3",
connector=None,
patchA=None,
patchB=None,
shrinkA=0.,
shrinkB=0.,
mutation_scale=10.,
mutation_aspect=None,
clip_on=False,
dpi_cor=1.,
**kwargs):
"""
Connect point *xyA* in *coordsA* with point *xyB* in *coordsB*
Valid keys are
=============== ======================================================
Key Description
=============== ======================================================
arrowstyle the arrow style
connectionstyle the connection style
relpos default is (0.5, 0.5)
patchA default is bounding box of the text
patchB default is None
shrinkA default is 2 points
shrinkB default is 2 points
mutation_scale default is text size (in points)
mutation_aspect default is 1.
? any key for :class:`matplotlib.patches.PathPatch`
=============== ======================================================
*coordsA* and *coordsB* are strings that indicate the
coordinates of *xyA* and *xyB*.
================= ===================================================
Property Description
================= ===================================================
'figure points' points from the lower left corner of the figure
'figure pixels' pixels from the lower left corner of the figure
'figure fraction' 0,0 is lower left of figure and 1,1 is upper, right
'axes points' points from lower left corner of axes
'axes pixels' pixels from lower left corner of axes
'axes fraction' 0,1 is lower left of axes and 1,1 is upper right
'data' use the coordinate system of the object being
annotated (default)
'offset points' Specify an offset (in points) from the *xy* value
'polar' you can specify *theta*, *r* for the annotation,
even in cartesian plots. Note that if you
are using a polar axes, you do not need
to specify polar for the coordinate
system since that is the native "data" coordinate
system.
================= ===================================================
Alternatively they can be set to any valid
`~matplotlib.transforms.Transform`.
"""
if coordsB is None:
coordsB = coordsA
# we'll draw ourself after the artist we annotate by default
self.xy1 = xyA
self.xy2 = xyB
self.coords1 = coordsA
self.coords2 = coordsB
self.axesA = axesA
self.axesB = axesB
FancyArrowPatch.__init__(self,
posA=(0, 0), posB=(1, 1),
arrowstyle=arrowstyle,
arrow_transmuter=arrow_transmuter,
connectionstyle=connectionstyle,
connector=connector,
patchA=patchA,
patchB=patchB,
shrinkA=shrinkA,
shrinkB=shrinkB,
mutation_scale=mutation_scale,
mutation_aspect=mutation_aspect,
clip_on=clip_on,
dpi_cor=dpi_cor,
**kwargs)
# if True, draw annotation only if self.xy is inside the axes
self._annotation_clip = None
def _get_xy(self, x, y, s, axes=None):
"""
calculate the pixel position of given point
"""
if axes is None:
axes = self.axes
if s == 'data':
trans = axes.transData
x = float(self.convert_xunits(x))
y = float(self.convert_yunits(y))
return trans.transform_point((x, y))
elif s == 'offset points':
# convert the data point
dx, dy = self.xy
# prevent recursion
if self.xycoords == 'offset points':
return self._get_xy(dx, dy, 'data')
dx, dy = self._get_xy(dx, dy, self.xycoords)
# convert the offset
dpi = self.figure.get_dpi()
x *= dpi / 72.
y *= dpi / 72.
# add the offset to the data point
x += dx
y += dy
return x, y
elif s == 'polar':
theta, r = x, y
x = r * np.cos(theta)
y = r * np.sin(theta)
trans = axes.transData
return trans.transform_point((x, y))
elif s == 'figure points':
# points from the lower left corner of the figure
dpi = self.figure.dpi
l, b, w, h = self.figure.bbox.bounds
r = l + w
t = b + h
x *= dpi / 72.
y *= dpi / 72.
if x < 0:
x = r + x
if y < 0:
y = t + y
return x, y
elif s == 'figure pixels':
# pixels from the lower left corner of the figure
l, b, w, h = self.figure.bbox.bounds
r = l + w
t = b + h
if x < 0:
x = r + x
if y < 0:
y = t + y
return x, y
elif s == 'figure fraction':
# (0,0) is lower left, (1,1) is upper right of figure
trans = self.figure.transFigure
return trans.transform_point((x, y))
elif s == 'axes points':
# points from the lower left corner of the axes
dpi = self.figure.dpi
l, b, w, h = axes.bbox.bounds
r = l + w
t = b + h
if x < 0:
x = r + x * dpi / 72.
else:
x = l + x * dpi / 72.
if y < 0:
y = t + y * dpi / 72.
else:
y = b + y * dpi / 72.
return x, y
elif s == 'axes pixels':
#pixels from the lower left corner of the axes
l, b, w, h = axes.bbox.bounds
r = l + w
t = b + h
if x < 0:
x = r + x
else:
x = l + x
if y < 0:
y = t + y
else:
y = b + y
return x, y
elif s == 'axes fraction':
#(0,0) is lower left, (1,1) is upper right of axes
trans = axes.transAxes
return trans.transform_point((x, y))
elif isinstance(s, transforms.Transform):
return s.transform_point((x, y))
else:
raise ValueError("{} is not a valid coordinate "
"transformation.".format(s))
def set_annotation_clip(self, b):
"""
set *annotation_clip* attribute.
* True: the annotation will only be drawn when self.xy is inside the
axes.
* False: the annotation will always be drawn regardless of its
position.
* None: the self.xy will be checked only if *xycoords* is "data"
"""
self._annotation_clip = b
self.stale = True
def get_annotation_clip(self):
"""
Return *annotation_clip* attribute.
See :meth:`set_annotation_clip` for the meaning of return values.
"""
return self._annotation_clip
def get_path_in_displaycoord(self):
"""
Return the mutated path of the arrow in the display coord
"""
dpi_cor = self.get_dpi_cor()
x, y = self.xy1
posA = self._get_xy(x, y, self.coords1, self.axesA)
x, y = self.xy2
posB = self._get_xy(x, y, 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"):
x, y = self.xy1
xy_pixel = self._get_xy(x, y, self.coords1, self.axesA)
if not self.axes.contains_point(xy_pixel):
return False
if b or (b is None and self.coords2 == "data"):
x, y = self.xy2
xy_pixel = self._get_xy(x, y, 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 renderer is not None:
self._renderer = renderer
if not self.get_visible() or not self._check_xy(renderer):
return
FancyArrowPatch.draw(self, renderer)
|
6dbcc8c1a4f1b9307f149d162c1e5619f703774393c4f80d6b7db86c46f67e7c
|
"""
This module contains all the 2D line class which can draw with a
variety of line styles, markers and colors.
"""
# TODO: expose cap and join style attrs
from numbers import Integral, Number, Real
import logging
import numpy as np
from . import artist, cbook, colors as mcolors, docstring, rcParams
from .artist import Artist, allow_rasterization
from .cbook import (
_to_unmasked_float_array, ls_mapper, ls_mapper_r, STEP_LOOKUP_MAP)
from .markers import MarkerStyle
from .path import Path
from .transforms import Bbox, TransformedPath
# Imported here for backward compatibility, even though they don't
# really belong.
from . import _path
from .markers import (
CARETLEFT, CARETRIGHT, CARETUP, CARETDOWN,
CARETLEFTBASE, CARETRIGHTBASE, CARETUPBASE, CARETDOWNBASE,
TICKLEFT, TICKRIGHT, TICKUP, TICKDOWN)
_log = logging.getLogger(__name__)
def _get_dash_pattern(style):
"""Convert linestyle -> dash pattern
"""
# go from short hand -> full strings
if isinstance(style, str):
style = ls_mapper.get(style, style)
# un-dashed styles
if style in ['solid', 'None']:
offset, dashes = None, None
# dashed styles
elif style in ['dashed', 'dashdot', 'dotted']:
offset = 0
dashes = tuple(rcParams['lines.{}_pattern'.format(style)])
#
elif isinstance(style, tuple):
offset, dashes = style
else:
raise ValueError('Unrecognized linestyle: %s' % str(style))
# normalize offset to be positive and shorter than the dash cycle
if dashes is not None and offset is not None:
dsum = sum(dashes)
if dsum:
offset %= dsum
return offset, dashes
def _scale_dashes(offset, dashes, lw):
if not rcParams['lines.scale_dashes']:
return offset, dashes
scaled_offset = scaled_dashes = None
if offset is not None:
scaled_offset = offset * lw
if dashes is not None:
scaled_dashes = [x * lw if x is not None else None
for x in dashes]
return scaled_offset, scaled_dashes
def segment_hits(cx, cy, x, y, radius):
"""
Return the indices of the segments in the polyline with coordinates (*cx*,
*cy*) that are within a distance *radius* of the point (*x*, *y*).
"""
# Process single points specially
if len(x) <= 1:
res, = np.nonzero((cx - x) ** 2 + (cy - y) ** 2 <= radius ** 2)
return res
# We need to lop the last element off a lot.
xr, yr = x[:-1], y[:-1]
# Only look at line segments whose nearest point to C on the line
# lies within the segment.
dx, dy = x[1:] - xr, y[1:] - yr
Lnorm_sq = dx ** 2 + dy ** 2 # Possibly want to eliminate Lnorm==0
u = ((cx - xr) * dx + (cy - yr) * dy) / Lnorm_sq
candidates = (u >= 0) & (u <= 1)
# Note that there is a little area near one side of each point
# which will be near neither segment, and another which will
# be near both, depending on the angle of the lines. The
# following radius test eliminates these ambiguities.
point_hits = (cx - x) ** 2 + (cy - y) ** 2 <= radius ** 2
candidates = candidates & ~(point_hits[:-1] | point_hits[1:])
# For those candidates which remain, determine how far they lie away
# from the line.
px, py = xr + u * dx, yr + u * dy
line_hits = (cx - px) ** 2 + (cy - py) ** 2 <= radius ** 2
line_hits = line_hits & candidates
points, = point_hits.ravel().nonzero()
lines, = line_hits.ravel().nonzero()
return np.concatenate((points, lines))
def _mark_every_path(markevery, tpath, affine, ax_transform):
"""
Helper function that sorts out how to deal the input
`markevery` and returns the points where markers should be drawn.
Takes in the `markevery` value and the line path and returns the
sub-sampled path.
"""
# pull out the two bits of data we want from the path
codes, verts = tpath.codes, tpath.vertices
def _slice_or_none(in_v, slc):
'''
Helper function to cope with `codes` being an
ndarray or `None`
'''
if in_v is None:
return None
return in_v[slc]
# if just an int, assume starting at 0 and make a tuple
if isinstance(markevery, Integral):
markevery = (0, markevery)
# if just a float, assume starting at 0.0 and make a tuple
elif isinstance(markevery, Real):
markevery = (0.0, markevery)
if isinstance(markevery, tuple):
if len(markevery) != 2:
raise ValueError('`markevery` is a tuple but its len is not 2; '
'markevery={}'.format(markevery))
start, step = markevery
# if step is an int, old behavior
if isinstance(step, Integral):
# tuple of 2 int is for backwards compatibility,
if not isinstance(start, Integral):
raise ValueError(
'`markevery` is a tuple with len 2 and second element is '
'an int, but the first element is not an int; markevery={}'
.format(markevery))
# just return, we are done here
return Path(verts[slice(start, None, step)],
_slice_or_none(codes, slice(start, None, step)))
elif isinstance(step, Real):
if not isinstance(start, Real):
raise ValueError(
'`markevery` is a tuple with len 2 and second element is '
'a float, but the first element is not a float or an int; '
'markevery={}'.format(markevery))
# calc cumulative distance along path (in display coords):
disp_coords = affine.transform(tpath.vertices)
delta = np.empty((len(disp_coords), 2))
delta[0, :] = 0
delta[1:, :] = disp_coords[1:, :] - disp_coords[:-1, :]
delta = np.sum(delta**2, axis=1)
delta = np.sqrt(delta)
delta = np.cumsum(delta)
# calc distance between markers along path based on the axes
# bounding box diagonal being a distance of unity:
scale = ax_transform.transform(np.array([[0, 0], [1, 1]]))
scale = np.diff(scale, axis=0)
scale = np.sum(scale**2)
scale = np.sqrt(scale)
marker_delta = np.arange(start * scale, delta[-1], step * scale)
# find closest actual data point that is closest to
# the theoretical distance along the path:
inds = np.abs(delta[np.newaxis, :] - marker_delta[:, np.newaxis])
inds = inds.argmin(axis=1)
inds = np.unique(inds)
# return, we are done here
return Path(verts[inds], _slice_or_none(codes, inds))
else:
raise ValueError(
f"markevery={markevery!r} is a tuple with len 2, but its "
f"second element is not an int or a float")
elif isinstance(markevery, slice):
# mazol tov, it's already a slice, just return
return Path(verts[markevery], _slice_or_none(codes, markevery))
elif np.iterable(markevery):
# fancy indexing
try:
return Path(verts[markevery], _slice_or_none(codes, markevery))
except (ValueError, IndexError):
raise ValueError(
f"markevery={markevery!r} is iterable but not a valid numpy "
f"fancy index")
else:
raise ValueError(f"markevery={markevery!r} is not a recognized value")
@cbook._define_aliases({
"antialiased": ["aa"],
"color": ["c"],
"drawstyle": ["ds"],
"linestyle": ["ls"],
"linewidth": ["lw"],
"markeredgecolor": ["mec"],
"markeredgewidth": ["mew"],
"markerfacecolor": ["mfc"],
"markerfacecoloralt": ["mfcalt"],
"markersize": ["ms"],
})
class Line2D(Artist):
"""
A line - the line can have both a solid linestyle connecting all
the vertices, and a marker at each vertex. Additionally, the
drawing of the solid line is influenced by the drawstyle, e.g., one
can create "stepped" lines in various styles.
"""
lineStyles = _lineStyles = { # hidden names deprecated
'-': '_draw_solid',
'--': '_draw_dashed',
'-.': '_draw_dash_dot',
':': '_draw_dotted',
'None': '_draw_nothing',
' ': '_draw_nothing',
'': '_draw_nothing',
}
_drawStyles_l = {
'default': '_draw_lines',
'steps-mid': '_draw_steps_mid',
'steps-pre': '_draw_steps_pre',
'steps-post': '_draw_steps_post',
}
_drawStyles_s = {
'steps': '_draw_steps_pre',
}
# drawStyles should now be deprecated.
drawStyles = {**_drawStyles_l, **_drawStyles_s}
# Need a list ordered with long names first:
drawStyleKeys = [*_drawStyles_l, *_drawStyles_s]
# Referenced here to maintain API. These are defined in
# MarkerStyle
markers = MarkerStyle.markers
filled_markers = MarkerStyle.filled_markers
fillStyles = MarkerStyle.fillstyles
zorder = 2
validCap = ('butt', 'round', 'projecting')
validJoin = ('miter', 'round', 'bevel')
def __str__(self):
if self._label != "":
return f"Line2D({self._label})"
elif self._x is None:
return "Line2D()"
elif len(self._x) > 3:
return "Line2D((%g,%g),(%g,%g),...,(%g,%g))" % (
self._x[0], self._y[0], self._x[0],
self._y[0], self._x[-1], self._y[-1])
else:
return "Line2D(%s)" % ",".join(
map("({:g},{:g})".format, self._x, self._y))
def __init__(self, xdata, ydata,
linewidth=None, # all Nones default to rc
linestyle=None,
color=None,
marker=None,
markersize=None,
markeredgewidth=None,
markeredgecolor=None,
markerfacecolor=None,
markerfacecoloralt='none',
fillstyle=None,
antialiased=None,
dash_capstyle=None,
solid_capstyle=None,
dash_joinstyle=None,
solid_joinstyle=None,
pickradius=5,
drawstyle=None,
markevery=None,
**kwargs
):
"""
Create a :class:`~matplotlib.lines.Line2D` instance with *x*
and *y* data in sequences *xdata*, *ydata*.
The kwargs are :class:`~matplotlib.lines.Line2D` properties:
%(_Line2D_docstr)s
See :meth:`set_linestyle` for a description of the line styles,
:meth:`set_marker` for a description of the markers, and
:meth:`set_drawstyle` for a description of the draw styles.
"""
Artist.__init__(self)
#convert sequences to numpy arrays
if not np.iterable(xdata):
raise RuntimeError('xdata must be a sequence')
if not np.iterable(ydata):
raise RuntimeError('ydata must be a sequence')
if linewidth is None:
linewidth = rcParams['lines.linewidth']
if linestyle is None:
linestyle = rcParams['lines.linestyle']
if marker is None:
marker = rcParams['lines.marker']
if markerfacecolor is None:
markerfacecolor = rcParams['lines.markerfacecolor']
if markeredgecolor is None:
markeredgecolor = rcParams['lines.markeredgecolor']
if color is None:
color = rcParams['lines.color']
if markersize is None:
markersize = rcParams['lines.markersize']
if antialiased is None:
antialiased = rcParams['lines.antialiased']
if dash_capstyle is None:
dash_capstyle = rcParams['lines.dash_capstyle']
if dash_joinstyle is None:
dash_joinstyle = rcParams['lines.dash_joinstyle']
if solid_capstyle is None:
solid_capstyle = rcParams['lines.solid_capstyle']
if solid_joinstyle is None:
solid_joinstyle = rcParams['lines.solid_joinstyle']
if isinstance(linestyle, str):
ds, ls = self._split_drawstyle_linestyle(linestyle)
if ds is not None and drawstyle is not None and ds != drawstyle:
raise ValueError("Inconsistent drawstyle ({!r}) and linestyle "
"({!r})".format(drawstyle, linestyle))
linestyle = ls
if ds is not None:
drawstyle = ds
if drawstyle is None:
drawstyle = 'default'
self._dashcapstyle = None
self._dashjoinstyle = None
self._solidjoinstyle = None
self._solidcapstyle = None
self.set_dash_capstyle(dash_capstyle)
self.set_dash_joinstyle(dash_joinstyle)
self.set_solid_capstyle(solid_capstyle)
self.set_solid_joinstyle(solid_joinstyle)
self._linestyles = None
self._drawstyle = None
self._linewidth = linewidth
# scaled dash + offset
self._dashSeq = None
self._dashOffset = 0
# unscaled dash + offset
# this is needed scaling the dash pattern by linewidth
self._us_dashSeq = None
self._us_dashOffset = 0
self.set_linewidth(linewidth)
self.set_linestyle(linestyle)
self.set_drawstyle(drawstyle)
self._color = None
self.set_color(color)
self._marker = MarkerStyle(marker, fillstyle)
self._markevery = None
self._markersize = None
self._antialiased = None
self.set_markevery(markevery)
self.set_antialiased(antialiased)
self.set_markersize(markersize)
self._markeredgecolor = None
self._markeredgewidth = None
self._markerfacecolor = None
self._markerfacecoloralt = None
self.set_markerfacecolor(markerfacecolor)
self.set_markerfacecoloralt(markerfacecoloralt)
self.set_markeredgecolor(markeredgecolor)
self.set_markeredgewidth(markeredgewidth)
# update kwargs before updating data to give the caller a
# chance to init axes (and hence unit support)
self.update(kwargs)
self.pickradius = pickradius
self.ind_offset = 0
if isinstance(self._picker, Number):
self.pickradius = self._picker
self._xorig = np.asarray([])
self._yorig = np.asarray([])
self._invalidx = True
self._invalidy = True
self._x = None
self._y = None
self._xy = None
self._path = None
self._transformed_path = None
self._subslice = False
self._x_filled = None # used in subslicing; only x is needed
self.set_data(xdata, ydata)
@cbook.deprecated("3.1")
@property
def verticalOffset(self):
return None
def contains(self, mouseevent):
"""
Test whether the mouse event occurred on the line. The pick
radius determines the precision of the location test (usually
within five points of the value). Use
:meth:`~matplotlib.lines.Line2D.get_pickradius` or
:meth:`~matplotlib.lines.Line2D.set_pickradius` to view or
modify it.
Parameters
----------
mouseevent : `matplotlib.backend_bases.MouseEvent`
Returns
-------
contains : bool
Whether any values are within the radius.
details : dict
A dictionary ``{'ind': pointlist}``, where *pointlist* is a
list of points of the line that are within the pickradius around
the event position.
TODO: sort returned indices by distance
"""
if callable(self._contains):
return self._contains(self, mouseevent)
if not isinstance(self.pickradius, Number):
raise ValueError("pick radius should be a distance")
# Make sure we have data to plot
if self._invalidy or self._invalidx:
self.recache()
if len(self._xy) == 0:
return False, {}
# Convert points to pixels
transformed_path = self._get_transformed_path()
path, affine = transformed_path.get_transformed_path_and_affine()
path = affine.transform_path(path)
xy = path.vertices
xt = xy[:, 0]
yt = xy[:, 1]
# Convert pick radius from points to pixels
if self.figure is None:
_log.warning('no figure set when check if mouse is on line')
pixels = self.pickradius
else:
pixels = self.figure.dpi / 72. * self.pickradius
# The math involved in checking for containment (here and inside of
# segment_hits) assumes that it is OK to overflow, so temporarily set
# the error flags accordingly.
with np.errstate(all='ignore'):
# Check for collision
if self._linestyle in ['None', None]:
# If no line, return the nearby point(s)
ind, = np.nonzero(
(xt - mouseevent.x) ** 2 + (yt - mouseevent.y) ** 2
<= pixels ** 2)
else:
# If line, return the nearby segment(s)
ind = segment_hits(mouseevent.x, mouseevent.y, xt, yt, pixels)
if self._drawstyle.startswith("steps"):
ind //= 2
ind += self.ind_offset
# Return the point(s) within radius
return len(ind) > 0, dict(ind=ind)
def get_pickradius(self):
"""
Return the pick radius used for containment tests.
See `.contains` for more details.
"""
return self.pickradius
def set_pickradius(self, d):
"""Set the pick radius used for containment tests.
See `.contains` for more details.
Parameters
----------
d : float
Pick radius, in points.
"""
self.pickradius = d
def get_fillstyle(self):
"""
Return the marker fill style.
See also `~.Line2D.set_fillstyle`.
"""
return self._marker.get_fillstyle()
def set_fillstyle(self, fs):
"""
Set the marker fill style.
Parameters
----------
fs : {'full', 'left', 'right', 'bottom', 'top', 'none'}
Possible values:
- 'full': Fill the whole marker with the *markerfacecolor*.
- 'left', 'right', 'bottom', 'top': Fill the marker half at
the given side with the *markerfacecolor*. The other
half of the marker is filled with *markerfacecoloralt*.
- 'none': No filling.
For examples see
:doc:`/gallery/lines_bars_and_markers/marker_fillstyle_reference`.
"""
self._marker.set_fillstyle(fs)
self.stale = True
def set_markevery(self, every):
"""Set the markevery property to subsample the plot when using markers.
e.g., if `every=5`, every 5-th marker will be plotted.
Parameters
----------
every : None or int or (int, int) or slice or List[int] or float or \
(float, float)
Which markers to plot.
- every=None, every point will be plotted.
- every=N, every N-th marker will be plotted starting with
marker 0.
- every=(start, N), every N-th marker, starting at point
start, will be plotted.
- every=slice(start, end, N), every N-th marker, starting at
point start, up to but not including point end, will be plotted.
- every=[i, j, m, n], only markers at points i, j, m, and n
will be plotted.
- every=0.1, (i.e. a float) then markers will be spaced at
approximately equal distances along the line; the distance
along the line between markers is determined by multiplying the
display-coordinate distance of the axes bounding-box diagonal
by the value of every.
- every=(0.5, 0.1) (i.e. a length-2 tuple of float), the same
functionality as every=0.1 is exhibited but the first marker will
be 0.5 multiplied by the display-coordinate-diagonal-distance
along the line.
Notes
-----
Setting the markevery property will only show markers at actual data
points. When using float arguments to set the markevery property
on irregularly spaced data, the markers will likely not appear evenly
spaced because the actual data points do not coincide with the
theoretical spacing between markers.
When using a start offset to specify the first marker, the offset will
be from the first data point which may be different from the first
the visible data point if the plot is zoomed in.
If zooming in on a plot when using float arguments then the actual
data points that have markers will change because the distance between
markers is always determined from the display-coordinates
axes-bounding-box-diagonal regardless of the actual axes data limits.
"""
if self._markevery != every:
self.stale = True
self._markevery = every
def get_markevery(self):
"""
Return the markevery setting for marker subsampling.
See also `~.Line2D.set_markevery`.
"""
return self._markevery
def set_picker(self, p):
"""Sets the event picker details for the line.
Parameters
----------
p : float or callable[[Artist, Event], Tuple[bool, dict]]
If a float, it is used as the pick radius in points.
"""
if callable(p):
self._contains = p
else:
self.pickradius = p
self._picker = p
def get_window_extent(self, renderer):
bbox = Bbox([[0, 0], [0, 0]])
trans_data_to_xy = self.get_transform().transform
bbox.update_from_data_xy(trans_data_to_xy(self.get_xydata()),
ignore=True)
# correct for marker size, if any
if self._marker:
ms = (self._markersize / 72.0 * self.figure.dpi) * 0.5
bbox = bbox.padded(ms)
return bbox
@Artist.axes.setter
def axes(self, ax):
# call the set method from the base-class property
Artist.axes.fset(self, ax)
if ax is not None:
# connect unit-related callbacks
if ax.xaxis is not None:
self._xcid = ax.xaxis.callbacks.connect('units',
self.recache_always)
if ax.yaxis is not None:
self._ycid = ax.yaxis.callbacks.connect('units',
self.recache_always)
def set_data(self, *args):
"""
Set the x and y data.
Parameters
----------
*args : (N, 2) array or two 1D arrays
"""
if len(args) == 1:
(x, y), = args
else:
x, y = args
self.set_xdata(x)
self.set_ydata(y)
def recache_always(self):
self.recache(always=True)
def recache(self, always=False):
if always or self._invalidx:
xconv = self.convert_xunits(self._xorig)
x = _to_unmasked_float_array(xconv).ravel()
else:
x = self._x
if always or self._invalidy:
yconv = self.convert_yunits(self._yorig)
y = _to_unmasked_float_array(yconv).ravel()
else:
y = self._y
self._xy = np.column_stack(np.broadcast_arrays(x, y)).astype(float)
self._x, self._y = self._xy.T # views
self._subslice = False
if (self.axes and len(x) > 1000 and self._is_sorted(x) and
self.axes.name == 'rectilinear' and
self.axes.get_xscale() == 'linear' and
self._markevery is None and
self.get_clip_on()):
self._subslice = True
nanmask = np.isnan(x)
if nanmask.any():
self._x_filled = self._x.copy()
indices = np.arange(len(x))
self._x_filled[nanmask] = np.interp(indices[nanmask],
indices[~nanmask], self._x[~nanmask])
else:
self._x_filled = self._x
if self._path is not None:
interpolation_steps = self._path._interpolation_steps
else:
interpolation_steps = 1
xy = STEP_LOOKUP_MAP[self._drawstyle](*self._xy.T)
self._path = Path(np.asarray(xy).T,
_interpolation_steps=interpolation_steps)
self._transformed_path = None
self._invalidx = False
self._invalidy = False
def _transform_path(self, subslice=None):
"""
Puts a TransformedPath instance at self._transformed_path;
all invalidation of the transform is then handled by the
TransformedPath instance.
"""
# Masked arrays are now handled by the Path class itself
if subslice is not None:
xy = STEP_LOOKUP_MAP[self._drawstyle](*self._xy[subslice, :].T)
_path = Path(np.asarray(xy).T,
_interpolation_steps=self._path._interpolation_steps)
else:
_path = self._path
self._transformed_path = TransformedPath(_path, self.get_transform())
def _get_transformed_path(self):
"""
Return the :class:`~matplotlib.transforms.TransformedPath` instance
of this line.
"""
if self._transformed_path is None:
self._transform_path()
return self._transformed_path
def set_transform(self, t):
"""
Set the Transformation instance used by this artist.
Parameters
----------
t : `matplotlib.transforms.Transform`
"""
Artist.set_transform(self, t)
self._invalidx = True
self._invalidy = True
self.stale = True
def _is_sorted(self, x):
"""Return whether x is sorted in ascending order."""
# We don't handle the monotonically decreasing case.
return _path.is_sorted(x)
@allow_rasterization
def draw(self, renderer):
# docstring inherited from Artist.draw.
if not self.get_visible():
return
if self._invalidy or self._invalidx:
self.recache()
self.ind_offset = 0 # Needed for contains() method.
if self._subslice and self.axes:
x0, x1 = self.axes.get_xbound()
i0 = self._x_filled.searchsorted(x0, 'left')
i1 = self._x_filled.searchsorted(x1, 'right')
subslice = slice(max(i0 - 1, 0), i1 + 1)
self.ind_offset = subslice.start
self._transform_path(subslice)
else:
subslice = None
if self.get_path_effects():
from matplotlib.patheffects import PathEffectRenderer
renderer = PathEffectRenderer(self.get_path_effects(), renderer)
renderer.open_group('line2d', self.get_gid())
if self._lineStyles[self._linestyle] != '_draw_nothing':
tpath, affine = (self._get_transformed_path()
.get_transformed_path_and_affine())
if len(tpath.vertices):
gc = renderer.new_gc()
self._set_gc_clip(gc)
lc_rgba = mcolors.to_rgba(self._color, self._alpha)
gc.set_foreground(lc_rgba, isRGBA=True)
gc.set_antialiased(self._antialiased)
gc.set_linewidth(self._linewidth)
if self.is_dashed():
cap = self._dashcapstyle
join = self._dashjoinstyle
else:
cap = self._solidcapstyle
join = self._solidjoinstyle
gc.set_joinstyle(join)
gc.set_capstyle(cap)
gc.set_snap(self.get_snap())
if self.get_sketch_params() is not None:
gc.set_sketch_params(*self.get_sketch_params())
gc.set_dashes(self._dashOffset, self._dashSeq)
renderer.draw_path(gc, tpath, affine.frozen())
gc.restore()
if self._marker and self._markersize > 0:
gc = renderer.new_gc()
self._set_gc_clip(gc)
gc.set_linewidth(self._markeredgewidth)
gc.set_antialiased(self._antialiased)
ec_rgba = mcolors.to_rgba(
self.get_markeredgecolor(), self._alpha)
fc_rgba = mcolors.to_rgba(
self._get_markerfacecolor(), self._alpha)
fcalt_rgba = mcolors.to_rgba(
self._get_markerfacecolor(alt=True), self._alpha)
# If the edgecolor is "auto", it is set according to the *line*
# color but inherits the alpha value of the *face* color, if any.
if (cbook._str_equal(self._markeredgecolor, "auto")
and not cbook._str_lower_equal(
self.get_markerfacecolor(), "none")):
ec_rgba = ec_rgba[:3] + (fc_rgba[3],)
gc.set_foreground(ec_rgba, isRGBA=True)
if self.get_sketch_params() is not None:
scale, length, randomness = self.get_sketch_params()
gc.set_sketch_params(scale/2, length/2, 2*randomness)
marker = self._marker
# Markers *must* be drawn ignoring the drawstyle (but don't pay the
# recaching if drawstyle is already "default").
if self.get_drawstyle() != "default":
with cbook._setattr_cm(
self, _drawstyle="default", _transformed_path=None):
self.recache()
self._transform_path(subslice)
tpath, affine = (self._get_transformed_path()
.get_transformed_path_and_affine())
else:
tpath, affine = (self._get_transformed_path()
.get_transformed_path_and_affine())
if len(tpath.vertices):
# subsample the markers if markevery is not None
markevery = self.get_markevery()
if markevery is not None:
subsampled = _mark_every_path(markevery, tpath,
affine, self.axes.transAxes)
else:
subsampled = tpath
snap = marker.get_snap_threshold()
if isinstance(snap, Real):
snap = renderer.points_to_pixels(self._markersize) >= snap
gc.set_snap(snap)
gc.set_joinstyle(marker.get_joinstyle())
gc.set_capstyle(marker.get_capstyle())
marker_path = marker.get_path()
marker_trans = marker.get_transform()
w = renderer.points_to_pixels(self._markersize)
if cbook._str_equal(marker.get_marker(), ","):
gc.set_linewidth(0)
else:
# Don't scale for pixels, and don't stroke them
marker_trans = marker_trans.scale(w)
renderer.draw_markers(gc, marker_path, marker_trans,
subsampled, affine.frozen(),
fc_rgba)
alt_marker_path = marker.get_alt_path()
if alt_marker_path:
alt_marker_trans = marker.get_alt_transform()
alt_marker_trans = alt_marker_trans.scale(w)
renderer.draw_markers(
gc, alt_marker_path, alt_marker_trans, subsampled,
affine.frozen(), fcalt_rgba)
gc.restore()
renderer.close_group('line2d')
self.stale = False
def get_antialiased(self):
"""Return whether antialiased rendering is used."""
return self._antialiased
def get_color(self):
"""
Return the line color.
See also `~.Line2D.set_color`.
"""
return self._color
def get_drawstyle(self):
"""
Return the drawstyle.
See also `~.Line2D.set_drawstyle`.
"""
return self._drawstyle
def get_linestyle(self):
"""
Return the linestyle.
See also `~.Line2D.set_linestyle`.
"""
return self._linestyle
def get_linewidth(self):
"""
Return the linewidth in points.
See also `~.Line2D.set_linewidth`.
"""
return self._linewidth
def get_marker(self):
"""
Return the line marker.
See also `~.Line2D.set_marker`.
"""
return self._marker.get_marker()
def get_markeredgecolor(self):
"""
Return the marker edge color.
See also `~.Line2D.set_markeredgecolor`.
"""
mec = self._markeredgecolor
if cbook._str_equal(mec, 'auto'):
if rcParams['_internal.classic_mode']:
if self._marker.get_marker() in ('.', ','):
return self._color
if self._marker.is_filled() and self.get_fillstyle() != 'none':
return 'k' # Bad hard-wired default...
return self._color
else:
return mec
def get_markeredgewidth(self):
"""
Return the marker edge width in points.
See also `~.Line2D.set_markeredgewidth`.
"""
return self._markeredgewidth
def _get_markerfacecolor(self, alt=False):
fc = self._markerfacecoloralt if alt else self._markerfacecolor
if cbook._str_lower_equal(fc, 'auto'):
if self.get_fillstyle() == 'none':
return 'none'
else:
return self._color
else:
return fc
def get_markerfacecolor(self):
"""
Return the marker face color.
See also `~.Line2D.set_markerfacecolor`.
"""
return self._get_markerfacecolor(alt=False)
def get_markerfacecoloralt(self):
"""
Return the alternate marker face color.
See also `~.Line2D.set_markerfacecoloralt`.
"""
return self._get_markerfacecolor(alt=True)
def get_markersize(self):
"""
Return the marker size in points.
See also `~.Line2D.set_markersize`.
"""
return self._markersize
def get_data(self, orig=True):
"""
Return the xdata, ydata.
If *orig* is *True*, return the original data.
"""
return self.get_xdata(orig=orig), self.get_ydata(orig=orig)
def get_xdata(self, orig=True):
"""
Return the xdata.
If *orig* is *True*, return the original data, else the
processed data.
"""
if orig:
return self._xorig
if self._invalidx:
self.recache()
return self._x
def get_ydata(self, orig=True):
"""
Return the ydata.
If *orig* is *True*, return the original data, else the
processed data.
"""
if orig:
return self._yorig
if self._invalidy:
self.recache()
return self._y
def get_path(self):
"""
Return the :class:`~matplotlib.path.Path` object associated
with this line.
"""
if self._invalidy or self._invalidx:
self.recache()
return self._path
def get_xydata(self):
"""
Return the *xy* data as a Nx2 numpy array.
"""
if self._invalidy or self._invalidx:
self.recache()
return self._xy
def set_antialiased(self, b):
"""
Set whether to use antialiased rendering.
Parameters
----------
b : bool
"""
if self._antialiased != b:
self.stale = True
self._antialiased = b
def set_color(self, color):
"""
Set the color of the line.
Parameters
----------
color : color
"""
self._color = color
self.stale = True
def set_drawstyle(self, drawstyle):
"""
Set the drawstyle of the plot.
The drawstyle determines how the points are connected.
Parameters
----------
drawstyle : {'default', 'steps', 'steps-pre', 'steps-mid', \
'steps-post'}, default: 'default'
For 'default', the points are connected with straight lines.
The steps variants connect the points with step-like lines,
i.e. horizontal lines with vertical steps. They differ in the
location of the step:
- 'steps-pre': The step is at the beginning of the line segment,
i.e. the line will be at the y-value of point to the right.
- 'steps-mid': The step is halfway between the points.
- 'steps-post: The step is at the end of the line segment,
i.e. the line will be at the y-value of the point to the left.
- 'steps' is equal to 'steps-pre' and is maintained for
backward-compatibility.
"""
if drawstyle is None:
drawstyle = 'default'
cbook._check_in_list(self.drawStyles, drawstyle=drawstyle)
if self._drawstyle != drawstyle:
self.stale = True
# invalidate to trigger a recache of the path
self._invalidx = True
self._drawstyle = drawstyle
def set_linewidth(self, w):
"""
Set the line width in points.
Parameters
----------
w : float
"""
w = float(w)
if self._linewidth != w:
self.stale = True
self._linewidth = w
# rescale the dashes + offset
self._dashOffset, self._dashSeq = _scale_dashes(
self._us_dashOffset, self._us_dashSeq, self._linewidth)
def _split_drawstyle_linestyle(self, ls):
"""
Split drawstyle from linestyle string.
If *ls* is only a drawstyle default to returning a linestyle
of '-'.
Parameters
----------
ls : str
The linestyle to be processed
Returns
-------
ret_ds : str or None
If the linestyle string does not contain a drawstyle prefix
return None, otherwise return it.
ls : str
The linestyle with the drawstyle (if any) stripped.
"""
for ds in self.drawStyleKeys: # long names are first in the list
if ls.startswith(ds):
cbook.warn_deprecated(
"3.1", message="Passing the drawstyle with the linestyle "
"as a single string is deprecated since Matplotlib "
"%(since)s and support will be removed %(removal)s; "
"please pass the drawstyle separately using the drawstyle "
"keyword argument to Line2D or set_drawstyle() method (or "
"ds/set_ds()).")
return ds, ls[len(ds):] or '-'
return None, ls
def set_linestyle(self, ls):
"""
Set the linestyle of the line.
Parameters
----------
ls : {'-', '--', '-.', ':', '', (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
``'None'`` or ``' '`` or ``''`` draw nothing
=============================== =================
Optionally, the string may be preceded by a drawstyle, e.g.
``'steps--'``. See :meth:`set_drawstyle` for details.
- Alternatively a dash tuple of the following form can be
provided::
(offset, onoffseq)
where ``onoffseq`` is an even length tuple of on and off ink
in points. See also :meth:`set_dashes`.
"""
if isinstance(ls, str):
ds, ls = self._split_drawstyle_linestyle(ls)
if ds is not None:
self.set_drawstyle(ds)
if ls in [' ', '', 'none']:
ls = 'None'
cbook._check_in_list([*self._lineStyles, *ls_mapper_r], ls=ls)
if ls not in self._lineStyles:
ls = ls_mapper_r[ls]
self._linestyle = ls
else:
self._linestyle = '--'
# get the unscaled dashes
self._us_dashOffset, self._us_dashSeq = _get_dash_pattern(ls)
# compute the linewidth scaled dashes
self._dashOffset, self._dashSeq = _scale_dashes(
self._us_dashOffset, self._us_dashSeq, self._linewidth)
@docstring.dedent_interpd
def set_marker(self, marker):
"""
Set the line marker.
Parameters
----------
marker : marker style
See `~matplotlib.markers` for full description of possible
arguments.
"""
self._marker.set_marker(marker)
self.stale = True
def set_markeredgecolor(self, ec):
"""
Set the marker edge color.
Parameters
----------
ec : color
"""
if ec is None:
ec = 'auto'
if (self._markeredgecolor is None
or np.any(self._markeredgecolor != ec)):
self.stale = True
self._markeredgecolor = ec
def set_markeredgewidth(self, ew):
"""
Set the marker edge width in points.
Parameters
----------
ew : float
"""
if ew is None:
ew = rcParams['lines.markeredgewidth']
if self._markeredgewidth != ew:
self.stale = True
self._markeredgewidth = ew
def set_markerfacecolor(self, fc):
"""
Set the marker face color.
Parameters
----------
fc : color
"""
if fc is None:
fc = 'auto'
if np.any(self._markerfacecolor != fc):
self.stale = True
self._markerfacecolor = fc
def set_markerfacecoloralt(self, fc):
"""
Set the alternate marker face color.
Parameters
----------
fc : color
"""
if fc is None:
fc = 'auto'
if np.any(self._markerfacecoloralt != fc):
self.stale = True
self._markerfacecoloralt = fc
def set_markersize(self, sz):
"""
Set the marker size in points.
Parameters
----------
sz : float
"""
sz = float(sz)
if self._markersize != sz:
self.stale = True
self._markersize = sz
def set_xdata(self, x):
"""
Set the data array for x.
Parameters
----------
x : 1D array
"""
self._xorig = x
self._invalidx = True
self.stale = True
def set_ydata(self, y):
"""
Set the data array for y.
Parameters
----------
y : 1D array
"""
self._yorig = y
self._invalidy = True
self.stale = True
def set_dashes(self, seq):
"""
Set the dash sequence.
The dash sequence is a sequence of floats of even length describing
the length of dashes and spaces in points.
For example, (5, 2, 1, 2) describes a sequence of 5 point and 1 point
dashes separated by 2 point spaces.
Parameters
----------
seq : sequence of floats (on/off ink in points) or (None, None)
If *seq* is empty or ``(None, None)``, the linestyle will be set
to solid.
"""
if seq == (None, None) or len(seq) == 0:
self.set_linestyle('-')
else:
self.set_linestyle((0, seq))
def update_from(self, other):
"""Copy properties from other to self."""
Artist.update_from(self, other)
self._linestyle = other._linestyle
self._linewidth = other._linewidth
self._color = other._color
self._markersize = other._markersize
self._markerfacecolor = other._markerfacecolor
self._markerfacecoloralt = other._markerfacecoloralt
self._markeredgecolor = other._markeredgecolor
self._markeredgewidth = other._markeredgewidth
self._dashSeq = other._dashSeq
self._us_dashSeq = other._us_dashSeq
self._dashOffset = other._dashOffset
self._us_dashOffset = other._us_dashOffset
self._dashcapstyle = other._dashcapstyle
self._dashjoinstyle = other._dashjoinstyle
self._solidcapstyle = other._solidcapstyle
self._solidjoinstyle = other._solidjoinstyle
self._linestyle = other._linestyle
self._marker = MarkerStyle(other._marker.get_marker(),
other._marker.get_fillstyle())
self._drawstyle = other._drawstyle
def set_dash_joinstyle(self, s):
"""
Set the join style for dashed lines.
Parameters
----------
s : {'miter', 'round', 'bevel'}
For examples see :doc:`/gallery/lines_bars_and_markers/joinstyle`.
"""
s = s.lower()
cbook._check_in_list(self.validJoin, s=s)
if self._dashjoinstyle != s:
self.stale = True
self._dashjoinstyle = s
def set_solid_joinstyle(self, s):
"""
Set the join style for solid lines.
Parameters
----------
s : {'miter', 'round', 'bevel'}
For examples see :doc:`/gallery/lines_bars_and_markers/joinstyle`.
"""
s = s.lower()
cbook._check_in_list(self.validJoin, s=s)
if self._solidjoinstyle != s:
self.stale = True
self._solidjoinstyle = s
def get_dash_joinstyle(self):
"""
Return the join style for dashed lines.
See also `~.Line2D.set_dash_joinstyle`.
"""
return self._dashjoinstyle
def get_solid_joinstyle(self):
"""
Return the join style for solid lines.
See also `~.Line2D.set_solid_joinstyle`.
"""
return self._solidjoinstyle
def set_dash_capstyle(self, s):
"""
Set the cap style for dashed lines.
Parameters
----------
s : {'butt', 'round', 'projecting'}
"""
s = s.lower()
cbook._check_in_list(self.validCap, s=s)
if self._dashcapstyle != s:
self.stale = True
self._dashcapstyle = s
def set_solid_capstyle(self, s):
"""
Set the cap style for solid lines.
Parameters
----------
s : {'butt', 'round', 'projecting'}
"""
s = s.lower()
cbook._check_in_list(self.validCap, s=s)
if self._solidcapstyle != s:
self.stale = True
self._solidcapstyle = s
def get_dash_capstyle(self):
"""
Return the cap style for dashed lines.
See also `~.Line2D.set_dash_capstyle`.
"""
return self._dashcapstyle
def get_solid_capstyle(self):
"""
Return the cap style for solid lines.
See also `~.Line2D.set_solid_capstyle`.
"""
return self._solidcapstyle
def is_dashed(self):
"""
Return whether line has a dashed linestyle.
See also `~.Line2D.set_linestyle`.
"""
return self._linestyle in ('--', '-.', ':')
class VertexSelector(object):
"""
Manage the callbacks to maintain a list of selected vertices for
:class:`matplotlib.lines.Line2D`. Derived classes should override
:meth:`~matplotlib.lines.VertexSelector.process_selected` to do
something with the picks.
Here is an example which highlights the selected verts with red
circles::
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.lines as lines
class HighlightSelected(lines.VertexSelector):
def __init__(self, line, fmt='ro', **kwargs):
lines.VertexSelector.__init__(self, line)
self.markers, = self.axes.plot([], [], fmt, **kwargs)
def process_selected(self, ind, xs, ys):
self.markers.set_data(xs, ys)
self.canvas.draw()
fig, ax = plt.subplots()
x, y = np.random.rand(2, 30)
line, = ax.plot(x, y, 'bs-', picker=5)
selector = HighlightSelected(line)
plt.show()
"""
def __init__(self, line):
"""
Initialize the class with a :class:`matplotlib.lines.Line2D`
instance. The line should already be added to some
:class:`matplotlib.axes.Axes` instance and should have the
picker property set.
"""
if line.axes is None:
raise RuntimeError('You must first add the line to the Axes')
if line.get_picker() is None:
raise RuntimeError('You must first set the picker property '
'of the line')
self.axes = line.axes
self.line = line
self.canvas = self.axes.figure.canvas
self.cid = self.canvas.mpl_connect('pick_event', self.onpick)
self.ind = set()
def process_selected(self, ind, xs, ys):
"""
Default "do nothing" implementation of the
:meth:`process_selected` method.
*ind* are the indices of the selected vertices. *xs* and *ys*
are the coordinates of the selected vertices.
"""
pass
def onpick(self, event):
"""When the line is picked, update the set of selected indices."""
if event.artist is not self.line:
return
self.ind ^= set(event.ind)
ind = sorted(self.ind)
xdata, ydata = self.line.get_data()
self.process_selected(ind, xdata[ind], ydata[ind])
lineStyles = Line2D._lineStyles
lineMarkers = MarkerStyle.markers
drawStyles = Line2D.drawStyles
fillStyles = MarkerStyle.fillstyles
docstring.interpd.update(_Line2D_docstr=artist.kwdoc(Line2D))
# You can not set the docstring of an instancemethod,
# but you can on the underlying function. Go figure.
docstring.dedent_interpd(Line2D.__init__)
|
c82966331e8afb2ea98c6dc57476a7711c918729de16e0446d067f9617b3572b
|
# Javascript template for HTMLWriter
JS_INCLUDE = """
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/
css/font-awesome.min.css">
<script language="javascript">
function isInternetExplorer() {
ua = navigator.userAgent;
/* MSIE used to detect old browsers and Trident used to newer ones*/
return ua.indexOf("MSIE ") > -1 || ua.indexOf("Trident/") > -1;
}
/* Define the Animation class */
function Animation(frames, img_id, slider_id, interval, loop_select_id){
this.img_id = img_id;
this.slider_id = slider_id;
this.loop_select_id = loop_select_id;
this.interval = interval;
this.current_frame = 0;
this.direction = 0;
this.timer = null;
this.frames = new Array(frames.length);
for (var i=0; i<frames.length; i++)
{
this.frames[i] = new Image();
this.frames[i].src = frames[i];
}
var slider = document.getElementById(this.slider_id);
slider.max = this.frames.length - 1;
if (isInternetExplorer()) {
// switch from oninput to onchange because IE <= 11 does not conform
// with W3C specification. It ignores oninput and onchange behaves
// like oninput. In contrast, Mircosoft Edge behaves correctly.
slider.setAttribute('onchange', slider.getAttribute('oninput'));
slider.setAttribute('oninput', null);
}
this.set_frame(this.current_frame);
}
Animation.prototype.get_loop_state = function(){
var button_group = document[this.loop_select_id].state;
for (var i = 0; i < button_group.length; i++) {
var button = button_group[i];
if (button.checked) {
return button.value;
}
}
return undefined;
}
Animation.prototype.set_frame = function(frame){
this.current_frame = frame;
document.getElementById(this.img_id).src =
this.frames[this.current_frame].src;
document.getElementById(this.slider_id).value = this.current_frame;
}
Animation.prototype.next_frame = function()
{
this.set_frame(Math.min(this.frames.length - 1, this.current_frame + 1));
}
Animation.prototype.previous_frame = function()
{
this.set_frame(Math.max(0, this.current_frame - 1));
}
Animation.prototype.first_frame = function()
{
this.set_frame(0);
}
Animation.prototype.last_frame = function()
{
this.set_frame(this.frames.length - 1);
}
Animation.prototype.slower = function()
{
this.interval /= 0.7;
if(this.direction > 0){this.play_animation();}
else if(this.direction < 0){this.reverse_animation();}
}
Animation.prototype.faster = function()
{
this.interval *= 0.7;
if(this.direction > 0){this.play_animation();}
else if(this.direction < 0){this.reverse_animation();}
}
Animation.prototype.anim_step_forward = function()
{
this.current_frame += 1;
if(this.current_frame < this.frames.length){
this.set_frame(this.current_frame);
}else{
var loop_state = this.get_loop_state();
if(loop_state == "loop"){
this.first_frame();
}else if(loop_state == "reflect"){
this.last_frame();
this.reverse_animation();
}else{
this.pause_animation();
this.last_frame();
}
}
}
Animation.prototype.anim_step_reverse = function()
{
this.current_frame -= 1;
if(this.current_frame >= 0){
this.set_frame(this.current_frame);
}else{
var loop_state = this.get_loop_state();
if(loop_state == "loop"){
this.last_frame();
}else if(loop_state == "reflect"){
this.first_frame();
this.play_animation();
}else{
this.pause_animation();
this.first_frame();
}
}
}
Animation.prototype.pause_animation = function()
{
this.direction = 0;
if (this.timer){
clearInterval(this.timer);
this.timer = null;
}
}
Animation.prototype.play_animation = function()
{
this.pause_animation();
this.direction = 1;
var t = this;
if (!this.timer) this.timer = setInterval(function() {
t.anim_step_forward();
}, this.interval);
}
Animation.prototype.reverse_animation = function()
{
this.pause_animation();
this.direction = -1;
var t = this;
if (!this.timer) this.timer = setInterval(function() {
t.anim_step_reverse();
}, this.interval);
}
</script>
"""
# Style definitions for the HTML template
STYLE_INCLUDE = """
<style>
.animation {
display: inline-block;
text-align: center;
}
input[type=range].anim-slider {
width: 374px;
margin-left: auto;
margin-right: auto;
}
.anim-buttons {
margin: 8px 0px;
}
.anim-buttons button {
padding: 0;
width: 36px;
}
.anim-state label {
margin-right: 8px;
}
.anim-state input {
margin: 0;
vertical-align: middle;
}
</style>
"""
# HTML template for HTMLWriter
DISPLAY_TEMPLATE = """
<div class="animation">
<img id="_anim_img{id}">
<div class="anim-controls">
<input id="_anim_slider{id}" type="range" class="anim-slider"
name="points" min="0" max="1" step="1" value="0"
oninput="anim{id}.set_frame(parseInt(this.value));"></input>
<div class="anim-buttons">
<button onclick="anim{id}.slower()"><i class="fa fa-minus"></i></button>
<button onclick="anim{id}.first_frame()"><i class="fa fa-fast-backward">
</i></button>
<button onclick="anim{id}.previous_frame()">
<i class="fa fa-step-backward"></i></button>
<button onclick="anim{id}.reverse_animation()">
<i class="fa fa-play fa-flip-horizontal"></i></button>
<button onclick="anim{id}.pause_animation()"><i class="fa fa-pause">
</i></button>
<button onclick="anim{id}.play_animation()"><i class="fa fa-play"></i>
</button>
<button onclick="anim{id}.next_frame()"><i class="fa fa-step-forward">
</i></button>
<button onclick="anim{id}.last_frame()"><i class="fa fa-fast-forward">
</i></button>
<button onclick="anim{id}.faster()"><i class="fa fa-plus"></i></button>
</div>
<form action="#n" name="_anim_loop_select{id}" class="anim-state">
<input type="radio" name="state" value="once" id="_anim_radio1_{id}"
{once_checked}>
<label for="_anim_radio1_{id}">Once</label>
<input type="radio" name="state" value="loop" id="_anim_radio2_{id}"
{loop_checked}>
<label for="_anim_radio2_{id}">Loop</label>
<input type="radio" name="state" value="reflect" id="_anim_radio3_{id}"
{reflect_checked}>
<label for="_anim_radio3_{id}">Reflect</label>
</form>
</div>
</div>
<script language="javascript">
/* Instantiate the Animation class. */
/* The IDs given should match those used in the template above. */
(function() {{
var img_id = "_anim_img{id}";
var slider_id = "_anim_slider{id}";
var loop_select_id = "_anim_loop_select{id}";
var frames = new Array({Nframes});
{fill_frames}
/* set a timeout to make sure all the above elements are created before
the object is initialized. */
setTimeout(function() {{
anim{id} = new Animation(frames, img_id, slider_id, {interval},
loop_select_id);
}}, 0);
}})()
</script>
"""
INCLUDED_FRAMES = """
for (var i=0; i<{Nframes}; i++){{
frames[i] = "{frame_dir}/frame" + ("0000000" + i).slice(-7) +
".{frame_format}";
}}
"""
|
6c9e6741e316038918696db16101495e82b96f0a49afb59fdd2ceef5f0ee95b7
|
import logging
import matplotlib.cbook as cbook
import matplotlib.widgets as widgets
from matplotlib.rcsetup import validate_stringlist
import matplotlib.backend_tools as tools
_log = logging.getLogger(__name__)
class ToolEvent(object):
"""Event for tool manipulation (add/remove)."""
def __init__(self, name, sender, tool, data=None):
self.name = name
self.sender = sender
self.tool = tool
self.data = data
class ToolTriggerEvent(ToolEvent):
"""Event to inform that a tool has been triggered."""
def __init__(self, name, sender, tool, canvasevent=None, data=None):
ToolEvent.__init__(self, name, sender, tool, data)
self.canvasevent = canvasevent
class ToolManagerMessageEvent(object):
"""
Event carrying messages from toolmanager.
Messages usually get displayed to the user by the toolbar.
"""
def __init__(self, name, sender, message):
self.name = name
self.sender = sender
self.message = message
class ToolManager(object):
"""
Manager for actions triggered by user interactions (key press, toolbar
clicks, ...) on a Figure.
Attributes
----------
figure : `Figure`
keypresslock : `widgets.LockDraw`
`LockDraw` object to know if the `canvas` key_press_event is locked
messagelock : `widgets.LockDraw`
`LockDraw` object to know if the message is available to write
"""
def __init__(self, figure=None):
_log.warning('Treat the new Tool classes introduced in v1.5 as '
'experimental for now, the API will likely change in '
'version 2.1 and perhaps the rcParam as well')
self._key_press_handler_id = None
self._tools = {}
self._keys = {}
self._toggled = {}
self._callbacks = cbook.CallbackRegistry()
# to process keypress event
self.keypresslock = widgets.LockDraw()
self.messagelock = widgets.LockDraw()
self._figure = None
self.set_figure(figure)
@property
def canvas(self):
"""Canvas managed by FigureManager."""
if not self._figure:
return None
return self._figure.canvas
@property
def figure(self):
"""Figure that holds the canvas."""
return self._figure
@figure.setter
def figure(self, figure):
self.set_figure(figure)
def set_figure(self, figure, update_tools=True):
"""
Bind the given figure to the tools.
Parameters
----------
figure : `.Figure`
update_tools : bool
Force tools to update figure
"""
if self._key_press_handler_id:
self.canvas.mpl_disconnect(self._key_press_handler_id)
self._figure = figure
if figure:
self._key_press_handler_id = self.canvas.mpl_connect(
'key_press_event', self._key_press)
if update_tools:
for tool in self._tools.values():
tool.figure = figure
def toolmanager_connect(self, s, func):
"""
Connect event with string *s* to *func*.
Parameters
----------
s : String
Name of the event
The following events are recognized
- 'tool_message_event'
- 'tool_removed_event'
- 'tool_added_event'
For every tool added a new event is created
- 'tool_trigger_TOOLNAME`
Where TOOLNAME is the id of the tool.
func : function
Function to be called with signature
def func(event)
"""
return self._callbacks.connect(s, func)
def toolmanager_disconnect(self, cid):
"""
Disconnect callback id *cid*.
Example usage::
cid = toolmanager.toolmanager_connect('tool_trigger_zoom', onpress)
#...later
toolmanager.toolmanager_disconnect(cid)
"""
return self._callbacks.disconnect(cid)
def message_event(self, message, sender=None):
"""Emit a `ToolManagerMessageEvent`."""
if sender is None:
sender = self
s = 'tool_message_event'
event = ToolManagerMessageEvent(s, sender, message)
self._callbacks.process(s, event)
@property
def active_toggle(self):
"""Currently toggled tools."""
return self._toggled
def get_tool_keymap(self, name):
"""
Get the keymap associated with the specified tool.
Parameters
----------
name : string
Name of the Tool
Returns
-------
list : list of keys associated with the Tool
"""
keys = [k for k, i in self._keys.items() if i == name]
return keys
def _remove_keys(self, name):
for k in self.get_tool_keymap(name):
del self._keys[k]
def update_keymap(self, name, *keys):
"""
Set the keymap to associate with the specified tool.
Parameters
----------
name : string
Name of the Tool
keys : keys to associate with the Tool
"""
if name not in self._tools:
raise KeyError('%s not in Tools' % name)
self._remove_keys(name)
for key in keys:
for k in validate_stringlist(key):
if k in self._keys:
cbook._warn_external('Key %s changed from %s to %s' %
(k, self._keys[k], name))
self._keys[k] = name
def remove_tool(self, name):
"""
Remove tool named *name*.
Parameters
----------
name : string
Name of the Tool
"""
tool = self.get_tool(name)
tool.destroy()
# If is a toggle tool and toggled, untoggle
if getattr(tool, 'toggled', False):
self.trigger_tool(tool, 'toolmanager')
self._remove_keys(name)
s = 'tool_removed_event'
event = ToolEvent(s, self, tool)
self._callbacks.process(s, event)
del self._tools[name]
def add_tool(self, name, tool, *args, **kwargs):
"""
Add *tool* to `ToolManager`.
If successful, adds a new event ``tool_trigger_{name}`` where
``{name}`` is the *name* of the tool; the event is fired everytime the
tool is triggered.
Parameters
----------
name : str
Name of the tool, treated as the ID, has to be unique.
tool : class_like, i.e. str or type
Reference to find the class of the Tool to added.
Notes
-----
args and kwargs get passed directly to the tools constructor.
See Also
--------
matplotlib.backend_tools.ToolBase : The base class for tools.
"""
tool_cls = self._get_cls_to_instantiate(tool)
if not tool_cls:
raise ValueError('Impossible to find class for %s' % str(tool))
if name in self._tools:
cbook._warn_external('A "Tool class" with the same name already '
'exists, not added')
return self._tools[name]
tool_obj = tool_cls(self, name, *args, **kwargs)
self._tools[name] = tool_obj
if tool_cls.default_keymap is not None:
self.update_keymap(name, tool_cls.default_keymap)
# For toggle tools init the radio_group in self._toggled
if isinstance(tool_obj, tools.ToolToggleBase):
# None group is not mutually exclusive, a set is used to keep track
# of all toggled tools in this group
if tool_obj.radio_group is None:
self._toggled.setdefault(None, set())
else:
self._toggled.setdefault(tool_obj.radio_group, None)
# If initially toggled
if tool_obj.toggled:
self._handle_toggle(tool_obj, None, None, None)
tool_obj.set_figure(self.figure)
self._tool_added_event(tool_obj)
return tool_obj
def _tool_added_event(self, tool):
s = 'tool_added_event'
event = ToolEvent(s, self, tool)
self._callbacks.process(s, event)
def _handle_toggle(self, tool, sender, canvasevent, data):
"""
Toggle tools, need to untoggle prior to using other Toggle tool.
Called from trigger_tool.
Parameters
----------
tool : Tool object
sender : object
Object that wishes to trigger the tool
canvasevent : Event
Original Canvas event or None
data : Object
Extra data to pass to the tool when triggering
"""
radio_group = tool.radio_group
# radio_group None is not mutually exclusive
# just keep track of toggled tools in this group
if radio_group is None:
if tool.name in self._toggled[None]:
self._toggled[None].remove(tool.name)
else:
self._toggled[None].add(tool.name)
return
# If the tool already has a toggled state, untoggle it
if self._toggled[radio_group] == tool.name:
toggled = None
# If no tool was toggled in the radio_group
# toggle it
elif self._toggled[radio_group] is None:
toggled = tool.name
# Other tool in the radio_group is toggled
else:
# Untoggle previously toggled tool
self.trigger_tool(self._toggled[radio_group],
self,
canvasevent,
data)
toggled = tool.name
# Keep track of the toggled tool in the radio_group
self._toggled[radio_group] = toggled
def _get_cls_to_instantiate(self, callback_class):
# Find the class that corresponds to the tool
if isinstance(callback_class, str):
# FIXME: make more complete searching structure
if callback_class in globals():
callback_class = globals()[callback_class]
else:
mod = 'backend_tools'
current_module = __import__(mod,
globals(), locals(), [mod], 1)
callback_class = getattr(current_module, callback_class, False)
if callable(callback_class):
return callback_class
else:
return None
def trigger_tool(self, name, sender=None, canvasevent=None, data=None):
"""
Trigger a tool and emit the ``tool_trigger_{name}`` event.
Parameters
----------
name : string
Name of the tool
sender : object
Object that wishes to trigger the tool
canvasevent : Event
Original Canvas event or None
data : Object
Extra data to pass to the tool when triggering
"""
tool = self.get_tool(name)
if tool is None:
return
if sender is None:
sender = self
self._trigger_tool(name, sender, canvasevent, data)
s = 'tool_trigger_%s' % name
event = ToolTriggerEvent(s, sender, tool, canvasevent, data)
self._callbacks.process(s, event)
def _trigger_tool(self, name, sender=None, canvasevent=None, data=None):
"""Actually trigger a tool."""
tool = self.get_tool(name)
if isinstance(tool, tools.ToolToggleBase):
self._handle_toggle(tool, sender, canvasevent, data)
# Important!!!
# This is where the Tool object gets triggered
tool.trigger(sender, canvasevent, data)
def _key_press(self, event):
if event.key is None or self.keypresslock.locked():
return
name = self._keys.get(event.key, None)
if name is None:
return
self.trigger_tool(name, canvasevent=event)
@property
def tools(self):
"""A dict mapping tool name -> controlled tool."""
return self._tools
def get_tool(self, name, warn=True):
"""
Return the tool object, also accepts the actual tool for convenience.
Parameters
----------
name : str, ToolBase
Name of the tool, or the tool itself
warn : bool, optional
If this method should give warnings.
"""
if isinstance(name, tools.ToolBase) and name.name in self._tools:
return name
if name not in self._tools:
if warn:
cbook._warn_external("ToolManager does not control tool "
"%s" % name)
return None
return self._tools[name]
|
300a695b52a85d9cb4e371b1072438c9aa5d56a343de3e6b193848a32ac8effe
|
"""
The OffsetBox is a simple container artist. The child artist are meant
to be drawn at a relative position to its parent. The [VH]Packer,
DrawingArea and TextArea are derived from the OffsetBox.
The [VH]Packer automatically adjust the relative positions of their
children, which should be instances of the OffsetBox. This is used to
align similar artists together, e.g., in legend.
The DrawingArea can contain any Artist as a child. The
DrawingArea has a fixed width and height. The position of children
relative to the parent is fixed. The TextArea is contains a single
Text instance. The width and height of the TextArea instance is the
width and height of the its child text.
"""
import numpy as np
from matplotlib import cbook, docstring, rcParams
import matplotlib.artist as martist
import matplotlib.path as mpath
import matplotlib.text as mtext
import matplotlib.transforms as mtransforms
from matplotlib.font_manager import FontProperties
from matplotlib.image import BboxImage
from matplotlib.patches import (
FancyBboxPatch, FancyArrowPatch, bbox_artist as mbbox_artist)
from matplotlib.text import _AnnotationBase
from matplotlib.transforms import Bbox, BboxBase, TransformedBbox
DEBUG = False
# for debugging use
def bbox_artist(*args, **kwargs):
if DEBUG:
mbbox_artist(*args, **kwargs)
# _get_packed_offsets() and _get_aligned_offsets() are coded assuming
# that we are packing boxes horizontally. But same function will be
# used with vertical packing.
def _get_packed_offsets(wd_list, total, sep, mode="fixed"):
"""
Given a list of (width, xdescent) of each boxes, calculate the
total width and the x-offset positions of each items according to
*mode*. xdescent is analogous to the usual descent, but along the
x-direction. xdescent values are currently ignored.
*wd_list* : list of (width, xdescent) of boxes to be packed.
*sep* : spacing between boxes
*total* : Intended total length. None if not used.
*mode* : packing mode. 'fixed', 'expand', or 'equal'.
"""
w_list, d_list = zip(*wd_list)
# d_list is currently not used.
if mode == "fixed":
offsets_ = np.cumsum([0] + [w + sep for w in w_list])
offsets = offsets_[:-1]
if total is None:
total = offsets_[-1] - sep
return total, offsets
elif mode == "expand":
# This is a bit of a hack to avoid a TypeError when *total*
# is None and used in conjugation with tight layout.
if total is None:
total = 1
if len(w_list) > 1:
sep = (total - sum(w_list)) / (len(w_list) - 1)
else:
sep = 0
offsets_ = np.cumsum([0] + [w + sep for w in w_list])
offsets = offsets_[:-1]
return total, offsets
elif mode == "equal":
maxh = max(w_list)
if total is None:
total = (maxh + sep) * len(w_list)
else:
sep = total / len(w_list) - maxh
offsets = (maxh + sep) * np.arange(len(w_list))
return total, offsets
else:
raise ValueError("Unknown mode : %s" % (mode,))
def _get_aligned_offsets(hd_list, height, align="baseline"):
"""
Given a list of (height, descent) of each boxes, align the boxes
with *align* and calculate the y-offsets of each boxes.
total width and the offset positions of each items according to
*mode*. xdescent is analogous to the usual descent, but along the
x-direction. xdescent values are currently ignored.
*hd_list* : list of (width, xdescent) of boxes to be aligned.
*sep* : spacing between boxes
*height* : Intended total length. None if not used.
*align* : align mode. 'baseline', 'top', 'bottom', or 'center'.
"""
if height is None:
height = max(h for h, d in hd_list)
if align == "baseline":
height_descent = max(h - d for h, d in hd_list)
descent = max(d for h, d in hd_list)
height = height_descent + descent
offsets = [0. for h, d in hd_list]
elif align in ["left", "top"]:
descent = 0.
offsets = [d for h, d in hd_list]
elif align in ["right", "bottom"]:
descent = 0.
offsets = [height - h + d for h, d in hd_list]
elif align == "center":
descent = 0.
offsets = [(height - h) * .5 + d for h, d in hd_list]
else:
raise ValueError("Unknown Align mode : %s" % (align,))
return height, descent, offsets
class OffsetBox(martist.Artist):
"""
The OffsetBox is a simple container artist. The child artist are meant
to be drawn at a relative position to its parent.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Clipping has not been implemented in the OffesetBox family, so
# disable the clip flag for consistency. It can always be turned back
# on to zero effect.
self.set_clip_on(False)
self._children = []
self._offset = (0, 0)
def set_figure(self, fig):
"""
Set the figure
accepts a class:`~matplotlib.figure.Figure` instance
"""
martist.Artist.set_figure(self, fig)
for c in self.get_children():
c.set_figure(fig)
@martist.Artist.axes.setter
def axes(self, ax):
# TODO deal with this better
martist.Artist.axes.fset(self, ax)
for c in self.get_children():
if c is not None:
c.axes = ax
def contains(self, mouseevent):
for c in self.get_children():
a, b = c.contains(mouseevent)
if a:
return a, b
return False, {}
def set_offset(self, xy):
"""
Set the offset.
Parameters
----------
xy : (float, float) or callable
The (x,y) coordinates of the offset in display units.
A callable must have the signature::
def offset(width, height, xdescent, ydescent, renderer) \
-> (float, float)
"""
self._offset = xy
self.stale = True
def get_offset(self, width, height, xdescent, ydescent, renderer):
"""
Get the offset
accepts extent of the box
"""
return (self._offset(width, height, xdescent, ydescent, renderer)
if callable(self._offset)
else self._offset)
def set_width(self, width):
"""
Set the width
accepts float
"""
self.width = width
self.stale = True
def set_height(self, height):
"""
Set the height
accepts float
"""
self.height = height
self.stale = True
def get_visible_children(self):
"""
Return a list of visible artists it contains.
"""
return [c for c in self._children if c.get_visible()]
def get_children(self):
"""
Return a list of artists it contains.
"""
return self._children
def get_extent_offsets(self, renderer):
raise Exception("")
def get_extent(self, renderer):
"""
Return with, height, xdescent, ydescent of box
"""
w, h, xd, yd, offsets = self.get_extent_offsets(renderer)
return w, h, xd, yd
def get_window_extent(self, renderer):
'''
get the bounding box in display space.
'''
w, h, xd, yd, offsets = self.get_extent_offsets(renderer)
px, py = self.get_offset(w, h, xd, yd, renderer)
return mtransforms.Bbox.from_bounds(px - xd, py - yd, w, h)
def draw(self, renderer):
"""
Update the location of children if necessary and draw them
to the given *renderer*.
"""
width, height, xdescent, ydescent, offsets = self.get_extent_offsets(
renderer)
px, py = self.get_offset(width, height, xdescent, ydescent, renderer)
for c, (ox, oy) in zip(self.get_visible_children(), offsets):
c.set_offset((px + ox, py + oy))
c.draw(renderer)
bbox_artist(self, renderer, fill=False, props=dict(pad=0.))
self.stale = False
class PackerBase(OffsetBox):
def __init__(self, pad=None, sep=None, width=None, height=None,
align=None, mode=None,
children=None):
"""
Parameters
----------
pad : float, optional
Boundary pad.
sep : float, optional
Spacing between items.
width : float, optional
height : float, optional
Width and height of the container box, calculated if
`None`.
align : str, optional
Alignment of boxes. Can be one of ``top``, ``bottom``,
``left``, ``right``, ``center`` and ``baseline``
mode : str, optional
Packing mode.
Notes
-----
*pad* and *sep* need to given in points and will be scale with
the renderer dpi, while *width* and *height* need to be in
pixels.
"""
super().__init__()
self.height = height
self.width = width
self.sep = sep
self.pad = pad
self.mode = mode
self.align = align
self._children = children
class VPacker(PackerBase):
"""
The VPacker has its children packed vertically. It automatically
adjust the relative positions of children in the drawing time.
"""
def __init__(self, pad=None, sep=None, width=None, height=None,
align="baseline", mode="fixed",
children=None):
"""
Parameters
----------
pad : float, optional
Boundary pad.
sep : float, optional
Spacing between items.
width : float, optional
height : float, optional
width and height of the container box, calculated if
`None`.
align : str, optional
Alignment of boxes.
mode : str, optional
Packing mode.
Notes
-----
*pad* and *sep* need to given in points and will be scale with
the renderer dpi, while *width* and *height* need to be in
pixels.
"""
super().__init__(pad, sep, width, height, align, mode, children)
def get_extent_offsets(self, renderer):
"""
update offset of childrens and return the extents of the box
"""
dpicor = renderer.points_to_pixels(1.)
pad = self.pad * dpicor
sep = self.sep * dpicor
if self.width is not None:
for c in self.get_visible_children():
if isinstance(c, PackerBase) and c.mode == "expand":
c.set_width(self.width)
whd_list = [c.get_extent(renderer)
for c in self.get_visible_children()]
whd_list = [(w, h, xd, (h - yd)) for w, h, xd, yd in whd_list]
wd_list = [(w, xd) for w, h, xd, yd in whd_list]
width, xdescent, xoffsets = _get_aligned_offsets(wd_list,
self.width,
self.align)
pack_list = [(h, yd) for w, h, xd, yd in whd_list]
height, yoffsets_ = _get_packed_offsets(pack_list, self.height,
sep, self.mode)
yoffsets = yoffsets_ + [yd for w, h, xd, yd in whd_list]
ydescent = height - yoffsets[0]
yoffsets = height - yoffsets
yoffsets = yoffsets - ydescent
return (width + 2 * pad, height + 2 * pad,
xdescent + pad, ydescent + pad,
list(zip(xoffsets, yoffsets)))
class HPacker(PackerBase):
"""
The HPacker has its children packed horizontally. It automatically
adjusts the relative positions of children at draw time.
"""
def __init__(self, pad=None, sep=None, width=None, height=None,
align="baseline", mode="fixed",
children=None):
"""
Parameters
----------
pad : float, optional
Boundary pad.
sep : float, optional
Spacing between items.
width : float, optional
height : float, optional
Width and height of the container box, calculated if
`None`.
align : str
Alignment of boxes.
mode : str
Packing mode.
Notes
-----
*pad* and *sep* need to given in points and will be scale with
the renderer dpi, while *width* and *height* need to be in
pixels.
"""
super().__init__(pad, sep, width, height, align, mode, children)
def get_extent_offsets(self, renderer):
"""
update offset of children and return the extents of the box
"""
dpicor = renderer.points_to_pixels(1.)
pad = self.pad * dpicor
sep = self.sep * dpicor
whd_list = [c.get_extent(renderer)
for c in self.get_visible_children()]
if not whd_list:
return 2 * pad, 2 * pad, pad, pad, []
if self.height is None:
height_descent = max(h - yd for w, h, xd, yd in whd_list)
ydescent = max(yd for w, h, xd, yd in whd_list)
height = height_descent + ydescent
else:
height = self.height - 2 * pad # width w/o pad
hd_list = [(h, yd) for w, h, xd, yd in whd_list]
height, ydescent, yoffsets = _get_aligned_offsets(hd_list,
self.height,
self.align)
pack_list = [(w, xd) for w, h, xd, yd in whd_list]
width, xoffsets_ = _get_packed_offsets(pack_list, self.width,
sep, self.mode)
xoffsets = xoffsets_ + [xd for w, h, xd, yd in whd_list]
xdescent = whd_list[0][2]
xoffsets = xoffsets - xdescent
return (width + 2 * pad, height + 2 * pad,
xdescent + pad, ydescent + pad,
list(zip(xoffsets, yoffsets)))
class PaddedBox(OffsetBox):
def __init__(self, child, pad=None, draw_frame=False, patch_attrs=None):
"""
*pad* : boundary pad
.. note::
*pad* need to given in points and will be
scale with the renderer dpi, while *width* and *height*
need to be in pixels.
"""
super().__init__()
self.pad = pad
self._children = [child]
self.patch = FancyBboxPatch(
xy=(0.0, 0.0), width=1., height=1.,
facecolor='w', edgecolor='k',
mutation_scale=1, # self.prop.get_size_in_points(),
snap=True
)
self.patch.set_boxstyle("square", pad=0)
if patch_attrs is not None:
self.patch.update(patch_attrs)
self._drawFrame = draw_frame
def get_extent_offsets(self, renderer):
"""
update offset of childrens and return the extents of the box
"""
dpicor = renderer.points_to_pixels(1.)
pad = self.pad * dpicor
w, h, xd, yd = self._children[0].get_extent(renderer)
return w + 2 * pad, h + 2 * pad, \
xd + pad, yd + pad, \
[(0, 0)]
def draw(self, renderer):
"""
Update the location of children if necessary and draw them
to the given *renderer*.
"""
width, height, xdescent, ydescent, offsets = self.get_extent_offsets(
renderer)
px, py = self.get_offset(width, height, xdescent, ydescent, renderer)
for c, (ox, oy) in zip(self.get_visible_children(), offsets):
c.set_offset((px + ox, py + oy))
self.draw_frame(renderer)
for c in self.get_visible_children():
c.draw(renderer)
#bbox_artist(self, renderer, fill=False, props=dict(pad=0.))
self.stale = False
def update_frame(self, bbox, fontsize=None):
self.patch.set_bounds(bbox.x0, bbox.y0,
bbox.width, bbox.height)
if fontsize:
self.patch.set_mutation_scale(fontsize)
self.stale = True
def draw_frame(self, renderer):
# update the location and size of the legend
bbox = self.get_window_extent(renderer)
self.update_frame(bbox)
if self._drawFrame:
self.patch.draw(renderer)
class DrawingArea(OffsetBox):
"""
The DrawingArea can contain any Artist as a child. The DrawingArea
has a fixed width and height. The position of children relative to
the parent is fixed. The children can be clipped at the
boundaries of the parent.
"""
def __init__(self, width, height, xdescent=0.,
ydescent=0., clip=False):
"""
*width*, *height* : width and height of the container box.
*xdescent*, *ydescent* : descent of the box in x- and y-direction.
*clip* : Whether to clip the children
"""
super().__init__()
self.width = width
self.height = height
self.xdescent = xdescent
self.ydescent = ydescent
self._clip_children = clip
self.offset_transform = mtransforms.Affine2D()
self.offset_transform.clear()
self.offset_transform.translate(0, 0)
self.dpi_transform = mtransforms.Affine2D()
@property
def clip_children(self):
"""
If the children of this DrawingArea should be clipped
by DrawingArea bounding box.
"""
return self._clip_children
@clip_children.setter
def clip_children(self, val):
self._clip_children = bool(val)
self.stale = True
def get_transform(self):
"""
Return the :class:`~matplotlib.transforms.Transform` applied
to the children
"""
return self.dpi_transform + self.offset_transform
def set_transform(self, t):
"""
set_transform is ignored.
"""
pass
def set_offset(self, xy):
"""
Set the offset of the container.
Parameters
----------
xy : (float, float)
The (x,y) coordinates of the offset in display units.
"""
self._offset = xy
self.offset_transform.clear()
self.offset_transform.translate(xy[0], xy[1])
self.stale = True
def get_offset(self):
"""
return offset of the container.
"""
return self._offset
def get_window_extent(self, renderer):
'''
get the bounding box in display space.
'''
w, h, xd, yd = self.get_extent(renderer)
ox, oy = self.get_offset() # w, h, xd, yd)
return mtransforms.Bbox.from_bounds(ox - xd, oy - yd, w, h)
def get_extent(self, renderer):
"""
Return with, height, xdescent, ydescent of box
"""
dpi_cor = renderer.points_to_pixels(1.)
return self.width * dpi_cor, self.height * dpi_cor, \
self.xdescent * dpi_cor, self.ydescent * dpi_cor
def add_artist(self, a):
'Add any :class:`~matplotlib.artist.Artist` to the container box'
self._children.append(a)
if not a.is_transform_set():
a.set_transform(self.get_transform())
if self.axes is not None:
a.axes = self.axes
fig = self.figure
if fig is not None:
a.set_figure(fig)
def draw(self, renderer):
"""
Draw the children
"""
dpi_cor = renderer.points_to_pixels(1.)
self.dpi_transform.clear()
self.dpi_transform.scale(dpi_cor, dpi_cor)
# At this point the DrawingArea has a transform
# to the display space so the path created is
# good for clipping children
tpath = mtransforms.TransformedPath(
mpath.Path([[0, 0], [0, self.height],
[self.width, self.height],
[self.width, 0]]),
self.get_transform())
for c in self._children:
if self._clip_children and not (c.clipbox or c._clippath):
c.set_clip_path(tpath)
c.draw(renderer)
bbox_artist(self, renderer, fill=False, props=dict(pad=0.))
self.stale = False
class TextArea(OffsetBox):
"""
The TextArea is contains a single Text instance. The text is
placed at (0,0) with baseline+left alignment. The width and height
of the TextArea instance is the width and height of the its child
text.
"""
def __init__(self, s,
textprops=None,
multilinebaseline=None,
minimumdescent=True,
):
"""
Parameters
----------
s : str
a string to be displayed.
textprops : dictionary, optional, default: None
Dictionary of keyword parameters to be passed to the
`~matplotlib.text.Text` instance contained inside TextArea.
multilinebaseline : bool, optional
If `True`, baseline for multiline text is adjusted so that it is
(approximately) center-aligned with singleline text.
minimumdescent : bool, optional
If `True`, the box has a minimum descent of "p".
"""
if textprops is None:
textprops = {}
if "va" not in textprops:
textprops["va"] = "baseline"
self._text = mtext.Text(0, 0, s, **textprops)
OffsetBox.__init__(self)
self._children = [self._text]
self.offset_transform = mtransforms.Affine2D()
self.offset_transform.clear()
self.offset_transform.translate(0, 0)
self._baseline_transform = mtransforms.Affine2D()
self._text.set_transform(self.offset_transform +
self._baseline_transform)
self._multilinebaseline = multilinebaseline
self._minimumdescent = minimumdescent
def set_text(self, s):
"Set the text of this area as a string."
self._text.set_text(s)
self.stale = True
def get_text(self):
"Returns the string representation of this area's text"
return self._text.get_text()
def set_multilinebaseline(self, t):
"""
Set multilinebaseline .
If True, baseline for multiline text is adjusted so that it is
(approximately) center-aligned with single-line text.
"""
self._multilinebaseline = t
self.stale = True
def get_multilinebaseline(self):
"""
get multilinebaseline .
"""
return self._multilinebaseline
def set_minimumdescent(self, t):
"""
Set minimumdescent .
If True, extent of the single line text is adjusted so that
it has minimum descent of "p"
"""
self._minimumdescent = t
self.stale = True
def get_minimumdescent(self):
"""
get minimumdescent.
"""
return self._minimumdescent
def set_transform(self, t):
"""
set_transform is ignored.
"""
pass
def set_offset(self, xy):
"""
Set the offset of the container.
Parameters
----------
xy : (float, float)
The (x,y) coordinates of the offset in display units.
"""
self._offset = xy
self.offset_transform.clear()
self.offset_transform.translate(xy[0], xy[1])
self.stale = True
def get_offset(self):
"""
return offset of the container.
"""
return self._offset
def get_window_extent(self, renderer):
'''
get the bounding box in display space.
'''
w, h, xd, yd = self.get_extent(renderer)
ox, oy = self.get_offset() # w, h, xd, yd)
return mtransforms.Bbox.from_bounds(ox - xd, oy - yd, w, h)
def get_extent(self, renderer):
_, h_, d_ = renderer.get_text_width_height_descent(
"lp", self._text._fontproperties, ismath=False)
bbox, info, d = self._text._get_layout(renderer)
w, h = bbox.width, bbox.height
self._baseline_transform.clear()
if len(info) > 1 and self._multilinebaseline:
d_new = 0.5 * h - 0.5 * (h_ - d_)
self._baseline_transform.translate(0, d - d_new)
d = d_new
else: # single line
h_d = max(h_ - d_, h - d)
if self.get_minimumdescent():
## to have a minimum descent, #i.e., "l" and "p" have same
## descents.
d = max(d, d_)
#else:
# d = d
h = h_d + d
return w, h, 0., d
def draw(self, renderer):
"""
Draw the children
"""
self._text.draw(renderer)
bbox_artist(self, renderer, fill=False, props=dict(pad=0.))
self.stale = False
class AuxTransformBox(OffsetBox):
"""
Offset Box with the aux_transform. Its children will be
transformed with the aux_transform first then will be
offseted. The absolute coordinate of the aux_transform is meaning
as it will be automatically adjust so that the left-lower corner
of the bounding box of children will be set to (0,0) before the
offset transform.
It is similar to drawing area, except that the extent of the box
is not predetermined but calculated from the window extent of its
children. Furthermore, the extent of the children will be
calculated in the transformed coordinate.
"""
def __init__(self, aux_transform):
self.aux_transform = aux_transform
OffsetBox.__init__(self)
self.offset_transform = mtransforms.Affine2D()
self.offset_transform.clear()
self.offset_transform.translate(0, 0)
# ref_offset_transform is used to make the offset_transform is
# always reference to the lower-left corner of the bbox of its
# children.
self.ref_offset_transform = mtransforms.Affine2D()
self.ref_offset_transform.clear()
def add_artist(self, a):
'Add any :class:`~matplotlib.artist.Artist` to the container box'
self._children.append(a)
a.set_transform(self.get_transform())
self.stale = True
def get_transform(self):
"""
Return the :class:`~matplotlib.transforms.Transform` applied
to the children
"""
return self.aux_transform + \
self.ref_offset_transform + \
self.offset_transform
def set_transform(self, t):
"""
set_transform is ignored.
"""
pass
def set_offset(self, xy):
"""
Set the offset of the container.
Parameters
----------
xy : (float, float)
The (x,y) coordinates of the offset in display units.
"""
self._offset = xy
self.offset_transform.clear()
self.offset_transform.translate(xy[0], xy[1])
self.stale = True
def get_offset(self):
"""
return offset of the container.
"""
return self._offset
def get_window_extent(self, renderer):
'''
get the bounding box in display space.
'''
w, h, xd, yd = self.get_extent(renderer)
ox, oy = self.get_offset() # w, h, xd, yd)
return mtransforms.Bbox.from_bounds(ox - xd, oy - yd, w, h)
def get_extent(self, renderer):
# clear the offset transforms
_off = self.offset_transform.to_values() # to be restored later
self.ref_offset_transform.clear()
self.offset_transform.clear()
# calculate the extent
bboxes = [c.get_window_extent(renderer) for c in self._children]
ub = mtransforms.Bbox.union(bboxes)
# adjust ref_offset_transform
self.ref_offset_transform.translate(-ub.x0, -ub.y0)
# restor offset transform
mtx = self.offset_transform.matrix_from_values(*_off)
self.offset_transform.set_matrix(mtx)
return ub.width, ub.height, 0., 0.
def draw(self, renderer):
"""
Draw the children
"""
for c in self._children:
c.draw(renderer)
bbox_artist(self, renderer, fill=False, props=dict(pad=0.))
self.stale = False
class AnchoredOffsetbox(OffsetBox):
"""
An offset box placed according to the legend location
loc. AnchoredOffsetbox has a single child. When multiple children
is needed, use other OffsetBox class to enclose them. By default,
the offset box is anchored against its parent axes. You may
explicitly specify the bbox_to_anchor.
"""
zorder = 5 # zorder of the legend
# Location codes
codes = {'upper right': 1,
'upper left': 2,
'lower left': 3,
'lower right': 4,
'right': 5,
'center left': 6,
'center right': 7,
'lower center': 8,
'upper center': 9,
'center': 10,
}
def __init__(self, loc,
pad=0.4, borderpad=0.5,
child=None, prop=None, frameon=True,
bbox_to_anchor=None,
bbox_transform=None,
**kwargs):
"""
loc is a string or an integer specifying the legend location.
The valid location codes are::
'upper right' : 1,
'upper left' : 2,
'lower left' : 3,
'lower right' : 4,
'right' : 5, (same as 'center right', for back-compatibility)
'center left' : 6,
'center right' : 7,
'lower center' : 8,
'upper center' : 9,
'center' : 10,
pad : pad around the child for drawing a frame. given in
fraction of fontsize.
borderpad : pad between offsetbox frame and the bbox_to_anchor,
child : OffsetBox instance that will be anchored.
prop : font property. This is only used as a reference for paddings.
frameon : draw a frame box if True.
bbox_to_anchor : bbox to anchor. Use self.axes.bbox if None.
bbox_transform : with which the bbox_to_anchor will be transformed.
"""
super().__init__(**kwargs)
self.set_bbox_to_anchor(bbox_to_anchor, bbox_transform)
self.set_child(child)
if isinstance(loc, str):
try:
loc = self.codes[loc]
except KeyError:
raise ValueError('Unrecognized location "%s". Valid '
'locations are\n\t%s\n'
% (loc, '\n\t'.join(self.codes)))
self.loc = loc
self.borderpad = borderpad
self.pad = pad
if prop is None:
self.prop = FontProperties(size=rcParams["legend.fontsize"])
elif isinstance(prop, dict):
self.prop = FontProperties(**prop)
if "size" not in prop:
self.prop.set_size(rcParams["legend.fontsize"])
else:
self.prop = prop
self.patch = FancyBboxPatch(
xy=(0.0, 0.0), width=1., height=1.,
facecolor='w', edgecolor='k',
mutation_scale=self.prop.get_size_in_points(),
snap=True
)
self.patch.set_boxstyle("square", pad=0)
self._drawFrame = frameon
def set_child(self, child):
"set the child to be anchored"
self._child = child
if child is not None:
child.axes = self.axes
self.stale = True
def get_child(self):
"return the child"
return self._child
def get_children(self):
"return the list of children"
return [self._child]
def get_extent(self, renderer):
"""
return the extent of the artist. The extent of the child
added with the pad is returned
"""
w, h, xd, yd = self.get_child().get_extent(renderer)
fontsize = renderer.points_to_pixels(self.prop.get_size_in_points())
pad = self.pad * fontsize
return w + 2 * pad, h + 2 * pad, xd + pad, yd + pad
def get_bbox_to_anchor(self):
"""
return the bbox that the legend will be anchored
"""
if self._bbox_to_anchor is None:
return self.axes.bbox
else:
transform = self._bbox_to_anchor_transform
if transform is None:
return self._bbox_to_anchor
else:
return TransformedBbox(self._bbox_to_anchor,
transform)
def set_bbox_to_anchor(self, bbox, transform=None):
"""
set the bbox that the child will be anchored.
*bbox* can be a Bbox instance, a list of [left, bottom, width,
height], or a list of [left, bottom] where the width and
height will be assumed to be zero. The bbox will be
transformed to display coordinate by the given transform.
"""
if bbox is None or isinstance(bbox, BboxBase):
self._bbox_to_anchor = bbox
else:
try:
l = len(bbox)
except TypeError:
raise ValueError("Invalid argument for bbox : %s" % str(bbox))
if l == 2:
bbox = [bbox[0], bbox[1], 0, 0]
self._bbox_to_anchor = Bbox.from_bounds(*bbox)
self._bbox_to_anchor_transform = transform
self.stale = True
def get_window_extent(self, renderer):
'''
get the bounding box in display space.
'''
self._update_offset_func(renderer)
w, h, xd, yd = self.get_extent(renderer)
ox, oy = self.get_offset(w, h, xd, yd, renderer)
return Bbox.from_bounds(ox - xd, oy - yd, w, h)
def _update_offset_func(self, renderer, fontsize=None):
"""
Update the offset func which depends on the dpi of the
renderer (because of the padding).
"""
if fontsize is None:
fontsize = renderer.points_to_pixels(
self.prop.get_size_in_points())
def _offset(w, h, xd, yd, renderer, fontsize=fontsize, self=self):
bbox = Bbox.from_bounds(0, 0, w, h)
borderpad = self.borderpad * fontsize
bbox_to_anchor = self.get_bbox_to_anchor()
x0, y0 = self._get_anchored_bbox(self.loc,
bbox,
bbox_to_anchor,
borderpad)
return x0 + xd, y0 + yd
self.set_offset(_offset)
def update_frame(self, bbox, fontsize=None):
self.patch.set_bounds(bbox.x0, bbox.y0,
bbox.width, bbox.height)
if fontsize:
self.patch.set_mutation_scale(fontsize)
def draw(self, renderer):
"draw the artist"
if not self.get_visible():
return
fontsize = renderer.points_to_pixels(self.prop.get_size_in_points())
self._update_offset_func(renderer, fontsize)
if self._drawFrame:
# update the location and size of the legend
bbox = self.get_window_extent(renderer)
self.update_frame(bbox, fontsize)
self.patch.draw(renderer)
width, height, xdescent, ydescent = self.get_extent(renderer)
px, py = self.get_offset(width, height, xdescent, ydescent, renderer)
self.get_child().set_offset((px, py))
self.get_child().draw(renderer)
self.stale = False
def _get_anchored_bbox(self, loc, bbox, parentbbox, borderpad):
"""
return the position of the bbox anchored at the parentbbox
with the loc code, with the borderpad.
"""
assert loc in range(1, 11) # called only internally
BEST, UR, UL, LL, LR, R, CL, CR, LC, UC, C = range(11)
anchor_coefs = {UR: "NE",
UL: "NW",
LL: "SW",
LR: "SE",
R: "E",
CL: "W",
CR: "E",
LC: "S",
UC: "N",
C: "C"}
c = anchor_coefs[loc]
container = parentbbox.padded(-borderpad)
anchored_box = bbox.anchored(c, container=container)
return anchored_box.x0, anchored_box.y0
class AnchoredText(AnchoredOffsetbox):
"""
AnchoredOffsetbox with Text.
"""
def __init__(self, s, loc, pad=0.4, borderpad=0.5, prop=None, **kwargs):
"""
Parameters
----------
s : string
Text.
loc : str
Location code.
pad : float, optional
Pad between the text and the frame as fraction of the font
size.
borderpad : float, optional
Pad between the frame and the axes (or *bbox_to_anchor*).
prop : dictionary, optional, default: None
Dictionary of keyword parameters to be passed to the
`~matplotlib.text.Text` instance contained inside AnchoredText.
Notes
-----
Other keyword parameters of `AnchoredOffsetbox` are also
allowed.
"""
if prop is None:
prop = {}
badkwargs = {'ha', 'horizontalalignment', 'va', 'verticalalignment'}
if badkwargs & set(prop):
cbook.warn_deprecated(
"3.1", message="Mixing horizontalalignment or "
"verticalalignment with AnchoredText is not supported, "
"deprecated since %(version)s, and will raise an exception "
"%(removal)s.")
self.txt = TextArea(s, textprops=prop, minimumdescent=False)
fp = self.txt._text.get_fontproperties()
super().__init__(
loc, pad=pad, borderpad=borderpad, child=self.txt, prop=fp,
**kwargs)
class OffsetImage(OffsetBox):
def __init__(self, arr,
zoom=1,
cmap=None,
norm=None,
interpolation=None,
origin=None,
filternorm=1,
filterrad=4.0,
resample=False,
dpi_cor=True,
**kwargs
):
OffsetBox.__init__(self)
self._dpi_cor = dpi_cor
self.image = BboxImage(bbox=self.get_window_extent,
cmap=cmap,
norm=norm,
interpolation=interpolation,
origin=origin,
filternorm=filternorm,
filterrad=filterrad,
resample=resample,
**kwargs
)
self._children = [self.image]
self.set_zoom(zoom)
self.set_data(arr)
def set_data(self, arr):
self._data = np.asarray(arr)
self.image.set_data(self._data)
self.stale = True
def get_data(self):
return self._data
def set_zoom(self, zoom):
self._zoom = zoom
self.stale = True
def get_zoom(self):
return self._zoom
# def set_axes(self, axes):
# self.image.set_axes(axes)
# martist.Artist.set_axes(self, axes)
# def set_offset(self, xy):
# """
# Set the offset of the container.
#
# Parameters
# ----------
# xy : (float, float)
# The (x,y) coordinates of the offset in display units.
# """
# self._offset = xy
# self.offset_transform.clear()
# self.offset_transform.translate(xy[0], xy[1])
def get_offset(self):
"""
return offset of the container.
"""
return self._offset
def get_children(self):
return [self.image]
def get_window_extent(self, renderer):
'''
get the bounding box in display space.
'''
w, h, xd, yd = self.get_extent(renderer)
ox, oy = self.get_offset()
return mtransforms.Bbox.from_bounds(ox - xd, oy - yd, w, h)
def get_extent(self, renderer):
if self._dpi_cor: # True, do correction
dpi_cor = renderer.points_to_pixels(1.)
else:
dpi_cor = 1.
zoom = self.get_zoom()
data = self.get_data()
ny, nx = data.shape[:2]
w, h = dpi_cor * nx * zoom, dpi_cor * ny * zoom
return w, h, 0, 0
def draw(self, renderer):
"""
Draw the children
"""
self.image.draw(renderer)
# bbox_artist(self, renderer, fill=False, props=dict(pad=0.))
self.stale = False
class AnnotationBbox(martist.Artist, _AnnotationBase):
"""
Annotation-like class, but with offsetbox instead of Text.
"""
zorder = 3
def __str__(self):
return "AnnotationBbox(%g,%g)" % (self.xy[0], self.xy[1])
@docstring.dedent_interpd
def __init__(self, offsetbox, xy,
xybox=None,
xycoords='data',
boxcoords=None,
frameon=True, pad=0.4, # BboxPatch
annotation_clip=None,
box_alignment=(0.5, 0.5),
bboxprops=None,
arrowprops=None,
fontsize=None,
**kwargs):
"""
*offsetbox* : OffsetBox instance
*xycoords* : same as Annotation but can be a tuple of two
strings which are interpreted as x and y coordinates.
*boxcoords* : similar to textcoords as Annotation but can be a
tuple of two strings which are interpreted as x and y
coordinates.
*box_alignment* : a tuple of two floats for a vertical and
horizontal alignment of the offset box w.r.t. the *boxcoords*.
The lower-left corner is (0.0) and upper-right corner is (1.1).
other parameters are identical to that of Annotation.
"""
martist.Artist.__init__(self, **kwargs)
_AnnotationBase.__init__(self,
xy,
xycoords=xycoords,
annotation_clip=annotation_clip)
self.offsetbox = offsetbox
self.arrowprops = arrowprops
self.set_fontsize(fontsize)
if xybox is None:
self.xybox = xy
else:
self.xybox = xybox
if boxcoords is None:
self.boxcoords = xycoords
else:
self.boxcoords = boxcoords
if arrowprops is not None:
self._arrow_relpos = self.arrowprops.pop("relpos", (0.5, 0.5))
self.arrow_patch = FancyArrowPatch((0, 0), (1, 1),
**self.arrowprops)
else:
self._arrow_relpos = None
self.arrow_patch = None
self._box_alignment = box_alignment
# frame
self.patch = FancyBboxPatch(
xy=(0.0, 0.0), width=1., height=1.,
facecolor='w', edgecolor='k',
mutation_scale=self.prop.get_size_in_points(),
snap=True
)
self.patch.set_boxstyle("square", pad=pad)
if bboxprops:
self.patch.set(**bboxprops)
self._drawFrame = frameon
@property
def xyann(self):
return self.xybox
@xyann.setter
def xyann(self, xyann):
self.xybox = xyann
self.stale = True
@property
def anncoords(self):
return self.boxcoords
@anncoords.setter
def anncoords(self, coords):
self.boxcoords = coords
self.stale = True
def contains(self, event):
t, tinfo = self.offsetbox.contains(event)
#if self.arrow_patch is not None:
# a,ainfo=self.arrow_patch.contains(event)
# t = t or a
# self.arrow_patch is currently not checked as this can be a line - JJ
return t, tinfo
def get_children(self):
children = [self.offsetbox, self.patch]
if self.arrow_patch:
children.append(self.arrow_patch)
return children
def set_figure(self, fig):
if self.arrow_patch is not None:
self.arrow_patch.set_figure(fig)
self.offsetbox.set_figure(fig)
martist.Artist.set_figure(self, fig)
def set_fontsize(self, s=None):
"""
set fontsize in points
"""
if s is None:
s = rcParams["legend.fontsize"]
self.prop = FontProperties(size=s)
self.stale = True
def get_fontsize(self, s=None):
"""
return fontsize in points
"""
return self.prop.get_size_in_points()
def update_positions(self, renderer):
"""
Update the pixel positions of the annotated point and the text.
"""
xy_pixel = self._get_position_xy(renderer)
self._update_position_xybox(renderer, xy_pixel)
mutation_scale = renderer.points_to_pixels(self.get_fontsize())
self.patch.set_mutation_scale(mutation_scale)
if self.arrow_patch:
self.arrow_patch.set_mutation_scale(mutation_scale)
def _update_position_xybox(self, renderer, xy_pixel):
"""
Update the pixel positions of the annotation text and the arrow
patch.
"""
x, y = self.xybox
if isinstance(self.boxcoords, tuple):
xcoord, ycoord = self.boxcoords
x1, y1 = self._get_xy(renderer, x, y, xcoord)
x2, y2 = self._get_xy(renderer, x, y, ycoord)
ox0, oy0 = x1, y2
else:
ox0, oy0 = self._get_xy(renderer, x, y, self.boxcoords)
w, h, xd, yd = self.offsetbox.get_extent(renderer)
_fw, _fh = self._box_alignment
self.offsetbox.set_offset((ox0 - _fw * w + xd, oy0 - _fh * h + yd))
# update patch position
bbox = self.offsetbox.get_window_extent(renderer)
#self.offsetbox.set_offset((ox0-_fw*w, oy0-_fh*h))
self.patch.set_bounds(bbox.x0, bbox.y0,
bbox.width, bbox.height)
x, y = xy_pixel
ox1, oy1 = x, y
if self.arrowprops:
d = self.arrowprops.copy()
# Use FancyArrowPatch if self.arrowprops has "arrowstyle" key.
# adjust the starting point of the arrow relative to
# the textbox.
# TODO : Rotation needs to be accounted.
relpos = self._arrow_relpos
ox0 = bbox.x0 + bbox.width * relpos[0]
oy0 = bbox.y0 + bbox.height * relpos[1]
# The arrow will be drawn from (ox0, oy0) to (ox1,
# oy1). It will be first clipped by patchA and patchB.
# Then it will be shrunk by shrinkA and shrinkB
# (in points). If patch A is not set, self.bbox_patch
# is used.
self.arrow_patch.set_positions((ox0, oy0), (ox1, oy1))
fs = self.prop.get_size_in_points()
mutation_scale = d.pop("mutation_scale", fs)
mutation_scale = renderer.points_to_pixels(mutation_scale)
self.arrow_patch.set_mutation_scale(mutation_scale)
patchA = d.pop("patchA", self.patch)
self.arrow_patch.set_patchA(patchA)
def draw(self, renderer):
"""
Draw the :class:`Annotation` object to the given *renderer*.
"""
if renderer is not None:
self._renderer = renderer
if not self.get_visible():
return
xy_pixel = self._get_position_xy(renderer)
if not self._check_xy(renderer, xy_pixel):
return
self.update_positions(renderer)
if self.arrow_patch is not None:
if self.arrow_patch.figure is None and self.figure is not None:
self.arrow_patch.figure = self.figure
self.arrow_patch.draw(renderer)
if self._drawFrame:
self.patch.draw(renderer)
self.offsetbox.draw(renderer)
self.stale = False
class DraggableBase(object):
"""
helper code for a draggable artist (legend, offsetbox)
The derived class must override following two method.
def save_offset(self):
pass
def update_offset(self, dx, dy):
pass
*save_offset* is called when the object is picked for dragging and it
is meant to save reference position of the artist.
*update_offset* is called during the dragging. dx and dy is the pixel
offset from the point where the mouse drag started.
Optionally you may override following two methods.
def artist_picker(self, artist, evt):
return self.ref_artist.contains(evt)
def finalize_offset(self):
pass
*artist_picker* is a picker method that will be
used. *finalize_offset* is called when the mouse is released. In
current implementation of DraggableLegend and DraggableAnnotation,
*update_offset* places the artists simply in display
coordinates. And *finalize_offset* recalculate their position in
the normalized axes coordinate and set a relevant attribute.
"""
def __init__(self, ref_artist, use_blit=False):
self.ref_artist = ref_artist
self.got_artist = False
self.canvas = self.ref_artist.figure.canvas
self._use_blit = use_blit and self.canvas.supports_blit
c2 = self.canvas.mpl_connect('pick_event', self.on_pick)
c3 = self.canvas.mpl_connect('button_release_event', self.on_release)
ref_artist.set_picker(self.artist_picker)
self.cids = [c2, c3]
def on_motion(self, evt):
if self._check_still_parented() and self.got_artist:
dx = evt.x - self.mouse_x
dy = evt.y - self.mouse_y
self.update_offset(dx, dy)
self.canvas.draw()
def on_motion_blit(self, evt):
if self._check_still_parented() and self.got_artist:
dx = evt.x - self.mouse_x
dy = evt.y - self.mouse_y
self.update_offset(dx, dy)
self.canvas.restore_region(self.background)
self.ref_artist.draw(self.ref_artist.figure._cachedRenderer)
self.canvas.blit(self.ref_artist.figure.bbox)
def on_pick(self, evt):
if self._check_still_parented() and evt.artist == self.ref_artist:
self.mouse_x = evt.mouseevent.x
self.mouse_y = evt.mouseevent.y
self.got_artist = True
if self._use_blit:
self.ref_artist.set_animated(True)
self.canvas.draw()
self.background = self.canvas.copy_from_bbox(
self.ref_artist.figure.bbox)
self.ref_artist.draw(self.ref_artist.figure._cachedRenderer)
self.canvas.blit(self.ref_artist.figure.bbox)
self._c1 = self.canvas.mpl_connect('motion_notify_event',
self.on_motion_blit)
else:
self._c1 = self.canvas.mpl_connect('motion_notify_event',
self.on_motion)
self.save_offset()
def on_release(self, event):
if self._check_still_parented() and self.got_artist:
self.finalize_offset()
self.got_artist = False
self.canvas.mpl_disconnect(self._c1)
if self._use_blit:
self.ref_artist.set_animated(False)
def _check_still_parented(self):
if self.ref_artist.figure is None:
self.disconnect()
return False
else:
return True
def disconnect(self):
"""disconnect the callbacks"""
for cid in self.cids:
self.canvas.mpl_disconnect(cid)
try:
c1 = self._c1
except AttributeError:
pass
else:
self.canvas.mpl_disconnect(c1)
def artist_picker(self, artist, evt):
return self.ref_artist.contains(evt)
def save_offset(self):
pass
def update_offset(self, dx, dy):
pass
def finalize_offset(self):
pass
class DraggableOffsetBox(DraggableBase):
def __init__(self, ref_artist, offsetbox, use_blit=False):
DraggableBase.__init__(self, ref_artist, use_blit=use_blit)
self.offsetbox = offsetbox
def save_offset(self):
offsetbox = self.offsetbox
renderer = offsetbox.figure._cachedRenderer
w, h, xd, yd = offsetbox.get_extent(renderer)
offset = offsetbox.get_offset(w, h, xd, yd, renderer)
self.offsetbox_x, self.offsetbox_y = offset
self.offsetbox.set_offset(offset)
def update_offset(self, dx, dy):
loc_in_canvas = self.offsetbox_x + dx, self.offsetbox_y + dy
self.offsetbox.set_offset(loc_in_canvas)
def get_loc_in_canvas(self):
offsetbox = self.offsetbox
renderer = offsetbox.figure._cachedRenderer
w, h, xd, yd = offsetbox.get_extent(renderer)
ox, oy = offsetbox._offset
loc_in_canvas = (ox - xd, oy - yd)
return loc_in_canvas
class DraggableAnnotation(DraggableBase):
def __init__(self, annotation, use_blit=False):
DraggableBase.__init__(self, annotation, use_blit=use_blit)
self.annotation = annotation
def save_offset(self):
ann = self.annotation
self.ox, self.oy = ann.get_transform().transform(ann.xyann)
def update_offset(self, dx, dy):
ann = self.annotation
ann.xyann = ann.get_transform().inverted().transform(
(self.ox + dx, self.oy + dy))
|
19790ccf1699ac97a68463c89ad906551a99e5cccfd55039977e643570f78823
|
r"""
A module for dealing with the polylines used throughout Matplotlib.
The primary class for polyline handling in Matplotlib is `Path`. Almost all
vector drawing makes use of `Path`\s somewhere in the drawing pipeline.
Whilst a `Path` instance itself cannot be drawn, some `.Artist` subclasses,
such as `.PathPatch` and `.PathCollection`, can be used for convenient `Path`
visualisation.
"""
from functools import lru_cache
from weakref import WeakValueDictionary
import numpy as np
from . import _path, cbook, rcParams
from .cbook import _to_unmasked_float_array, simple_linear_interpolation
class Path(object):
"""
:class:`Path` represents a series of possibly disconnected,
possibly closed, line and curve segments.
The underlying storage is made up of two parallel numpy arrays:
- *vertices*: an Nx2 float array of vertices
- *codes*: an N-length uint8 array of vertex types
These two arrays always have the same length in the first
dimension. For example, to represent a cubic curve, you must
provide three vertices as well as three codes ``CURVE3``.
The code types are:
- ``STOP`` : 1 vertex (ignored)
A marker for the end of the entire path (currently not
required and ignored)
- ``MOVETO`` : 1 vertex
Pick up the pen and move to the given vertex.
- ``LINETO`` : 1 vertex
Draw a line from the current position to the given vertex.
- ``CURVE3`` : 1 control point, 1 endpoint
Draw a quadratic Bezier curve from the current position,
with the given control point, to the given end point.
- ``CURVE4`` : 2 control points, 1 endpoint
Draw a cubic Bezier curve from the current position, with
the given control points, to the given end point.
- ``CLOSEPOLY`` : 1 vertex (ignored)
Draw a line segment to the start point of the current
polyline.
Users of Path objects should not access the vertices and codes
arrays directly. Instead, they should use :meth:`iter_segments`
or :meth:`cleaned` to get the vertex/code pairs. This is important,
since many :class:`Path` objects, as an optimization, do not store a
*codes* at all, but have a default one provided for them by
:meth:`iter_segments`.
Some behavior of Path objects can be controlled by rcParams. See
the rcParams whose keys contain 'path.'.
.. note::
The vertices and codes arrays should be treated as
immutable -- there are a number of optimizations and assumptions
made up front in the constructor that will not change when the
data changes.
"""
code_type = np.uint8
# Path codes
STOP = code_type(0) # 1 vertex
MOVETO = code_type(1) # 1 vertex
LINETO = code_type(2) # 1 vertex
CURVE3 = code_type(3) # 2 vertices
CURVE4 = code_type(4) # 3 vertices
CLOSEPOLY = code_type(79) # 1 vertex
#: A dictionary mapping Path codes to the number of vertices that the
#: code expects.
NUM_VERTICES_FOR_CODE = {STOP: 1,
MOVETO: 1,
LINETO: 1,
CURVE3: 2,
CURVE4: 3,
CLOSEPOLY: 1}
def __init__(self, vertices, codes=None, _interpolation_steps=1,
closed=False, readonly=False):
"""
Create a new path with the given vertices and codes.
Parameters
----------
vertices : array_like
The ``(n, 2)`` float array, masked array or sequence of pairs
representing the vertices of the path.
If *vertices* contains masked values, they will be converted
to NaNs which are then handled correctly by the Agg
PathIterator and other consumers of path data, such as
:meth:`iter_segments`.
codes : {None, array_like}, optional
n-length array integers representing the codes of the path.
If not None, codes must be the same length as vertices.
If None, *vertices* will be treated as a series of line segments.
_interpolation_steps : int, optional
Used as a hint to certain projections, such as Polar, that this
path should be linearly interpolated immediately before drawing.
This attribute is primarily an implementation detail and is not
intended for public use.
closed : bool, optional
If *codes* is None and closed is True, vertices will be treated as
line segments of a closed polygon.
readonly : bool, optional
Makes the path behave in an immutable way and sets the vertices
and codes as read-only arrays.
"""
vertices = _to_unmasked_float_array(vertices)
if vertices.ndim != 2 or vertices.shape[1] != 2:
raise ValueError(
"'vertices' must be a 2D list or array with shape Nx2")
if codes is not None:
codes = np.asarray(codes, self.code_type)
if codes.ndim != 1 or len(codes) != len(vertices):
raise ValueError("'codes' must be a 1D list or array with the "
"same length of 'vertices'")
if len(codes) and codes[0] != self.MOVETO:
raise ValueError("The first element of 'code' must be equal "
"to 'MOVETO' ({})".format(self.MOVETO))
elif closed and len(vertices):
codes = np.empty(len(vertices), dtype=self.code_type)
codes[0] = self.MOVETO
codes[1:-1] = self.LINETO
codes[-1] = self.CLOSEPOLY
self._vertices = vertices
self._codes = codes
self._interpolation_steps = _interpolation_steps
self._update_values()
if readonly:
self._vertices.flags.writeable = False
if self._codes is not None:
self._codes.flags.writeable = False
self._readonly = True
else:
self._readonly = False
@classmethod
def _fast_from_codes_and_verts(cls, verts, codes, internals_from=None):
"""
Creates a Path instance without the expense of calling the constructor.
Parameters
----------
verts : numpy array
codes : numpy array
internals_from : Path or None
If not None, another `Path` from which the attributes
``should_simplify``, ``simplify_threshold``, and
``interpolation_steps`` will be copied. Note that ``readonly`` is
never copied, and always set to ``False`` by this constructor.
"""
pth = cls.__new__(cls)
pth._vertices = _to_unmasked_float_array(verts)
pth._codes = codes
pth._readonly = False
if internals_from is not None:
pth._should_simplify = internals_from._should_simplify
pth._simplify_threshold = internals_from._simplify_threshold
pth._interpolation_steps = internals_from._interpolation_steps
else:
pth._should_simplify = True
pth._simplify_threshold = rcParams['path.simplify_threshold']
pth._interpolation_steps = 1
return pth
def _update_values(self):
self._simplify_threshold = rcParams['path.simplify_threshold']
self._should_simplify = (
self._simplify_threshold > 0 and
rcParams['path.simplify'] and
len(self._vertices) >= 128 and
(self._codes is None or np.all(self._codes <= Path.LINETO))
)
@property
def vertices(self):
"""
The list of vertices in the `Path` as an Nx2 numpy array.
"""
return self._vertices
@vertices.setter
def vertices(self, vertices):
if self._readonly:
raise AttributeError("Can't set vertices on a readonly Path")
self._vertices = vertices
self._update_values()
@property
def codes(self):
"""
The list of codes in the `Path` as a 1-D numpy array. Each
code is one of `STOP`, `MOVETO`, `LINETO`, `CURVE3`, `CURVE4`
or `CLOSEPOLY`. For codes that correspond to more than one
vertex (`CURVE3` and `CURVE4`), that code will be repeated so
that the length of `self.vertices` and `self.codes` is always
the same.
"""
return self._codes
@codes.setter
def codes(self, codes):
if self._readonly:
raise AttributeError("Can't set codes on a readonly Path")
self._codes = codes
self._update_values()
@property
def simplify_threshold(self):
"""
The fraction of a pixel difference below which vertices will
be simplified out.
"""
return self._simplify_threshold
@simplify_threshold.setter
def simplify_threshold(self, threshold):
self._simplify_threshold = threshold
@cbook.deprecated(
"3.1", alternative="not np.isfinite(self.vertices).all()")
@property
def has_nonfinite(self):
"""
`True` if the vertices array has nonfinite values.
"""
return not np.isfinite(self._vertices).all()
@property
def should_simplify(self):
"""
`True` if the vertices array should be simplified.
"""
return self._should_simplify
@should_simplify.setter
def should_simplify(self, should_simplify):
self._should_simplify = should_simplify
@property
def readonly(self):
"""
`True` if the `Path` is read-only.
"""
return self._readonly
def __copy__(self):
"""
Returns a shallow copy of the `Path`, which will share the
vertices and codes with the source `Path`.
"""
import copy
return copy.copy(self)
copy = __copy__
def __deepcopy__(self, memo=None):
"""
Returns a deepcopy of the `Path`. The `Path` will not be
readonly, even if the source `Path` is.
"""
try:
codes = self.codes.copy()
except AttributeError:
codes = None
return self.__class__(
self.vertices.copy(), codes,
_interpolation_steps=self._interpolation_steps)
deepcopy = __deepcopy__
@classmethod
def make_compound_path_from_polys(cls, XY):
"""
Make a compound path object to draw a number
of polygons with equal numbers of sides XY is a (numpolys x
numsides x 2) numpy array of vertices. Return object is a
:class:`Path`
.. plot:: gallery/misc/histogram_path.py
"""
# for each poly: 1 for the MOVETO, (numsides-1) for the LINETO, 1 for
# the CLOSEPOLY; the vert for the closepoly is ignored but we still
# need it to keep the codes aligned with the vertices
numpolys, numsides, two = XY.shape
if two != 2:
raise ValueError("The third dimension of 'XY' must be 2")
stride = numsides + 1
nverts = numpolys * stride
verts = np.zeros((nverts, 2))
codes = np.full(nverts, cls.LINETO, dtype=cls.code_type)
codes[0::stride] = cls.MOVETO
codes[numsides::stride] = cls.CLOSEPOLY
for i in range(numsides):
verts[i::stride] = XY[:, i]
return cls(verts, codes)
@classmethod
def make_compound_path(cls, *args):
"""Make a compound path from a list of Path objects."""
# Handle an empty list in args (i.e. no args).
if not args:
return Path(np.empty([0, 2], dtype=np.float32))
lengths = [len(x) for x in args]
total_length = sum(lengths)
vertices = np.vstack([x.vertices for x in args])
vertices.reshape((total_length, 2))
codes = np.empty(total_length, dtype=cls.code_type)
i = 0
for path in args:
if path.codes is None:
codes[i] = cls.MOVETO
codes[i + 1:i + len(path.vertices)] = cls.LINETO
else:
codes[i:i + len(path.codes)] = path.codes
i += len(path.vertices)
return cls(vertices, codes)
def __repr__(self):
return "Path(%r, %r)" % (self.vertices, self.codes)
def __len__(self):
return len(self.vertices)
def iter_segments(self, transform=None, remove_nans=True, clip=None,
snap=False, stroke_width=1.0, simplify=None,
curves=True, sketch=None):
"""
Iterates over all of the curve segments in the path. Each iteration
returns a 2-tuple ``(vertices, code)``, where ``vertices`` is a
sequence of 1-3 coordinate pairs, and ``code`` is a `Path` code.
Additionally, this method can provide a number of standard cleanups and
conversions to the path.
Parameters
----------
transform : None or :class:`~matplotlib.transforms.Transform`
If not None, the given affine transformation will be applied to the
path.
remove_nans : bool, optional
Whether to remove all NaNs from the path and skip over them using
MOVETO commands.
clip : None or (float, float, float, float), optional
If not None, must be a four-tuple (x1, y1, x2, y2)
defining a rectangle in which to clip the path.
snap : None or bool, optional
If True, snap all nodes to pixels; if False, don't snap them.
If None, perform snapping if the path contains only segments
parallel to the x or y axes, and no more than 1024 of them.
stroke_width : float, optional
The width of the stroke being drawn (used for path snapping).
simplify : None or bool, optional
Whether to simplify the path by removing vertices
that do not affect its appearance. If None, use the
:attr:`should_simplify` attribute. See also :rc:`path.simplify`
and :rc:`path.simplify_threshold`.
curves : bool, optional
If True, curve segments will be returned as curve segments.
If False, all curves will be converted to line segments.
sketch : None or sequence, optional
If not None, must be a 3-tuple of the form
(scale, length, randomness), representing the sketch parameters.
"""
if not len(self):
return
cleaned = self.cleaned(transform=transform,
remove_nans=remove_nans, clip=clip,
snap=snap, stroke_width=stroke_width,
simplify=simplify, curves=curves,
sketch=sketch)
# Cache these object lookups for performance in the loop.
NUM_VERTICES_FOR_CODE = self.NUM_VERTICES_FOR_CODE
STOP = self.STOP
vertices = iter(cleaned.vertices)
codes = iter(cleaned.codes)
for curr_vertices, code in zip(vertices, codes):
if code == STOP:
break
extra_vertices = NUM_VERTICES_FOR_CODE[code] - 1
if extra_vertices:
for i in range(extra_vertices):
next(codes)
curr_vertices = np.append(curr_vertices, next(vertices))
yield curr_vertices, code
def cleaned(self, transform=None, remove_nans=False, clip=None,
quantize=False, simplify=False, curves=False,
stroke_width=1.0, snap=False, sketch=None):
"""
Return a new Path with vertices and codes cleaned according to the
parameters.
See Also
--------
Path.iter_segments : for details of the keyword arguments.
"""
vertices, codes = _path.cleanup_path(
self, transform, remove_nans, clip, snap, stroke_width, simplify,
curves, sketch)
pth = Path._fast_from_codes_and_verts(vertices, codes, self)
if not simplify:
pth._should_simplify = False
return pth
def transformed(self, transform):
"""
Return a transformed copy of the path.
See Also
--------
matplotlib.transforms.TransformedPath
A specialized path class that will cache the transformed result and
automatically update when the transform changes.
"""
return Path(transform.transform(self.vertices), self.codes,
self._interpolation_steps)
def contains_point(self, point, transform=None, radius=0.0):
"""
Returns whether the (closed) path contains the given point.
If *transform* is not ``None``, the path will be transformed before
performing the test.
*radius* allows the path to be made slightly larger or smaller.
"""
if transform is not None:
transform = transform.frozen()
# `point_in_path` does not handle nonlinear transforms, so we
# transform the path ourselves. If `transform` is affine, letting
# `point_in_path` handle the transform avoids allocating an extra
# buffer.
if transform and not transform.is_affine:
self = transform.transform_path(self)
transform = None
return _path.point_in_path(point[0], point[1], radius, self, transform)
def contains_points(self, points, transform=None, radius=0.0):
"""
Returns a bool array which is ``True`` if the (closed) path contains
the corresponding point.
If *transform* is not ``None``, the path will be transformed before
performing the test.
*radius* allows the path to be made slightly larger or smaller.
"""
if transform is not None:
transform = transform.frozen()
result = _path.points_in_path(points, radius, self, transform)
return result.astype('bool')
def contains_path(self, path, transform=None):
"""
Returns whether this (closed) path completely contains the given path.
If *transform* is not ``None``, the path will be transformed before
performing the test.
"""
if transform is not None:
transform = transform.frozen()
return _path.path_in_path(self, None, path, transform)
def get_extents(self, transform=None):
"""
Returns the extents (*xmin*, *ymin*, *xmax*, *ymax*) of the
path.
Unlike computing the extents on the *vertices* alone, this
algorithm will take into account the curves and deal with
control points appropriately.
"""
from .transforms import Bbox
path = self
if transform is not None:
transform = transform.frozen()
if not transform.is_affine:
path = self.transformed(transform)
transform = None
return Bbox(_path.get_path_extents(path, transform))
def intersects_path(self, other, filled=True):
"""
Returns *True* if this path intersects another given path.
*filled*, when True, treats the paths as if they were filled.
That is, if one path completely encloses the other,
:meth:`intersects_path` will return True.
"""
return _path.path_intersects_path(self, other, filled)
def intersects_bbox(self, bbox, filled=True):
"""
Returns *True* if this path intersects a given
:class:`~matplotlib.transforms.Bbox`.
*filled*, when True, treats the path as if it was filled.
That is, if the path completely encloses the bounding box,
:meth:`intersects_bbox` will return True.
The bounding box is always considered filled.
"""
return _path.path_intersects_rectangle(self,
bbox.x0, bbox.y0, bbox.x1, bbox.y1, filled)
def interpolated(self, steps):
"""
Returns a new path resampled to length N x steps. Does not
currently handle interpolating curves.
"""
if steps == 1:
return self
vertices = simple_linear_interpolation(self.vertices, steps)
codes = self.codes
if codes is not None:
new_codes = np.full((len(codes) - 1) * steps + 1, Path.LINETO,
dtype=self.code_type)
new_codes[0::steps] = codes
else:
new_codes = None
return Path(vertices, new_codes)
def to_polygons(self, transform=None, width=0, height=0, closed_only=True):
"""
Convert this path to a list of polygons or polylines. Each
polygon/polyline is an Nx2 array of vertices. In other words,
each polygon has no ``MOVETO`` instructions or curves. This
is useful for displaying in backends that do not support
compound paths or Bezier curves.
If *width* and *height* are both non-zero then the lines will
be simplified so that vertices outside of (0, 0), (width,
height) will be clipped.
If *closed_only* is `True` (default), only closed polygons,
with the last point being the same as the first point, will be
returned. Any unclosed polylines in the path will be
explicitly closed. If *closed_only* is `False`, any unclosed
polygons in the path will be returned as unclosed polygons,
and the closed polygons will be returned explicitly closed by
setting the last point to the same as the first point.
"""
if len(self.vertices) == 0:
return []
if transform is not None:
transform = transform.frozen()
if self.codes is None and (width == 0 or height == 0):
vertices = self.vertices
if closed_only:
if len(vertices) < 3:
return []
elif np.any(vertices[0] != vertices[-1]):
vertices = [*vertices, vertices[0]]
if transform is None:
return [vertices]
else:
return [transform.transform(vertices)]
# Deal with the case where there are curves and/or multiple
# subpaths (using extension code)
return _path.convert_path_to_polygons(
self, transform, width, height, closed_only)
_unit_rectangle = None
@classmethod
def unit_rectangle(cls):
"""
Return a `Path` instance of the unit rectangle from (0, 0) to (1, 1).
"""
if cls._unit_rectangle is None:
cls._unit_rectangle = \
cls([[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0],
[0.0, 0.0]],
[cls.MOVETO, cls.LINETO, cls.LINETO, cls.LINETO,
cls.CLOSEPOLY],
readonly=True)
return cls._unit_rectangle
_unit_regular_polygons = WeakValueDictionary()
@classmethod
def unit_regular_polygon(cls, numVertices):
"""
Return a :class:`Path` instance for a unit regular polygon with the
given *numVertices* and radius of 1.0, centered at (0, 0).
"""
if numVertices <= 16:
path = cls._unit_regular_polygons.get(numVertices)
else:
path = None
if path is None:
theta = ((2 * np.pi / numVertices) * np.arange(numVertices + 1)
# This initial rotation is to make sure the polygon always
# "points-up".
+ np.pi / 2)
verts = np.column_stack((np.cos(theta), np.sin(theta)))
codes = np.empty(numVertices + 1)
codes[0] = cls.MOVETO
codes[1:-1] = cls.LINETO
codes[-1] = cls.CLOSEPOLY
path = cls(verts, codes, readonly=True)
if numVertices <= 16:
cls._unit_regular_polygons[numVertices] = path
return path
_unit_regular_stars = WeakValueDictionary()
@classmethod
def unit_regular_star(cls, numVertices, innerCircle=0.5):
"""
Return a :class:`Path` for a unit regular star with the given
numVertices and radius of 1.0, centered at (0, 0).
"""
if numVertices <= 16:
path = cls._unit_regular_stars.get((numVertices, innerCircle))
else:
path = None
if path is None:
ns2 = numVertices * 2
theta = (2*np.pi/ns2 * np.arange(ns2 + 1))
# This initial rotation is to make sure the polygon always
# "points-up"
theta += np.pi / 2.0
r = np.ones(ns2 + 1)
r[1::2] = innerCircle
verts = np.vstack((r*np.cos(theta), r*np.sin(theta))).transpose()
codes = np.empty((ns2 + 1,))
codes[0] = cls.MOVETO
codes[1:-1] = cls.LINETO
codes[-1] = cls.CLOSEPOLY
path = cls(verts, codes, readonly=True)
if numVertices <= 16:
cls._unit_regular_stars[(numVertices, innerCircle)] = path
return path
@classmethod
def unit_regular_asterisk(cls, numVertices):
"""
Return a :class:`Path` for a unit regular asterisk with the given
numVertices and radius of 1.0, centered at (0, 0).
"""
return cls.unit_regular_star(numVertices, 0.0)
_unit_circle = None
@classmethod
def unit_circle(cls):
"""
Return the readonly :class:`Path` of the unit circle.
For most cases, :func:`Path.circle` will be what you want.
"""
if cls._unit_circle is None:
cls._unit_circle = cls.circle(center=(0, 0), radius=1,
readonly=True)
return cls._unit_circle
@classmethod
def circle(cls, center=(0., 0.), radius=1., readonly=False):
"""
Return a `Path` representing a circle of a given radius and center.
Parameters
----------
center : pair of floats
The center of the circle. Default ``(0, 0)``.
radius : float
The radius of the circle. Default is 1.
readonly : bool
Whether the created path should have the "readonly" argument
set when creating the Path instance.
Notes
-----
The circle is approximated using 8 cubic Bezier curves, as described in
Lancaster, Don. `Approximating a Circle or an Ellipse Using Four
Bezier Cubic Splines <http://www.tinaja.com/glib/ellipse4.pdf>`_.
"""
MAGIC = 0.2652031
SQRTHALF = np.sqrt(0.5)
MAGIC45 = SQRTHALF * MAGIC
vertices = np.array([[0.0, -1.0],
[MAGIC, -1.0],
[SQRTHALF-MAGIC45, -SQRTHALF-MAGIC45],
[SQRTHALF, -SQRTHALF],
[SQRTHALF+MAGIC45, -SQRTHALF+MAGIC45],
[1.0, -MAGIC],
[1.0, 0.0],
[1.0, MAGIC],
[SQRTHALF+MAGIC45, SQRTHALF-MAGIC45],
[SQRTHALF, SQRTHALF],
[SQRTHALF-MAGIC45, SQRTHALF+MAGIC45],
[MAGIC, 1.0],
[0.0, 1.0],
[-MAGIC, 1.0],
[-SQRTHALF+MAGIC45, SQRTHALF+MAGIC45],
[-SQRTHALF, SQRTHALF],
[-SQRTHALF-MAGIC45, SQRTHALF-MAGIC45],
[-1.0, MAGIC],
[-1.0, 0.0],
[-1.0, -MAGIC],
[-SQRTHALF-MAGIC45, -SQRTHALF+MAGIC45],
[-SQRTHALF, -SQRTHALF],
[-SQRTHALF+MAGIC45, -SQRTHALF-MAGIC45],
[-MAGIC, -1.0],
[0.0, -1.0],
[0.0, -1.0]],
dtype=float)
codes = [cls.CURVE4] * 26
codes[0] = cls.MOVETO
codes[-1] = cls.CLOSEPOLY
return Path(vertices * radius + center, codes, readonly=readonly)
_unit_circle_righthalf = None
@classmethod
def unit_circle_righthalf(cls):
"""
Return a `Path` of the right half of a unit circle.
See `Path.circle` for the reference on the approximation used.
"""
if cls._unit_circle_righthalf is None:
MAGIC = 0.2652031
SQRTHALF = np.sqrt(0.5)
MAGIC45 = SQRTHALF * MAGIC
vertices = np.array(
[[0.0, -1.0],
[MAGIC, -1.0],
[SQRTHALF-MAGIC45, -SQRTHALF-MAGIC45],
[SQRTHALF, -SQRTHALF],
[SQRTHALF+MAGIC45, -SQRTHALF+MAGIC45],
[1.0, -MAGIC],
[1.0, 0.0],
[1.0, MAGIC],
[SQRTHALF+MAGIC45, SQRTHALF-MAGIC45],
[SQRTHALF, SQRTHALF],
[SQRTHALF-MAGIC45, SQRTHALF+MAGIC45],
[MAGIC, 1.0],
[0.0, 1.0],
[0.0, -1.0]],
float)
codes = np.full(14, cls.CURVE4, dtype=cls.code_type)
codes[0] = cls.MOVETO
codes[-1] = cls.CLOSEPOLY
cls._unit_circle_righthalf = cls(vertices, codes, readonly=True)
return cls._unit_circle_righthalf
@classmethod
def arc(cls, theta1, theta2, n=None, is_wedge=False):
"""
Return the unit circle arc from angles *theta1* to *theta2* (in
degrees).
*theta2* is unwrapped to produce the shortest arc within 360 degrees.
That is, if *theta2* > *theta1* + 360, the arc will be from *theta1* to
*theta2* - 360 and not a full circle plus some extra overlap.
If *n* is provided, it is the number of spline segments to make.
If *n* is not provided, the number of spline segments is
determined based on the delta between *theta1* and *theta2*.
Masionobe, L. 2003. `Drawing an elliptical arc using
polylines, quadratic or cubic Bezier curves
<http://www.spaceroots.org/documents/ellipse/index.html>`_.
"""
halfpi = np.pi * 0.5
eta1 = theta1
eta2 = theta2 - 360 * np.floor((theta2 - theta1) / 360)
# Ensure 2pi range is not flattened to 0 due to floating-point errors,
# but don't try to expand existing 0 range.
if theta2 != theta1 and eta2 <= eta1:
eta2 += 360
eta1, eta2 = np.deg2rad([eta1, eta2])
# number of curve segments to make
if n is None:
n = int(2 ** np.ceil((eta2 - eta1) / halfpi))
if n < 1:
raise ValueError("n must be >= 1 or None")
deta = (eta2 - eta1) / n
t = np.tan(0.5 * deta)
alpha = np.sin(deta) * (np.sqrt(4.0 + 3.0 * t * t) - 1) / 3.0
steps = np.linspace(eta1, eta2, n + 1, True)
cos_eta = np.cos(steps)
sin_eta = np.sin(steps)
xA = cos_eta[:-1]
yA = sin_eta[:-1]
xA_dot = -yA
yA_dot = xA
xB = cos_eta[1:]
yB = sin_eta[1:]
xB_dot = -yB
yB_dot = xB
if is_wedge:
length = n * 3 + 4
vertices = np.zeros((length, 2), float)
codes = np.full(length, cls.CURVE4, dtype=cls.code_type)
vertices[1] = [xA[0], yA[0]]
codes[0:2] = [cls.MOVETO, cls.LINETO]
codes[-2:] = [cls.LINETO, cls.CLOSEPOLY]
vertex_offset = 2
end = length - 2
else:
length = n * 3 + 1
vertices = np.empty((length, 2), float)
codes = np.full(length, cls.CURVE4, dtype=cls.code_type)
vertices[0] = [xA[0], yA[0]]
codes[0] = cls.MOVETO
vertex_offset = 1
end = length
vertices[vertex_offset:end:3, 0] = xA + alpha * xA_dot
vertices[vertex_offset:end:3, 1] = yA + alpha * yA_dot
vertices[vertex_offset+1:end:3, 0] = xB - alpha * xB_dot
vertices[vertex_offset+1:end:3, 1] = yB - alpha * yB_dot
vertices[vertex_offset+2:end:3, 0] = xB
vertices[vertex_offset+2:end:3, 1] = yB
return cls(vertices, codes, readonly=True)
@classmethod
def wedge(cls, theta1, theta2, n=None):
"""
Return the unit circle wedge from angles *theta1* to *theta2* (in
degrees).
*theta2* is unwrapped to produce the shortest wedge within 360 degrees.
That is, if *theta2* > *theta1* + 360, the wedge will be from *theta1*
to *theta2* - 360 and not a full circle plus some extra overlap.
If *n* is provided, it is the number of spline segments to make.
If *n* is not provided, the number of spline segments is
determined based on the delta between *theta1* and *theta2*.
See `Path.arc` for the reference on the approximation used.
"""
return cls.arc(theta1, theta2, n, True)
@staticmethod
@lru_cache(8)
def hatch(hatchpattern, density=6):
"""
Given a hatch specifier, *hatchpattern*, generates a Path that
can be used in a repeated hatching pattern. *density* is the
number of lines per unit square.
"""
from matplotlib.hatch import get_path
return (get_path(hatchpattern, density)
if hatchpattern is not None else None)
def clip_to_bbox(self, bbox, inside=True):
"""
Clip the path to the given bounding box.
The path must be made up of one or more closed polygons. This
algorithm will not behave correctly for unclosed paths.
If *inside* is `True`, clip to the inside of the box, otherwise
to the outside of the box.
"""
# Use make_compound_path_from_polys
verts = _path.clip_path_to_rect(self, bbox, inside)
paths = [Path(poly) for poly in verts]
return self.make_compound_path(*paths)
def get_path_collection_extents(
master_transform, paths, transforms, offsets, offset_transform):
r"""
Given a sequence of `Path`\s, `~.Transform`\s objects, and offsets, as
found in a `~.PathCollection`, returns the bounding box that encapsulates
all of them.
Parameters
----------
master_transform : `~.Transform`
Global transformation applied to all paths.
paths : list of `Path`
transform : list of `~.Affine2D`
offsets : (N, 2) array-like
offset_transform : `~.Affine2D`
Transform applied to the offsets before offsetting the path.
Notes
-----
The way that *paths*, *transforms* and *offsets* are combined
follows the same method as for collections: Each is iterated over
independently, so if you have 3 paths, 2 transforms and 1 offset,
their combinations are as follows:
(A, A, A), (B, B, A), (C, A, A)
"""
from .transforms import Bbox
if len(paths) == 0:
raise ValueError("No paths provided")
return Bbox.from_extents(*_path.get_path_collection_extents(
master_transform, paths, np.atleast_3d(transforms),
offsets, offset_transform))
@cbook.deprecated("3.1", alternative="get_paths_collection_extents")
def get_paths_extents(paths, transforms=[]):
"""
Given a sequence of :class:`Path` objects and optional
:class:`~matplotlib.transforms.Transform` objects, returns the
bounding box that encapsulates all of them.
*paths* is a sequence of :class:`Path` instances.
*transforms* is an optional sequence of
:class:`~matplotlib.transforms.Affine2D` instances to apply to
each path.
"""
from .transforms import Bbox, Affine2D
if len(paths) == 0:
raise ValueError("No paths provided")
return Bbox.from_extents(*_path.get_path_collection_extents(
Affine2D(), paths, transforms, [], Affine2D()))
|
d17e3a30f63b7e8ab039e5276c2c23e39d0fa39ba6b6db291671bb73b1c555a4
|
"""
The classes here provide support for using custom classes with
Matplotlib, e.g., those that do not expose the array interface but know
how to convert themselves to arrays. It also supports classes with
units and units conversion. Use cases include converters for custom
objects, e.g., a list of datetime objects, as well as for objects that
are unit aware. We don't assume any particular units implementation;
rather a units implementation must provide the register with the Registry
converter dictionary and a `ConversionInterface`. For example,
here is a complete implementation which supports plotting with native
datetime objects::
import matplotlib.units as units
import matplotlib.dates as dates
import matplotlib.ticker as ticker
import datetime
class DateConverter(units.ConversionInterface):
@staticmethod
def convert(value, unit, axis):
'Convert a datetime value to a scalar or array'
return dates.date2num(value)
@staticmethod
def axisinfo(unit, axis):
'Return major and minor tick locators and formatters'
if unit!='date': return None
majloc = dates.AutoDateLocator()
majfmt = dates.AutoDateFormatter(majloc)
return AxisInfo(majloc=majloc,
majfmt=majfmt,
label='date')
@staticmethod
def default_units(x, axis):
'Return the default unit for x or None'
return 'date'
# Finally we register our object type with the Matplotlib units registry.
units.registry[datetime.date] = DateConverter()
"""
from numbers import Number
import numpy as np
from matplotlib import cbook
class ConversionError(TypeError):
pass
class AxisInfo(object):
"""
Information to support default axis labeling, tick labeling, and limits.
An instance of this class must be returned by
`ConversionInterface.axisinfo`.
"""
def __init__(self, majloc=None, minloc=None,
majfmt=None, minfmt=None, label=None,
default_limits=None):
"""
Parameters
----------
majloc, minloc : Locator, optional
Tick locators for the major and minor ticks.
majfmt, minfmt : Formatter, optional
Tick formatters for the major and minor ticks.
label : str, optional
The default axis label.
default_limits : optional
The default min and max limits of the axis if no data has
been plotted.
Notes
-----
If any of the above are ``None``, the axis will simply use the
default value.
"""
self.majloc = majloc
self.minloc = minloc
self.majfmt = majfmt
self.minfmt = minfmt
self.label = label
self.default_limits = default_limits
class ConversionInterface(object):
"""
The minimal interface for a converter to take custom data types (or
sequences) and convert them to values Matplotlib can use.
"""
@staticmethod
def axisinfo(unit, axis):
"""
Return an `~units.AxisInfo` for the axis with the specified units.
"""
return None
@staticmethod
def default_units(x, axis):
"""
Return the default unit for *x* or ``None`` for the given axis.
"""
return None
@staticmethod
def convert(obj, unit, axis):
"""
Convert *obj* using *unit* for the specified *axis*.
If *obj* is a sequence, return the converted sequence. The output must
be a sequence of scalars that can be used by the numpy array layer.
"""
return obj
@staticmethod
def is_numlike(x):
"""
The Matplotlib datalim, autoscaling, locators etc work with scalars
which are the units converted to floats given the current unit. The
converter may be passed these floats, or arrays of them, even when
units are set.
"""
if np.iterable(x):
for thisx in x:
return isinstance(thisx, Number)
else:
return isinstance(x, Number)
class Registry(dict):
"""Register types with conversion interface."""
def get_converter(self, x):
"""Get the converter interface instance for *x*, or None."""
if hasattr(x, "values"):
x = x.values # Unpack pandas Series and DataFrames.
if isinstance(x, np.ndarray):
# In case x in a masked array, access the underlying data (only its
# type matters). If x is a regular ndarray, getdata() just returns
# the array itself.
x = np.ma.getdata(x).ravel()
# If there are no elements in x, infer the units from its dtype
if not x.size:
return self.get_converter(np.array([0], dtype=x.dtype))
try: # Look up in the cache.
return self[type(x)]
except KeyError:
try: # If cache lookup fails, look up based on first element...
first = cbook.safe_first_element(x)
except (TypeError, StopIteration):
pass
else:
# ... and avoid infinite recursion for pathological iterables
# where indexing returns instances of the same iterable class.
if type(first) is not type(x):
return self.get_converter(first)
return None
registry = Registry()
|
1342bc87c3d54c9d2333529fbb4a03a47b84b781cf4d912f19cdca0432f0a741
|
"""
A module for finding, managing, and using fonts across platforms.
This module provides a single :class:`FontManager` instance that can
be shared across backends and platforms. The :func:`findfont`
function returns the best TrueType (TTF) font file in the local or
system font path that matches the specified :class:`FontProperties`
instance. The :class:`FontManager` also handles Adobe Font Metrics
(AFM) font files for use by the PostScript backend.
The design is based on the `W3C Cascading Style Sheet, Level 1 (CSS1)
font specification <http://www.w3.org/TR/1998/REC-CSS2-19980512/>`_.
Future versions may implement the Level 2 or 2.1 specifications.
"""
# KNOWN ISSUES
#
# - documentation
# - font variant is untested
# - font stretch is incomplete
# - font size is incomplete
# - default font algorithm needs improvement and testing
# - setWeights function needs improvement
# - 'light' is an invalid weight value, remove it.
from functools import lru_cache
import json
import logging
from numbers import Number
import os
from pathlib import Path
import subprocess
import sys
try:
from threading import Timer
except ImportError:
from dummy_threading import Timer
import matplotlib as mpl
from matplotlib import afm, cbook, ft2font, rcParams
from matplotlib.fontconfig_pattern import (
parse_fontconfig_pattern, generate_fontconfig_pattern)
_log = logging.getLogger(__name__)
font_scalings = {
'xx-small' : 0.579,
'x-small' : 0.694,
'small' : 0.833,
'medium' : 1.0,
'large' : 1.200,
'x-large' : 1.440,
'xx-large' : 1.728,
'larger' : 1.2,
'smaller' : 0.833,
None : 1.0}
stretch_dict = {
'ultra-condensed' : 100,
'extra-condensed' : 200,
'condensed' : 300,
'semi-condensed' : 400,
'normal' : 500,
'semi-expanded' : 600,
'expanded' : 700,
'extra-expanded' : 800,
'ultra-expanded' : 900}
weight_dict = {
'ultralight' : 100,
'light' : 200,
'normal' : 400,
'regular' : 400,
'book' : 400,
'medium' : 500,
'roman' : 500,
'semibold' : 600,
'demibold' : 600,
'demi' : 600,
'bold' : 700,
'heavy' : 800,
'extra bold' : 800,
'black' : 900}
font_family_aliases = {
'serif',
'sans-serif',
'sans serif',
'cursive',
'fantasy',
'monospace',
'sans'}
# OS Font paths
MSFolders = \
r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders'
MSFontDirectories = [
r'SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts',
r'SOFTWARE\Microsoft\Windows\CurrentVersion\Fonts']
MSUserFontDirectories = [
os.path.join(str(Path.home()), r'AppData\Local\Microsoft\Windows\Fonts'),
os.path.join(str(Path.home()), r'AppData\Roaming\Microsoft\Windows\Fonts')]
X11FontDirectories = [
# an old standard installation point
"/usr/X11R6/lib/X11/fonts/TTF/",
"/usr/X11/lib/X11/fonts",
# here is the new standard location for fonts
"/usr/share/fonts/",
# documented as a good place to install new fonts
"/usr/local/share/fonts/",
# common application, not really useful
"/usr/lib/openoffice/share/fonts/truetype/",
# user fonts
str(Path(os.environ.get('XDG_DATA_HOME',
Path.home() / ".local/share")) / "fonts"),
str(Path.home() / ".fonts"),
]
OSXFontDirectories = [
"/Library/Fonts/",
"/Network/Library/Fonts/",
"/System/Library/Fonts/",
# fonts installed via MacPorts
"/opt/local/share/fonts",
# user fonts
str(Path.home() / "Library/Fonts"),
]
def get_fontext_synonyms(fontext):
"""
Return a list of file extensions extensions that are synonyms for
the given file extension *fileext*.
"""
return {
'afm': ['afm'],
'otf': ['otf', 'ttc', 'ttf'],
'ttc': ['otf', 'ttc', 'ttf'],
'ttf': ['otf', 'ttc', 'ttf'],
}[fontext]
def list_fonts(directory, extensions):
"""
Return a list of all fonts matching any of the extensions, found
recursively under the directory.
"""
extensions = ["." + ext for ext in extensions]
return [os.path.join(dirpath, filename)
# os.walk ignores access errors, unlike Path.glob.
for dirpath, _, filenames in os.walk(directory)
for filename in filenames
if Path(filename).suffix.lower() in extensions]
def win32FontDirectory():
r"""
Return the user-specified font directory for Win32. This is
looked up from the registry key::
\\HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\Fonts
If the key is not found, ``%WINDIR%\Fonts`` will be returned.
"""
import winreg
try:
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, MSFolders) as user:
return winreg.QueryValueEx(user, 'Fonts')[0]
except OSError:
return os.path.join(os.environ['WINDIR'], 'Fonts')
def _win32RegistryFonts(reg_domain, base_dir):
r"""
Searches for fonts in the Windows registry.
Parameters
----------
reg_domain : int
The top level registry domain (e.g. HKEY_LOCAL_MACHINE).
base_dir : str
The path to the folder where the font files are usually located (e.g.
C:\Windows\Fonts). If only the filename of the font is stored in the
registry, the absolute path is built relative to this base directory.
Returns
-------
`set`
`pathlib.Path` objects with the absolute path to the font files found.
"""
import winreg
items = set()
for reg_path in MSFontDirectories:
try:
with winreg.OpenKey(reg_domain, reg_path) as local:
for j in range(winreg.QueryInfoKey(local)[1]):
# value may contain the filename of the font or its
# absolute path.
key, value, tp = winreg.EnumValue(local, j)
if not isinstance(value, str):
continue
# Work around for https://bugs.python.org/issue25778, which
# is fixed in Py>=3.6.1.
value = value.split("\0", 1)[0]
try:
# If value contains already an absolute path, then it
# is not changed further.
path = Path(base_dir, value).resolve()
except RuntimeError:
# Don't fail with invalid entries.
continue
items.add(path)
except (OSError, MemoryError):
continue
return items
def win32InstalledFonts(directory=None, fontext='ttf'):
"""
Search for fonts in the specified font directory, or use the
system directories if none given. Additionally, it is searched for user
fonts installed. A list of TrueType font filenames are returned by default,
or AFM fonts if *fontext* == 'afm'.
"""
import winreg
if directory is None:
directory = win32FontDirectory()
fontext = ['.' + ext for ext in get_fontext_synonyms(fontext)]
items = set()
# System fonts
items.update(_win32RegistryFonts(winreg.HKEY_LOCAL_MACHINE, directory))
# User fonts
for userdir in MSUserFontDirectories:
items.update(_win32RegistryFonts(winreg.HKEY_CURRENT_USER, userdir))
# Keep only paths with matching file extension.
return [str(path) for path in items if path.suffix.lower() in fontext]
@cbook.deprecated("3.1")
def OSXInstalledFonts(directories=None, fontext='ttf'):
"""Get list of font files on OS X."""
if directories is None:
directories = OSXFontDirectories
return [path
for directory in directories
for path in list_fonts(directory, get_fontext_synonyms(fontext))]
@lru_cache()
def _call_fc_list():
"""Cache and list the font filenames known to `fc-list`.
"""
# Delay the warning by 5s.
timer = Timer(5, lambda: _log.warning(
'Matplotlib is building the font cache using fc-list. '
'This may take a moment.'))
timer.start()
try:
out = subprocess.check_output(['fc-list', '--format=%{file}\\n'])
except (OSError, subprocess.CalledProcessError):
return []
finally:
timer.cancel()
return [os.fsdecode(fname) for fname in out.split(b'\n')]
def get_fontconfig_fonts(fontext='ttf'):
"""List the font filenames known to `fc-list` having the given extension.
"""
fontext = ['.' + ext for ext in get_fontext_synonyms(fontext)]
return [fname for fname in _call_fc_list()
if Path(fname).suffix.lower() in fontext]
def findSystemFonts(fontpaths=None, fontext='ttf'):
"""
Search for fonts in the specified font paths. If no paths are
given, will use a standard set of system paths, as well as the
list of fonts tracked by fontconfig if fontconfig is installed and
available. A list of TrueType fonts are returned by default with
AFM fonts as an option.
"""
fontfiles = set()
fontexts = get_fontext_synonyms(fontext)
if fontpaths is None:
if sys.platform == 'win32':
fontpaths = MSUserFontDirectories + [win32FontDirectory()]
# now get all installed fonts directly...
fontfiles.update(win32InstalledFonts(fontext=fontext))
else:
fontpaths = X11FontDirectories
if sys.platform == 'darwin':
fontpaths = [*X11FontDirectories, *OSXFontDirectories]
fontfiles.update(get_fontconfig_fonts(fontext))
elif isinstance(fontpaths, str):
fontpaths = [fontpaths]
for path in fontpaths:
fontfiles.update(map(os.path.abspath, list_fonts(path, fontexts)))
return [fname for fname in fontfiles if os.path.exists(fname)]
class FontEntry(object):
"""
A class for storing Font properties. It is used when populating
the font lookup dictionary.
"""
def __init__(self,
fname ='',
name ='',
style ='normal',
variant='normal',
weight ='normal',
stretch='normal',
size ='medium',
):
self.fname = fname
self.name = name
self.style = style
self.variant = variant
self.weight = weight
self.stretch = stretch
try:
self.size = str(float(size))
except ValueError:
self.size = size
def __repr__(self):
return "<Font '%s' (%s) %s %s %s %s>" % (
self.name, os.path.basename(self.fname), self.style, self.variant,
self.weight, self.stretch)
def ttfFontProperty(font):
"""
Extract information from a TrueType font file.
Parameters
----------
font : `.FT2Font`
The TrueType font file from which information will be extracted.
Returns
-------
`FontEntry`
The extracted font properties.
"""
name = font.family_name
# Styles are: italic, oblique, and normal (default)
sfnt = font.get_sfnt()
# These tables are actually mac_roman-encoded, but mac_roman support may be
# missing in some alternative Python implementations and we are only going
# to look for ASCII substrings, where any ASCII-compatible encoding works
# - or big-endian UTF-16, since important Microsoft fonts use that.
sfnt2 = (sfnt.get((1, 0, 0, 2), b'').decode('latin-1').lower() or
sfnt.get((3, 1, 0x0409, 2), b'').decode('utf_16_be').lower())
sfnt4 = (sfnt.get((1, 0, 0, 4), b'').decode('latin-1').lower() or
sfnt.get((3, 1, 0x0409, 4), b'').decode('utf_16_be').lower())
if sfnt4.find('oblique') >= 0:
style = 'oblique'
elif sfnt4.find('italic') >= 0:
style = 'italic'
elif sfnt2.find('regular') >= 0:
style = 'normal'
elif font.style_flags & ft2font.ITALIC:
style = 'italic'
else:
style = 'normal'
# Variants are: small-caps and normal (default)
# !!!! Untested
if name.lower() in ['capitals', 'small-caps']:
variant = 'small-caps'
else:
variant = 'normal'
weight = next((w for w in weight_dict if sfnt4.find(w) >= 0), None)
if not weight:
if font.style_flags & ft2font.BOLD:
weight = 700
else:
weight = 400
# Stretch can be absolute and relative
# Absolute stretches are: ultra-condensed, extra-condensed, condensed,
# semi-condensed, normal, semi-expanded, expanded, extra-expanded,
# and ultra-expanded.
# Relative stretches are: wider, narrower
# Child value is: inherit
if (sfnt4.find('narrow') >= 0 or sfnt4.find('condensed') >= 0 or
sfnt4.find('cond') >= 0):
stretch = 'condensed'
elif sfnt4.find('demi cond') >= 0:
stretch = 'semi-condensed'
elif sfnt4.find('wide') >= 0 or sfnt4.find('expanded') >= 0:
stretch = 'expanded'
else:
stretch = 'normal'
# Sizes can be absolute and relative.
# Absolute sizes are: xx-small, x-small, small, medium, large, x-large,
# and xx-large.
# Relative sizes are: larger, smaller
# Length value is an absolute font size, e.g., 12pt
# Percentage values are in 'em's. Most robust specification.
if not font.scalable:
raise NotImplementedError("Non-scalable fonts are not supported")
size = 'scalable'
return FontEntry(font.fname, name, style, variant, weight, stretch, size)
def afmFontProperty(fontpath, font):
"""
Extract information from an AFM font file.
Parameters
----------
font : `.AFM`
The AFM font file from which information will be extracted.
Returns
-------
`FontEntry`
The extracted font properties.
"""
name = font.get_familyname()
fontname = font.get_fontname().lower()
# Styles are: italic, oblique, and normal (default)
if font.get_angle() != 0 or 'italic' in name.lower():
style = 'italic'
elif 'oblique' in name.lower():
style = 'oblique'
else:
style = 'normal'
# Variants are: small-caps and normal (default)
# !!!! Untested
if name.lower() in ['capitals', 'small-caps']:
variant = 'small-caps'
else:
variant = 'normal'
weight = font.get_weight().lower()
if weight not in weight_dict:
weight = 'normal'
# Stretch can be absolute and relative
# Absolute stretches are: ultra-condensed, extra-condensed, condensed,
# semi-condensed, normal, semi-expanded, expanded, extra-expanded,
# and ultra-expanded.
# Relative stretches are: wider, narrower
# Child value is: inherit
if 'demi cond' in fontname:
stretch = 'semi-condensed'
elif 'narrow' in fontname or 'cond' in fontname:
stretch = 'condensed'
elif 'wide' in fontname or 'expanded' in fontname:
stretch = 'expanded'
else:
stretch = 'normal'
# Sizes can be absolute and relative.
# Absolute sizes are: xx-small, x-small, small, medium, large, x-large,
# and xx-large.
# Relative sizes are: larger, smaller
# Length value is an absolute font size, e.g., 12pt
# Percentage values are in 'em's. Most robust specification.
# All AFM fonts are apparently scalable.
size = 'scalable'
return FontEntry(fontpath, name, style, variant, weight, stretch, size)
def createFontList(fontfiles, fontext='ttf'):
"""
A function to create a font lookup list. The default is to create
a list of TrueType fonts. An AFM font list can optionally be
created.
"""
fontlist = []
# Add fonts from list of known font files.
seen = set()
for fpath in fontfiles:
_log.debug('createFontDict: %s', fpath)
fname = os.path.split(fpath)[1]
if fname in seen:
continue
if fontext == 'afm':
try:
with open(fpath, 'rb') as fh:
font = afm.AFM(fh)
except EnvironmentError:
_log.info("Could not open font file %s", fpath)
continue
except RuntimeError:
_log.info("Could not parse font file %s", fpath)
continue
try:
prop = afmFontProperty(fpath, font)
except KeyError as exc:
_log.info("Could not extract properties for %s: %s",
fpath, exc)
continue
else:
try:
font = ft2font.FT2Font(fpath)
except (OSError, RuntimeError) as exc:
_log.info("Could not open font file %s: %s", fpath, exc)
continue
except UnicodeError:
_log.info("Cannot handle unicode filenames")
continue
try:
prop = ttfFontProperty(font)
except (KeyError, RuntimeError, ValueError,
NotImplementedError) as exc:
_log.info("Could not extract properties for %s: %s",
fpath, exc)
continue
fontlist.append(prop)
seen.add(fname)
return fontlist
class FontProperties(object):
"""
A class for storing and manipulating font properties.
The font properties are those described in the `W3C Cascading
Style Sheet, Level 1
<http://www.w3.org/TR/1998/REC-CSS2-19980512/>`_ font
specification. The six properties are:
- family: A list of font names in decreasing order of priority.
The items may include a generic font family name, either
'serif', 'sans-serif', 'cursive', 'fantasy', or 'monospace'.
In that case, the actual font to be used will be looked up
from the associated rcParam.
- style: Either 'normal', 'italic' or 'oblique'.
- variant: Either 'normal' or 'small-caps'.
- stretch: A numeric value in the range 0-1000 or one of
'ultra-condensed', 'extra-condensed', 'condensed',
'semi-condensed', 'normal', 'semi-expanded', 'expanded',
'extra-expanded' or 'ultra-expanded'
- weight: A numeric value in the range 0-1000 or one of
'ultralight', 'light', 'normal', 'regular', 'book', 'medium',
'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy',
'extra bold', 'black'
- size: Either an relative value of 'xx-small', 'x-small',
'small', 'medium', 'large', 'x-large', 'xx-large' or an
absolute font size, e.g., 12
The default font property for TrueType fonts (as specified in the
default rcParams) is::
sans-serif, normal, normal, normal, normal, scalable.
Alternatively, a font may be specified using an absolute path to a
.ttf file, by using the *fname* kwarg.
The preferred usage of font sizes is to use the relative values,
e.g., 'large', instead of absolute font sizes, e.g., 12. This
approach allows all text sizes to be made larger or smaller based
on the font manager's default font size.
This class will also accept a fontconfig_ pattern_, if it is the only
argument provided. This support does not depend on fontconfig; we are
merely borrowing its pattern syntax for use here.
.. _fontconfig: https://www.freedesktop.org/wiki/Software/fontconfig/
.. _pattern:
https://www.freedesktop.org/software/fontconfig/fontconfig-user.html
Note that Matplotlib's internal font manager and fontconfig use a
different algorithm to lookup fonts, so the results of the same pattern
may be different in Matplotlib than in other applications that use
fontconfig.
"""
def __init__(self,
family = None,
style = None,
variant= None,
weight = None,
stretch= None,
size = None,
fname = None, # if set, it's a hardcoded filename to use
):
self._family = _normalize_font_family(rcParams['font.family'])
self._slant = rcParams['font.style']
self._variant = rcParams['font.variant']
self._weight = rcParams['font.weight']
self._stretch = rcParams['font.stretch']
self._size = rcParams['font.size']
self._file = None
if isinstance(family, str):
# Treat family as a fontconfig pattern if it is the only
# parameter provided.
if (style is None and
variant is None and
weight is None and
stretch is None and
size is None and
fname is None):
self.set_fontconfig_pattern(family)
return
self.set_family(family)
self.set_style(style)
self.set_variant(variant)
self.set_weight(weight)
self.set_stretch(stretch)
self.set_file(fname)
self.set_size(size)
def _parse_fontconfig_pattern(self, pattern):
return parse_fontconfig_pattern(pattern)
def __hash__(self):
l = (tuple(self.get_family()),
self.get_slant(),
self.get_variant(),
self.get_weight(),
self.get_stretch(),
self.get_size_in_points(),
self.get_file())
return hash(l)
def __eq__(self, other):
return hash(self) == hash(other)
def __str__(self):
return self.get_fontconfig_pattern()
def get_family(self):
"""
Return a list of font names that comprise the font family.
"""
return self._family
def get_name(self):
"""
Return the name of the font that best matches the font properties.
"""
return get_font(findfont(self)).family_name
def get_style(self):
"""
Return the font style. Values are: 'normal', 'italic' or 'oblique'.
"""
return self._slant
get_slant = get_style
def get_variant(self):
"""
Return the font variant. Values are: 'normal' or 'small-caps'.
"""
return self._variant
def get_weight(self):
"""
Set the font weight. Options are: A numeric value in the
range 0-1000 or one of 'light', 'normal', 'regular', 'book',
'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold',
'heavy', 'extra bold', 'black'
"""
return self._weight
def get_stretch(self):
"""
Return the font stretch or width. Options are: 'ultra-condensed',
'extra-condensed', 'condensed', 'semi-condensed', 'normal',
'semi-expanded', 'expanded', 'extra-expanded', 'ultra-expanded'.
"""
return self._stretch
def get_size(self):
"""
Return the font size.
"""
return self._size
def get_size_in_points(self):
return self._size
def get_file(self):
"""
Return the filename of the associated font.
"""
return self._file
def get_fontconfig_pattern(self):
"""
Get a fontconfig_ pattern_ suitable for looking up the font as
specified with fontconfig's ``fc-match`` utility.
This support does not depend on fontconfig; we are merely borrowing its
pattern syntax for use here.
"""
return generate_fontconfig_pattern(self)
def set_family(self, family):
"""
Change the font family. May be either an alias (generic name
is CSS parlance), such as: 'serif', 'sans-serif', 'cursive',
'fantasy', or 'monospace', a real font name or a list of real
font names. Real font names are not supported when
`text.usetex` is `True`.
"""
if family is None:
family = rcParams['font.family']
self._family = _normalize_font_family(family)
set_name = set_family
def set_style(self, style):
"""
Set the font style. Values are: 'normal', 'italic' or 'oblique'.
"""
if style is None:
style = rcParams['font.style']
cbook._check_in_list(['normal', 'italic', 'oblique'], style=style)
self._slant = style
set_slant = set_style
def set_variant(self, variant):
"""
Set the font variant. Values are: 'normal' or 'small-caps'.
"""
if variant is None:
variant = rcParams['font.variant']
cbook._check_in_list(['normal', 'small-caps'], variant=variant)
self._variant = variant
def set_weight(self, weight):
"""
Set the font weight. May be either a numeric value in the
range 0-1000 or one of 'ultralight', 'light', 'normal',
'regular', 'book', 'medium', 'roman', 'semibold', 'demibold',
'demi', 'bold', 'heavy', 'extra bold', 'black'
"""
if weight is None:
weight = rcParams['font.weight']
try:
weight = int(weight)
if weight < 0 or weight > 1000:
raise ValueError()
except ValueError:
if weight not in weight_dict:
raise ValueError("weight is invalid")
self._weight = weight
def set_stretch(self, stretch):
"""
Set the font stretch or width. Options are: 'ultra-condensed',
'extra-condensed', 'condensed', 'semi-condensed', 'normal',
'semi-expanded', 'expanded', 'extra-expanded' or
'ultra-expanded', or a numeric value in the range 0-1000.
"""
if stretch is None:
stretch = rcParams['font.stretch']
try:
stretch = int(stretch)
if stretch < 0 or stretch > 1000:
raise ValueError()
except ValueError:
if stretch not in stretch_dict:
raise ValueError("stretch is invalid")
self._stretch = stretch
def set_size(self, size):
"""
Set the font size. Either an relative value of 'xx-small',
'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'
or an absolute font size, e.g., 12.
"""
if size is None:
size = rcParams['font.size']
try:
size = float(size)
except ValueError:
try:
scale = font_scalings[size]
except KeyError:
raise ValueError(
"Size is invalid. Valid font size are "
+ ", ".join(map(str, font_scalings)))
else:
size = scale * FontManager.get_default_size()
if size < 1.0:
_log.info('Fontsize %1.2f < 1.0 pt not allowed by FreeType. '
'Setting fontsize = 1 pt', size)
size = 1.0
self._size = size
def set_file(self, file):
"""
Set the filename of the fontfile to use. In this case, all
other properties will be ignored.
"""
self._file = file
def set_fontconfig_pattern(self, pattern):
"""
Set the properties by parsing a fontconfig_ *pattern*.
This support does not depend on fontconfig; we are merely borrowing its
pattern syntax for use here.
"""
for key, val in self._parse_fontconfig_pattern(pattern).items():
if type(val) == list:
getattr(self, "set_" + key)(val[0])
else:
getattr(self, "set_" + key)(val)
def copy(self):
"""Return a copy of self."""
new = type(self)()
vars(new).update(vars(self))
return new
class JSONEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, FontManager):
return dict(o.__dict__, __class__='FontManager')
elif isinstance(o, FontEntry):
d = dict(o.__dict__, __class__='FontEntry')
try:
# Cache paths of fonts shipped with mpl relative to the mpl
# data path, which helps in the presence of venvs.
d["fname"] = str(
Path(d["fname"]).relative_to(mpl.get_data_path()))
except ValueError:
pass
return d
else:
return super().default(o)
def _json_decode(o):
cls = o.pop('__class__', None)
if cls is None:
return o
elif cls == 'FontManager':
r = FontManager.__new__(FontManager)
r.__dict__.update(o)
return r
elif cls == 'FontEntry':
r = FontEntry.__new__(FontEntry)
r.__dict__.update(o)
if not os.path.isabs(r.fname):
r.fname = os.path.join(mpl.get_data_path(), r.fname)
return r
else:
raise ValueError("don't know how to deserialize __class__=%s" % cls)
def json_dump(data, filename):
"""
Dumps a data structure as JSON in the named file.
Handles FontManager and its fields. File paths that are children of the
Matplotlib data path (typically, fonts shipped with Matplotlib) are stored
relative to that data path (to remain valid across virtualenvs).
"""
with open(filename, 'w') as fh:
try:
json.dump(data, fh, cls=JSONEncoder, indent=2)
except OSError as e:
_log.warning('Could not save font_manager cache {}'.format(e))
def json_load(filename):
"""
Loads a data structure as JSON from the named file.
Handles FontManager and its fields. Relative file paths are interpreted
as being relative to the Matplotlib data path, and transformed into
absolute paths.
"""
with open(filename, 'r') as fh:
return json.load(fh, object_hook=_json_decode)
def _normalize_font_family(family):
if isinstance(family, str):
family = [family]
return family
@cbook.deprecated("3.0")
class TempCache(object):
"""
A class to store temporary caches that are (a) not saved to disk
and (b) invalidated whenever certain font-related
rcParams---namely the family lookup lists---are changed or the
font cache is reloaded. This avoids the expensive linear search
through all fonts every time a font is looked up.
"""
# A list of rcparam names that, when changed, invalidated this
# cache.
invalidating_rcparams = (
'font.serif', 'font.sans-serif', 'font.cursive', 'font.fantasy',
'font.monospace')
def __init__(self):
self._lookup_cache = {}
self._last_rcParams = self.make_rcparams_key()
def make_rcparams_key(self):
return [id(fontManager)] + [
rcParams[param] for param in self.invalidating_rcparams]
def get(self, prop):
key = self.make_rcparams_key()
if key != self._last_rcParams:
self._lookup_cache = {}
self._last_rcParams = key
return self._lookup_cache.get(prop)
def set(self, prop, value):
key = self.make_rcparams_key()
if key != self._last_rcParams:
self._lookup_cache = {}
self._last_rcParams = key
self._lookup_cache[prop] = value
class FontManager(object):
"""
On import, the :class:`FontManager` singleton instance creates a
list of TrueType fonts based on the font properties: name, style,
variant, weight, stretch, and size. The :meth:`findfont` method
does a nearest neighbor search to find the font that most closely
matches the specification. If no good enough match is found, a
default font is returned.
"""
# Increment this version number whenever the font cache data
# format or behavior has changed and requires a existing font
# cache files to be rebuilt.
__version__ = 310
def __init__(self, size=None, weight='normal'):
self._version = self.__version__
self.__default_weight = weight
self.default_size = size
paths = [os.path.join(rcParams['datapath'], 'fonts', 'ttf'),
os.path.join(rcParams['datapath'], 'fonts', 'afm'),
os.path.join(rcParams['datapath'], 'fonts', 'pdfcorefonts')]
# Create list of font paths
for pathname in ['TTFPATH', 'AFMPATH']:
if pathname in os.environ:
ttfpath = os.environ[pathname]
if ttfpath.find(';') >= 0: # win32 style
paths.extend(ttfpath.split(';'))
elif ttfpath.find(':') >= 0: # unix style
paths.extend(ttfpath.split(':'))
else:
paths.append(ttfpath)
_log.debug('font search path %s', str(paths))
# Load TrueType fonts and create font dictionary.
self.defaultFamily = {
'ttf': 'DejaVu Sans',
'afm': 'Helvetica'}
ttffiles = findSystemFonts(paths) + findSystemFonts()
self.ttflist = createFontList(ttffiles)
afmfiles = (findSystemFonts(paths, fontext='afm')
+ findSystemFonts(fontext='afm'))
self.afmlist = createFontList(afmfiles, fontext='afm')
@cbook.deprecated("3.0")
@property
def ttffiles(self):
return [font.fname for font in self.ttflist]
@cbook.deprecated("3.0")
@property
def afmfiles(self):
return [font.fname for font in self.afmlist]
@property
def defaultFont(self):
# Lazily evaluated (findfont then caches the result) to avoid including
# the venv path in the json serialization.
return {ext: self.findfont(family, fontext=ext)
for ext, family in self.defaultFamily.items()}
def get_default_weight(self):
"""
Return the default font weight.
"""
return self.__default_weight
@staticmethod
def get_default_size():
"""
Return the default font size.
"""
return rcParams['font.size']
def set_default_weight(self, weight):
"""
Set the default font weight. The initial value is 'normal'.
"""
self.__default_weight = weight
# Each of the scoring functions below should return a value between
# 0.0 (perfect match) and 1.0 (terrible match)
def score_family(self, families, family2):
"""
Returns a match score between the list of font families in
*families* and the font family name *family2*.
An exact match at the head of the list returns 0.0.
A match further down the list will return between 0 and 1.
No match will return 1.0.
"""
if not isinstance(families, (list, tuple)):
families = [families]
elif len(families) == 0:
return 1.0
family2 = family2.lower()
step = 1 / len(families)
for i, family1 in enumerate(families):
family1 = family1.lower()
if family1 in font_family_aliases:
if family1 in ('sans', 'sans serif'):
family1 = 'sans-serif'
options = rcParams['font.' + family1]
options = [x.lower() for x in options]
if family2 in options:
idx = options.index(family2)
return (i + (idx / len(options))) * step
elif family1 == family2:
# The score should be weighted by where in the
# list the font was found.
return i * step
return 1.0
def score_style(self, style1, style2):
"""
Returns a match score between *style1* and *style2*.
An exact match returns 0.0.
A match between 'italic' and 'oblique' returns 0.1.
No match returns 1.0.
"""
if style1 == style2:
return 0.0
elif (style1 in ('italic', 'oblique')
and style2 in ('italic', 'oblique')):
return 0.1
return 1.0
def score_variant(self, variant1, variant2):
"""
Returns a match score between *variant1* and *variant2*.
An exact match returns 0.0, otherwise 1.0.
"""
if variant1 == variant2:
return 0.0
else:
return 1.0
def score_stretch(self, stretch1, stretch2):
"""
Returns a match score between *stretch1* and *stretch2*.
The result is the absolute value of the difference between the
CSS numeric values of *stretch1* and *stretch2*, normalized
between 0.0 and 1.0.
"""
try:
stretchval1 = int(stretch1)
except ValueError:
stretchval1 = stretch_dict.get(stretch1, 500)
try:
stretchval2 = int(stretch2)
except ValueError:
stretchval2 = stretch_dict.get(stretch2, 500)
return abs(stretchval1 - stretchval2) / 1000.0
def score_weight(self, weight1, weight2):
"""
Returns a match score between *weight1* and *weight2*.
The result is 0.0 if both weight1 and weight 2 are given as strings
and have the same value.
Otherwise, the result is the absolute value of the difference between
the CSS numeric values of *weight1* and *weight2*, normalized between
0.05 and 1.0.
"""
# exact match of the weight names, e.g. weight1 == weight2 == "regular"
if cbook._str_equal(weight1, weight2):
return 0.0
w1 = weight1 if isinstance(weight1, Number) else weight_dict[weight1]
w2 = weight2 if isinstance(weight2, Number) else weight_dict[weight2]
return 0.95 * (abs(w1 - w2) / 1000) + 0.05
def score_size(self, size1, size2):
"""
Returns a match score between *size1* and *size2*.
If *size2* (the size specified in the font file) is 'scalable', this
function always returns 0.0, since any font size can be generated.
Otherwise, the result is the absolute distance between *size1* and
*size2*, normalized so that the usual range of font sizes (6pt -
72pt) will lie between 0.0 and 1.0.
"""
if size2 == 'scalable':
return 0.0
# Size value should have already been
try:
sizeval1 = float(size1)
except ValueError:
sizeval1 = self.default_size * font_scalings[size1]
try:
sizeval2 = float(size2)
except ValueError:
return 1.0
return abs(sizeval1 - sizeval2) / 72
def findfont(self, prop, fontext='ttf', directory=None,
fallback_to_default=True, rebuild_if_missing=True):
"""
Find a font that most closely matches the given font properties.
Parameters
----------
prop : str or `~matplotlib.font_manager.FontProperties`
The font properties to search for. This can be either a
`.FontProperties` object or a string defining a
`fontconfig patterns`_.
fontext : {'ttf', 'afm'}, optional, default: 'ttf'
The extension of the font file:
- 'ttf': TrueType and OpenType fonts (.ttf, .ttc, .otf)
- 'afm': Adobe Font Metrics (.afm)
directory : str, optional
If given, only search this directory and its subdirectories.
fallback_to_default : bool
If True, will fallback to the default font family (usually
"DejaVu Sans" or "Helvetica") if the first lookup hard-fails.
rebuild_if_missing : bool
Whether to rebuild the font cache and search again if no match
is found.
Returns
-------
fontfile : str
The filename of the best matching font.
Notes
-----
This performs a nearest neighbor search. Each font is given a
similarity score to the target font properties. The first font with
the highest score is returned. If no matches below a certain
threshold are found, the default font (usually DejaVu Sans) is
returned.
The result is cached, so subsequent lookups don't have to
perform the O(n) nearest neighbor search.
See the `W3C Cascading Style Sheet, Level 1
<http://www.w3.org/TR/1998/REC-CSS2-19980512/>`_ documentation
for a description of the font finding algorithm.
.. _fontconfig patterns:
https://www.freedesktop.org/software/fontconfig/fontconfig-user.html
"""
# Pass the relevant rcParams (and the font manager, as `self`) to
# _findfont_cached so to prevent using a stale cache entry after an
# rcParam was changed.
rc_params = tuple(tuple(rcParams[key]) for key in [
"font.serif", "font.sans-serif", "font.cursive", "font.fantasy",
"font.monospace"])
return self._findfont_cached(
prop, fontext, directory, fallback_to_default, rebuild_if_missing,
rc_params)
@lru_cache()
def _findfont_cached(self, prop, fontext, directory, fallback_to_default,
rebuild_if_missing, rc_params):
if not isinstance(prop, FontProperties):
prop = FontProperties(prop)
fname = prop.get_file()
if fname is not None:
return fname
if fontext == 'afm':
fontlist = self.afmlist
else:
fontlist = self.ttflist
best_score = 1e64
best_font = None
_log.debug('findfont: Matching %s.', prop)
for font in fontlist:
if (directory is not None and
Path(directory) not in Path(font.fname).parents):
continue
# Matching family should have top priority, so multiply it by 10.
score = (self.score_family(prop.get_family(), font.name) * 10
+ self.score_style(prop.get_style(), font.style)
+ self.score_variant(prop.get_variant(), font.variant)
+ self.score_weight(prop.get_weight(), font.weight)
+ self.score_stretch(prop.get_stretch(), font.stretch)
+ self.score_size(prop.get_size(), font.size))
_log.debug('findfont: score(%s) = %s', font, score)
if score < best_score:
best_score = score
best_font = font
if score == 0:
break
if best_font is None or best_score >= 10.0:
if fallback_to_default:
_log.warning(
'findfont: Font family %s not found. Falling back to %s.',
prop.get_family(), self.defaultFamily[fontext])
default_prop = prop.copy()
default_prop.set_family(self.defaultFamily[fontext])
return self.findfont(default_prop, fontext, directory, False)
else:
# This is a hard fail -- we can't find anything reasonable,
# so just return the DejaVuSans.ttf
_log.warning('findfont: Could not match %s. Returning %s.',
prop, self.defaultFont[fontext])
result = self.defaultFont[fontext]
else:
_log.debug('findfont: Matching %s to %s (%r) with score of %f.',
prop, best_font.name, best_font.fname, best_score)
result = best_font.fname
if not os.path.isfile(result):
if rebuild_if_missing:
_log.info(
'findfont: Found a missing font file. Rebuilding cache.')
_rebuild()
return fontManager.findfont(
prop, fontext, directory, True, False)
else:
raise ValueError("No valid font could be found")
return result
@lru_cache()
def is_opentype_cff_font(filename):
"""
Return whether the given font is a Postscript Compact Font Format Font
embedded in an OpenType wrapper. Used by the PostScript and PDF backends
that can not subset these fonts.
"""
if os.path.splitext(filename)[1].lower() == '.otf':
with open(filename, 'rb') as fd:
return fd.read(4) == b"OTTO"
else:
return False
_get_font = lru_cache(64)(ft2font.FT2Font)
_fmcache = os.path.join(
mpl.get_cachedir(), 'fontlist-v{}.json'.format(FontManager.__version__))
fontManager = None
def get_font(filename, hinting_factor=None):
if hinting_factor is None:
hinting_factor = rcParams['text.hinting_factor']
return _get_font(filename, hinting_factor)
def _rebuild():
global fontManager
fontManager = FontManager()
with cbook._lock_path(_fmcache):
json_dump(fontManager, _fmcache)
_log.info("generated new fontManager")
try:
fontManager = json_load(_fmcache)
except Exception:
_rebuild()
else:
if getattr(fontManager, '_version', object()) != FontManager.__version__:
_rebuild()
else:
_log.debug("Using fontManager instance from %s", _fmcache)
findfont = fontManager.findfont
|
338599c31e2075cfdcab5ef5a218de2ad9a3cc119fd95a4ba3106d7a08b74d8f
|
"""
Builtin colormaps, colormap handling utilities, and the `ScalarMappable` mixin.
.. seealso::
:doc:`/gallery/color/colormap_reference` for a list of builtin
colormaps.
:doc:`/tutorials/colors/colormap-manipulation` for examples of how to
make colormaps and
:doc:`/tutorials/colors/colormaps` an in-depth discussion of
choosing colormaps.
:doc:`/tutorials/colors/colormapnorms` for more details about data
normalization
"""
import functools
import numpy as np
from numpy import ma
import matplotlib as mpl
import matplotlib.colors as colors
import matplotlib.cbook as cbook
from matplotlib._cm import datad
from matplotlib._cm_listed import cmaps as cmaps_listed
cmap_d = {}
# reverse all the colormaps.
# reversed colormaps have '_r' appended to the name.
def _reverser(f, x=None):
"""Helper such that ``_reverser(f)(x) == f(1 - x)``."""
if x is None:
# Returning a partial object keeps it picklable.
return functools.partial(_reverser, f)
return f(1 - x)
def revcmap(data):
"""Can only handle specification *data* in dictionary format."""
data_r = {}
for key, val in data.items():
if callable(val):
valnew = _reverser(val)
# This doesn't work: lambda x: val(1-x)
# The same "val" (the first one) is used
# each time, so the colors are identical
# and the result is shades of gray.
else:
# Flip x and exchange the y values facing x = 0 and x = 1.
valnew = [(1.0 - x, y1, y0) for x, y0, y1 in reversed(val)]
data_r[key] = valnew
return data_r
def _reverse_cmap_spec(spec):
"""Reverses cmap specification *spec*, can handle both dict and tuple
type specs."""
if 'listed' in spec:
return {'listed': spec['listed'][::-1]}
if 'red' in spec:
return revcmap(spec)
else:
revspec = list(reversed(spec))
if len(revspec[0]) == 2: # e.g., (1, (1.0, 0.0, 1.0))
revspec = [(1.0 - a, b) for a, b in revspec]
return revspec
def _generate_cmap(name, lutsize):
"""Generates the requested cmap from its *name*. The lut size is
*lutsize*."""
spec = datad[name]
# Generate the colormap object.
if 'red' in spec:
return colors.LinearSegmentedColormap(name, spec, lutsize)
elif 'listed' in spec:
return colors.ListedColormap(spec['listed'], name)
else:
return colors.LinearSegmentedColormap.from_list(name, spec, lutsize)
LUTSIZE = mpl.rcParams['image.lut']
# Generate the reversed specifications (all at once, to avoid
# modify-when-iterating).
datad.update({cmapname + '_r': _reverse_cmap_spec(spec)
for cmapname, spec in datad.items()})
# Precache the cmaps with ``lutsize = LUTSIZE``.
# Also add the reversed ones added in the section above:
for cmapname in datad:
cmap_d[cmapname] = _generate_cmap(cmapname, LUTSIZE)
cmap_d.update(cmaps_listed)
locals().update(cmap_d)
# Continue with definitions ...
def register_cmap(name=None, cmap=None, data=None, lut=None):
"""
Add a colormap to the set recognized by :func:`get_cmap`.
It can be used in two ways::
register_cmap(name='swirly', cmap=swirly_cmap)
register_cmap(name='choppy', data=choppydata, lut=128)
In the first case, *cmap* must be a :class:`matplotlib.colors.Colormap`
instance. The *name* is optional; if absent, the name will
be the :attr:`~matplotlib.colors.Colormap.name` attribute of the *cmap*.
In the second case, the three arguments are passed to
the :class:`~matplotlib.colors.LinearSegmentedColormap` initializer,
and the resulting colormap is registered.
"""
if name is None:
try:
name = cmap.name
except AttributeError:
raise ValueError("Arguments must include a name or a Colormap")
if not isinstance(name, str):
raise ValueError("Colormap name must be a string")
if isinstance(cmap, colors.Colormap):
cmap_d[name] = cmap
return
# For the remainder, let exceptions propagate.
if lut is None:
lut = mpl.rcParams['image.lut']
cmap = colors.LinearSegmentedColormap(name, data, lut)
cmap_d[name] = cmap
def get_cmap(name=None, lut=None):
"""
Get a colormap instance, defaulting to rc values if *name* is None.
Colormaps added with :func:`register_cmap` take precedence over
built-in colormaps.
If *name* is a :class:`matplotlib.colors.Colormap` instance, it will be
returned.
If *lut* is not None it must be an integer giving the number of
entries desired in the lookup table, and *name* must be a standard
mpl colormap name.
"""
if name is None:
name = mpl.rcParams['image.cmap']
if isinstance(name, colors.Colormap):
return name
cbook._check_in_list(sorted(cmap_d), name=name)
if lut is None:
return cmap_d[name]
else:
return cmap_d[name]._resample(lut)
class ScalarMappable(object):
"""
This is a mixin class to support scalar data to RGBA mapping.
The ScalarMappable makes use of data normalization before returning
RGBA colors from the given colormap.
"""
def __init__(self, norm=None, cmap=None):
r"""
Parameters
----------
norm : :class:`matplotlib.colors.Normalize` instance
The normalizing object which scales data, typically into the
interval ``[0, 1]``.
If *None*, *norm* defaults to a *colors.Normalize* object which
initializes its scaling based on the first data processed.
cmap : str or :class:`~matplotlib.colors.Colormap` instance
The colormap used to map normalized data values to RGBA colors.
"""
self.callbacksSM = cbook.CallbackRegistry()
if cmap is None:
cmap = get_cmap()
if norm is None:
norm = colors.Normalize()
self._A = None
#: The Normalization instance of this ScalarMappable.
self.norm = norm
#: The Colormap instance of this ScalarMappable.
self.cmap = get_cmap(cmap)
#: The last colorbar associated with this ScalarMappable. May be None.
self.colorbar = None
self.update_dict = {'array': False}
def to_rgba(self, x, alpha=None, bytes=False, norm=True):
"""
Return a normalized rgba array corresponding to *x*.
In the normal case, *x* is a 1-D or 2-D sequence of scalars, and
the corresponding ndarray of rgba values will be returned,
based on the norm and colormap set for this ScalarMappable.
There is one special case, for handling images that are already
rgb or rgba, such as might have been read from an image file.
If *x* is an ndarray with 3 dimensions,
and the last dimension is either 3 or 4, then it will be
treated as an rgb or rgba array, and no mapping will be done.
The array can be uint8, or it can be floating point with
values in the 0-1 range; otherwise a ValueError will be raised.
If it is a masked array, the mask will be ignored.
If the last dimension is 3, the *alpha* kwarg (defaulting to 1)
will be used to fill in the transparency. If the last dimension
is 4, the *alpha* kwarg is ignored; it does not
replace the pre-existing alpha. A ValueError will be raised
if the third dimension is other than 3 or 4.
In either case, if *bytes* is *False* (default), the rgba
array will be floats in the 0-1 range; if it is *True*,
the returned rgba array will be uint8 in the 0 to 255 range.
If norm is False, no normalization of the input data is
performed, and it is assumed to be in the range (0-1).
"""
# First check for special case, image input:
try:
if x.ndim == 3:
if x.shape[2] == 3:
if alpha is None:
alpha = 1
if x.dtype == np.uint8:
alpha = np.uint8(alpha * 255)
m, n = x.shape[:2]
xx = np.empty(shape=(m, n, 4), dtype=x.dtype)
xx[:, :, :3] = x
xx[:, :, 3] = alpha
elif x.shape[2] == 4:
xx = x
else:
raise ValueError("third dimension must be 3 or 4")
if xx.dtype.kind == 'f':
if norm and (xx.max() > 1 or xx.min() < 0):
raise ValueError("Floating point image RGB values "
"must be in the 0..1 range.")
if bytes:
xx = (xx * 255).astype(np.uint8)
elif xx.dtype == np.uint8:
if not bytes:
xx = xx.astype(np.float32) / 255
else:
raise ValueError("Image RGB array must be uint8 or "
"floating point; found %s" % xx.dtype)
return xx
except AttributeError:
# e.g., x is not an ndarray; so try mapping it
pass
# This is the normal case, mapping a scalar array:
x = ma.asarray(x)
if norm:
x = self.norm(x)
rgba = self.cmap(x, alpha=alpha, bytes=bytes)
return rgba
def set_array(self, A):
"""Set the image array from numpy array *A*.
Parameters
----------
A : ndarray
"""
self._A = A
self.update_dict['array'] = True
def get_array(self):
'Return the array'
return self._A
def get_cmap(self):
'return the colormap'
return self.cmap
def get_clim(self):
'return the min, max of the color limits for image scaling'
return self.norm.vmin, self.norm.vmax
def set_clim(self, vmin=None, vmax=None):
"""
set the norm limits for image scaling; if *vmin* is a length2
sequence, interpret it as ``(vmin, vmax)`` which is used to
support setp
ACCEPTS: a length 2 sequence of floats; may be overridden in methods
that have ``vmin`` and ``vmax`` kwargs.
"""
if vmax is None:
try:
vmin, vmax = vmin
except (TypeError, ValueError):
pass
if vmin is not None:
self.norm.vmin = colors._sanitize_extrema(vmin)
if vmax is not None:
self.norm.vmax = colors._sanitize_extrema(vmax)
self.changed()
def get_alpha(self):
"""
Returns
-------
alpha : float
Always returns 1.
"""
# This method is intended to be overridden by Artist sub-classes
return 1.
def set_cmap(self, cmap):
"""
set the colormap for luminance data
Parameters
----------
cmap : colormap or registered colormap name
"""
cmap = get_cmap(cmap)
self.cmap = cmap
self.changed()
def set_norm(self, norm):
"""Set the normalization instance.
Parameters
----------
norm : `.Normalize`
Notes
-----
If there are any colorbars using the mappable for this norm, setting
the norm of the mappable will reset the norm, locator, and formatters
on the colorbar to default.
"""
if norm is None:
norm = colors.Normalize()
self.norm = norm
self.changed()
def autoscale(self):
"""
Autoscale the scalar limits on the norm instance using the
current array
"""
if self._A is None:
raise TypeError('You must first set_array for mappable')
self.norm.autoscale(self._A)
self.changed()
def autoscale_None(self):
"""
Autoscale the scalar limits on the norm instance using the
current array, changing only limits that are None
"""
if self._A is None:
raise TypeError('You must first set_array for mappable')
self.norm.autoscale_None(self._A)
self.changed()
def add_checker(self, checker):
"""
Add an entry to a dictionary of boolean flags
that are set to True when the mappable is changed.
"""
self.update_dict[checker] = False
def check_update(self, checker):
"""
If mappable has changed since the last check,
return True; else return False
"""
if self.update_dict[checker]:
self.update_dict[checker] = False
return True
return False
def changed(self):
"""
Call this whenever the mappable is changed to notify all the
callbackSM listeners to the 'changed' signal
"""
self.callbacksSM.process('changed', self)
for key in self.update_dict:
self.update_dict[key] = True
self.stale = True
|
4d86c96ab2cde7a72c370340257f255a6ab9c0052466ee3b5295bbc025100fc6
|
"""
Conventions:
"constrain_x" means to constrain the variable with either
another kiwisolver variable, or a float. i.e. `constrain_width(0.2)`
will set a constraint that the width has to be 0.2 and this constraint is
permanent - i.e. it will not be removed if it becomes obsolete.
"edit_x" means to set x to a value (just a float), and that this value can
change. So `edit_width(0.2)` will set width to be 0.2, but `edit_width(0.3)`
will allow it to change to 0.3 later. Note that these values are still just
"suggestions" in `kiwisolver` parlance, and could be over-ridden by
other constrains.
"""
import itertools
import kiwisolver as kiwi
import logging
import numpy as np
_log = logging.getLogger(__name__)
# renderers can be complicated
def get_renderer(fig):
if fig._cachedRenderer:
renderer = fig._cachedRenderer
else:
canvas = fig.canvas
if canvas and hasattr(canvas, "get_renderer"):
renderer = canvas.get_renderer()
else:
# not sure if this can happen
# seems to with PDF...
_log.info("constrained_layout : falling back to Agg renderer")
from matplotlib.backends.backend_agg import FigureCanvasAgg
canvas = FigureCanvasAgg(fig)
renderer = canvas.get_renderer()
return renderer
class LayoutBox(object):
"""
Basic rectangle representation using kiwi solver variables
"""
def __init__(self, parent=None, name='', tightwidth=False,
tightheight=False, artist=None,
lower_left=(0, 0), upper_right=(1, 1), pos=False,
subplot=False, h_pad=None, w_pad=None):
Variable = kiwi.Variable
self.parent = parent
self.name = name
sn = self.name + '_'
if parent is None:
self.solver = kiwi.Solver()
self.constrained_layout_called = 0
else:
self.solver = parent.solver
self.constrained_layout_called = None
# parent wants to know about this child!
parent.add_child(self)
# keep track of artist associated w/ this layout. Can be none
self.artist = artist
# keep track if this box is supposed to be a pos that is constrained
# by the parent.
self.pos = pos
# keep track of whether we need to match this subplot up with others.
self.subplot = subplot
# we need the str below for Py 2 which complains the string is unicode
self.top = Variable(str(sn + 'top'))
self.bottom = Variable(str(sn + 'bottom'))
self.left = Variable(str(sn + 'left'))
self.right = Variable(str(sn + 'right'))
self.width = Variable(str(sn + 'width'))
self.height = Variable(str(sn + 'height'))
self.h_center = Variable(str(sn + 'h_center'))
self.v_center = Variable(str(sn + 'v_center'))
self.min_width = Variable(str(sn + 'min_width'))
self.min_height = Variable(str(sn + 'min_height'))
self.pref_width = Variable(str(sn + 'pref_width'))
self.pref_height = Variable(str(sn + 'pref_height'))
# margins are only used for axes-position layout boxes. maybe should
# be a separate subclass:
self.left_margin = Variable(str(sn + 'left_margin'))
self.right_margin = Variable(str(sn + 'right_margin'))
self.bottom_margin = Variable(str(sn + 'bottom_margin'))
self.top_margin = Variable(str(sn + 'top_margin'))
# mins
self.left_margin_min = Variable(str(sn + 'left_margin_min'))
self.right_margin_min = Variable(str(sn + 'right_margin_min'))
self.bottom_margin_min = Variable(str(sn + 'bottom_margin_min'))
self.top_margin_min = Variable(str(sn + 'top_margin_min'))
right, top = upper_right
left, bottom = lower_left
self.tightheight = tightheight
self.tightwidth = tightwidth
self.add_constraints()
self.children = []
self.subplotspec = None
if self.pos:
self.constrain_margins()
self.h_pad = h_pad
self.w_pad = w_pad
def constrain_margins(self):
"""
Only do this for pos. This sets a variable distance
margin between the position of the axes and the outer edge of
the axes.
Margins are variable because they change with the figure size.
Margin minimums are set to make room for axes decorations. However,
the margins can be larger if we are mathicng the position size to
other axes.
"""
sol = self.solver
# left
if not sol.hasEditVariable(self.left_margin_min):
sol.addEditVariable(self.left_margin_min, 'strong')
sol.suggestValue(self.left_margin_min, 0.0001)
c = (self.left_margin == self.left - self.parent.left)
self.solver.addConstraint(c | 'required')
c = (self.left_margin >= self.left_margin_min)
self.solver.addConstraint(c | 'strong')
# right
if not sol.hasEditVariable(self.right_margin_min):
sol.addEditVariable(self.right_margin_min, 'strong')
sol.suggestValue(self.right_margin_min, 0.0001)
c = (self.right_margin == self.parent.right - self.right)
self.solver.addConstraint(c | 'required')
c = (self.right_margin >= self.right_margin_min)
self.solver.addConstraint(c | 'required')
# bottom
if not sol.hasEditVariable(self.bottom_margin_min):
sol.addEditVariable(self.bottom_margin_min, 'strong')
sol.suggestValue(self.bottom_margin_min, 0.0001)
c = (self.bottom_margin == self.bottom - self.parent.bottom)
self.solver.addConstraint(c | 'required')
c = (self.bottom_margin >= self.bottom_margin_min)
self.solver.addConstraint(c | 'required')
# top
if not sol.hasEditVariable(self.top_margin_min):
sol.addEditVariable(self.top_margin_min, 'strong')
sol.suggestValue(self.top_margin_min, 0.0001)
c = (self.top_margin == self.parent.top - self.top)
self.solver.addConstraint(c | 'required')
c = (self.top_margin >= self.top_margin_min)
self.solver.addConstraint(c | 'required')
def add_child(self, child):
self.children += [child]
def remove_child(self, child):
try:
self.children.remove(child)
except ValueError:
_log.info("Tried to remove child that doesn't belong to parent")
def add_constraints(self):
sol = self.solver
# never let width and height go negative.
for i in [self.min_width, self.min_height]:
sol.addEditVariable(i, 1e9)
sol.suggestValue(i, 0.0)
# define relation ships between things thing width and right and left
self.hard_constraints()
# self.soft_constraints()
if self.parent:
self.parent_constrain()
# sol.updateVariables()
def parent_constrain(self):
parent = self.parent
hc = [self.left >= parent.left,
self.bottom >= parent.bottom,
self.top <= parent.top,
self.right <= parent.right]
for c in hc:
self.solver.addConstraint(c | 'required')
def hard_constraints(self):
hc = [self.width == self.right - self.left,
self.height == self.top - self.bottom,
self.h_center == (self.left + self.right) * 0.5,
self.v_center == (self.top + self.bottom) * 0.5,
self.width >= self.min_width,
self.height >= self.min_height]
for c in hc:
self.solver.addConstraint(c | 'required')
def soft_constraints(self):
sol = self.solver
if self.tightwidth:
suggest = 0.
else:
suggest = 20.
c = (self.pref_width == suggest)
for i in c:
sol.addConstraint(i | 'required')
if self.tightheight:
suggest = 0.
else:
suggest = 20.
c = (self.pref_height == suggest)
for i in c:
sol.addConstraint(i | 'required')
c = [(self.width >= suggest),
(self.height >= suggest)]
for i in c:
sol.addConstraint(i | 150000)
def set_parent(self, parent):
''' replace the parent of this with the new parent
'''
self.parent = parent
self.parent_constrain()
def constrain_geometry(self, left, bottom, right, top, strength='strong'):
hc = [self.left == left,
self.right == right,
self.bottom == bottom,
self.top == top]
for c in hc:
self.solver.addConstraint(c | strength)
# self.solver.updateVariables()
def constrain_same(self, other, strength='strong'):
"""
Make the layoutbox have same position as other layoutbox
"""
hc = [self.left == other.left,
self.right == other.right,
self.bottom == other.bottom,
self.top == other.top]
for c in hc:
self.solver.addConstraint(c | strength)
def constrain_left_margin(self, margin, strength='strong'):
c = (self.left == self.parent.left + margin)
self.solver.addConstraint(c | strength)
def edit_left_margin_min(self, margin):
self.solver.suggestValue(self.left_margin_min, margin)
def constrain_right_margin(self, margin, strength='strong'):
c = (self.right == self.parent.right - margin)
self.solver.addConstraint(c | strength)
def edit_right_margin_min(self, margin):
self.solver.suggestValue(self.right_margin_min, margin)
def constrain_bottom_margin(self, margin, strength='strong'):
c = (self.bottom == self.parent.bottom + margin)
self.solver.addConstraint(c | strength)
def edit_bottom_margin_min(self, margin):
self.solver.suggestValue(self.bottom_margin_min, margin)
def constrain_top_margin(self, margin, strength='strong'):
c = (self.top == self.parent.top - margin)
self.solver.addConstraint(c | strength)
def edit_top_margin_min(self, margin):
self.solver.suggestValue(self.top_margin_min, margin)
def get_rect(self):
return (self.left.value(), self.bottom.value(),
self.width.value(), self.height.value())
def update_variables(self):
'''
Update *all* the variables that are part of the solver this LayoutBox
is created with
'''
self.solver.updateVariables()
def edit_height(self, height, strength='strong'):
'''
Set the height of the layout box.
This is done as an editable variable so that the value can change
due to resizing.
'''
sol = self.solver
for i in [self.height]:
if not sol.hasEditVariable(i):
sol.addEditVariable(i, strength)
sol.suggestValue(self.height, height)
def constrain_height(self, height, strength='strong'):
'''
Constrain the height of the layout box. height is
either a float or a layoutbox.height.
'''
c = (self.height == height)
self.solver.addConstraint(c | strength)
def constrain_height_min(self, height, strength='strong'):
c = (self.height >= height)
self.solver.addConstraint(c | strength)
def edit_width(self, width, strength='strong'):
sol = self.solver
for i in [self.width]:
if not sol.hasEditVariable(i):
sol.addEditVariable(i, strength)
sol.suggestValue(self.width, width)
def constrain_width(self, width, strength='strong'):
'''
Constrain the width of the layout box. `width` is
either a float or a layoutbox.width.
'''
c = (self.width == width)
self.solver.addConstraint(c | strength)
def constrain_width_min(self, width, strength='strong'):
c = (self.width >= width)
self.solver.addConstraint(c | strength)
def constrain_left(self, left, strength='strong'):
c = (self.left == left)
self.solver.addConstraint(c | strength)
def constrain_bottom(self, bottom, strength='strong'):
c = (self.bottom == bottom)
self.solver.addConstraint(c | strength)
def constrain_right(self, right, strength='strong'):
c = (self.right == right)
self.solver.addConstraint(c | strength)
def constrain_top(self, top, strength='strong'):
c = (self.top == top)
self.solver.addConstraint(c | strength)
def _is_subplotspec_layoutbox(self):
'''
Helper to check if this layoutbox is the layoutbox of a
subplotspec
'''
name = (self.name).split('.')[-1]
return name[:2] == 'ss'
def _is_gridspec_layoutbox(self):
'''
Helper to check if this layoutbox is the layoutbox of a
gridspec
'''
name = (self.name).split('.')[-1]
return name[:8] == 'gridspec'
def find_child_subplots(self):
'''
Find children of this layout box that are subplots. We want to line
poss up, and this is an easy way to find them all.
'''
if self.subplot:
subplots = [self]
else:
subplots = []
for child in self.children:
subplots += child.find_child_subplots()
return subplots
def layout_from_subplotspec(self, subspec,
name='', artist=None, pos=False):
''' Make a layout box from a subplotspec. The layout box is
constrained to be a fraction of the width/height of the parent,
and be a fraction of the parent width/height from the left/bottom
of the parent. Therefore the parent can move around and the
layout for the subplot spec should move with it.
The parent is *usually* the gridspec that made the subplotspec.??
'''
lb = LayoutBox(parent=self, name=name, artist=artist, pos=pos)
gs = subspec.get_gridspec()
nrows, ncols = gs.get_geometry()
parent = self.parent
# OK, now, we want to set the position of this subplotspec
# based on its subplotspec parameters. The new gridspec will inherit.
# from gridspec. prob should be new method in gridspec
left = 0.0
right = 1.0
bottom = 0.0
top = 1.0
totWidth = right-left
totHeight = top-bottom
hspace = 0.
wspace = 0.
# calculate accumulated heights of columns
cellH = totHeight / (nrows + hspace * (nrows - 1))
sepH = hspace*cellH
if gs._row_height_ratios is not None:
netHeight = cellH * nrows
tr = float(sum(gs._row_height_ratios))
cellHeights = [netHeight*r/tr for r in gs._row_height_ratios]
else:
cellHeights = [cellH] * nrows
sepHeights = [0] + ([sepH] * (nrows - 1))
cellHs = np.add.accumulate(np.ravel(
list(zip(sepHeights, cellHeights))))
# calculate accumulated widths of rows
cellW = totWidth/(ncols + wspace * (ncols - 1))
sepW = wspace*cellW
if gs._col_width_ratios is not None:
netWidth = cellW * ncols
tr = float(sum(gs._col_width_ratios))
cellWidths = [netWidth * r / tr for r in gs._col_width_ratios]
else:
cellWidths = [cellW] * ncols
sepWidths = [0] + ([sepW] * (ncols - 1))
cellWs = np.add.accumulate(np.ravel(list(zip(sepWidths, cellWidths))))
figTops = [top - cellHs[2 * rowNum] for rowNum in range(nrows)]
figBottoms = [top - cellHs[2 * rowNum + 1] for rowNum in range(nrows)]
figLefts = [left + cellWs[2 * colNum] for colNum in range(ncols)]
figRights = [left + cellWs[2 * colNum + 1] for colNum in range(ncols)]
rowNum1, colNum1 = divmod(subspec.num1, ncols)
rowNum2, colNum2 = divmod(subspec.num2, ncols)
figBottom = min(figBottoms[rowNum1], figBottoms[rowNum2])
figTop = max(figTops[rowNum1], figTops[rowNum2])
figLeft = min(figLefts[colNum1], figLefts[colNum2])
figRight = max(figRights[colNum1], figRights[colNum2])
# These are numbers relative to 0,0,1,1. Need to constrain
# relative to parent.
width = figRight - figLeft
height = figTop - figBottom
parent = self.parent
cs = [self.left == parent.left + parent.width * figLeft,
self.bottom == parent.bottom + parent.height * figBottom,
self.width == parent.width * width,
self.height == parent.height * height]
for c in cs:
self.solver.addConstraint(c | 'required')
return lb
def __repr__(self):
args = (self.name, self.left.value(), self.bottom.value(),
self.right.value(), self.top.value())
return ('LayoutBox: %25s, (left: %1.3f) (bot: %1.3f) '
'(right: %1.3f) (top: %1.3f) ') % args
# Utility functions that act on layoutboxes...
def hstack(boxes, padding=0, strength='strong'):
'''
Stack LayoutBox instances from left to right.
`padding` is in figure-relative units.
'''
for i in range(1, len(boxes)):
c = (boxes[i-1].right + padding <= boxes[i].left)
boxes[i].solver.addConstraint(c | strength)
def hpack(boxes, padding=0, strength='strong'):
'''
Stack LayoutBox instances from left to right.
'''
for i in range(1, len(boxes)):
c = (boxes[i-1].right + padding == boxes[i].left)
boxes[i].solver.addConstraint(c | strength)
def vstack(boxes, padding=0, strength='strong'):
'''
Stack LayoutBox instances from top to bottom
'''
for i in range(1, len(boxes)):
c = (boxes[i-1].bottom - padding >= boxes[i].top)
boxes[i].solver.addConstraint(c | strength)
def vpack(boxes, padding=0, strength='strong'):
'''
Stack LayoutBox instances from top to bottom
'''
for i in range(1, len(boxes)):
c = (boxes[i-1].bottom - padding >= boxes[i].top)
boxes[i].solver.addConstraint(c | strength)
def match_heights(boxes, height_ratios=None, strength='medium'):
'''
Stack LayoutBox instances from top to bottom
'''
if height_ratios is None:
height_ratios = np.ones(len(boxes))
for i in range(1, len(boxes)):
c = (boxes[i-1].height ==
boxes[i].height*height_ratios[i-1]/height_ratios[i])
boxes[i].solver.addConstraint(c | strength)
def match_widths(boxes, width_ratios=None, strength='medium'):
'''
Stack LayoutBox instances from top to bottom
'''
if width_ratios is None:
width_ratios = np.ones(len(boxes))
for i in range(1, len(boxes)):
c = (boxes[i-1].width ==
boxes[i].width*width_ratios[i-1]/width_ratios[i])
boxes[i].solver.addConstraint(c | strength)
def vstackeq(boxes, padding=0, height_ratios=None):
vstack(boxes, padding=padding)
match_heights(boxes, height_ratios=height_ratios)
def hstackeq(boxes, padding=0, width_ratios=None):
hstack(boxes, padding=padding)
match_widths(boxes, width_ratios=width_ratios)
def align(boxes, attr, strength='strong'):
cons = []
for box in boxes[1:]:
cons = (getattr(boxes[0], attr) == getattr(box, attr))
boxes[0].solver.addConstraint(cons | strength)
def match_top_margins(boxes, levels=1):
box0 = boxes[0]
top0 = box0
for n in range(levels):
top0 = top0.parent
for box in boxes[1:]:
topb = box
for n in range(levels):
topb = topb.parent
c = (box0.top-top0.top == box.top-topb.top)
box0.solver.addConstraint(c | 'strong')
def match_bottom_margins(boxes, levels=1):
box0 = boxes[0]
top0 = box0
for n in range(levels):
top0 = top0.parent
for box in boxes[1:]:
topb = box
for n in range(levels):
topb = topb.parent
c = (box0.bottom-top0.bottom == box.bottom-topb.bottom)
box0.solver.addConstraint(c | 'strong')
def match_left_margins(boxes, levels=1):
box0 = boxes[0]
top0 = box0
for n in range(levels):
top0 = top0.parent
for box in boxes[1:]:
topb = box
for n in range(levels):
topb = topb.parent
c = (box0.left-top0.left == box.left-topb.left)
box0.solver.addConstraint(c | 'strong')
def match_right_margins(boxes, levels=1):
box0 = boxes[0]
top0 = box0
for n in range(levels):
top0 = top0.parent
for box in boxes[1:]:
topb = box
for n in range(levels):
topb = topb.parent
c = (box0.right-top0.right == box.right-topb.right)
box0.solver.addConstraint(c | 'strong')
def match_width_margins(boxes, levels=1):
match_left_margins(boxes, levels=levels)
match_right_margins(boxes, levels=levels)
def match_height_margins(boxes, levels=1):
match_top_margins(boxes, levels=levels)
match_bottom_margins(boxes, levels=levels)
def match_margins(boxes, levels=1):
match_width_margins(boxes, levels=levels)
match_height_margins(boxes, levels=levels)
_layoutboxobjnum = itertools.count()
def seq_id():
'''
Generate a short sequential id for layoutbox objects...
'''
global _layoutboxobjnum
return ('%06d' % (next(_layoutboxobjnum)))
def print_children(lb):
'''
Print the children of the layoutbox
'''
print(lb)
for child in lb.children:
print_children(child)
def nonetree(lb):
'''
Make all elements in this tree none... This signals not to do any more
layout.
'''
if lb is not None:
if lb.parent is None:
# Clear the solver. Hopefully this garbage collects.
lb.solver.reset()
nonechildren(lb)
else:
nonetree(lb.parent)
def nonechildren(lb):
for child in lb.children:
nonechildren(child)
lb.artist._layoutbox = None
lb = None
def print_tree(lb):
'''
Print the tree of layoutboxes
'''
if lb.parent is None:
print('LayoutBox Tree\n')
print('==============\n')
print_children(lb)
print('\n')
else:
print_tree(lb.parent)
def plot_children(fig, box, level=0, printit=True):
'''
Simple plotting to show where boxes are
'''
import matplotlib
import matplotlib.pyplot as plt
if isinstance(fig, matplotlib.figure.Figure):
ax = fig.add_axes([0., 0., 1., 1.])
ax.set_facecolor([1., 1., 1., 0.7])
ax.set_alpha(0.3)
fig.draw(fig.canvas.get_renderer())
else:
ax = fig
import matplotlib.patches as patches
colors = plt.rcParams["axes.prop_cycle"].by_key()["color"]
if printit:
print("Level:", level)
for child in box.children:
if printit:
print(child)
ax.add_patch(
patches.Rectangle(
(child.left.value(), child.bottom.value()), # (x,y)
child.width.value(), # width
child.height.value(), # height
fc='none',
alpha=0.8,
ec=colors[level]
)
)
if level > 0:
name = child.name.split('.')[-1]
if level % 2 == 0:
ax.text(child.left.value(), child.bottom.value(), name,
size=12-level, color=colors[level])
else:
ax.text(child.right.value(), child.top.value(), name,
ha='right', va='top', size=12-level,
color=colors[level])
plot_children(ax, child, level=level+1, printit=printit)
|
5e1fee15a3aae02075ef4fd8d5d5b430e35b08eca288d9c5fd17fc58abe81da4
|
"""
Stacked area plot for 1D arrays inspired by Douglas Y'barbo's stackoverflow
answer:
http://stackoverflow.com/questions/2225995/how-can-i-create-stacked-line-graph-with-matplotlib
(http://stackoverflow.com/users/66549/doug)
"""
import numpy as np
__all__ = ['stackplot']
def stackplot(axes, x, *args,
labels=(), colors=None, baseline='zero',
**kwargs):
"""
Draw a stacked area plot.
Parameters
----------
x : 1d array of dimension N
y : 2d array (dimension MxN), or sequence of 1d arrays (each dimension 1xN)
The data is assumed to be unstacked. Each of the following
calls is legal::
stackplot(x, y) # where y is MxN
stackplot(x, y1, y2, y3, y4) # where y1, y2, y3, y4, are all 1xNm
baseline : {'zero', 'sym', 'wiggle', 'weighted_wiggle'}
Method used to calculate the baseline:
- ``'zero'``: Constant zero baseline, i.e. a simple stacked plot.
- ``'sym'``: Symmetric around zero and is sometimes called
'ThemeRiver'.
- ``'wiggle'``: Minimizes the sum of the squared slopes.
- ``'weighted_wiggle'``: Does the same but weights to account for
size of each layer. It is also called 'Streamgraph'-layout. More
details can be found at http://leebyron.com/streamgraph/.
labels : Length N sequence of strings
Labels to assign to each data series.
colors : Length N sequence of colors
A list or tuple of colors. These will be cycled through and used to
colour the stacked areas.
**kwargs
All other keyword arguments are passed to `Axes.fill_between()`.
Returns
-------
list : list of `.PolyCollection`
A list of `.PolyCollection` instances, one for each element in the
stacked area plot.
"""
y = np.row_stack(args)
labels = iter(labels)
if colors is not None:
axes.set_prop_cycle(color=colors)
# Assume data passed has not been 'stacked', so stack it here.
# We'll need a float buffer for the upcoming calculations.
stack = np.cumsum(y, axis=0, dtype=np.promote_types(y.dtype, np.float32))
if baseline == 'zero':
first_line = 0.
elif baseline == 'sym':
first_line = -np.sum(y, 0) * 0.5
stack += first_line[None, :]
elif baseline == 'wiggle':
m = y.shape[0]
first_line = (y * (m - 0.5 - np.arange(m)[:, None])).sum(0)
first_line /= -m
stack += first_line
elif baseline == 'weighted_wiggle':
total = np.sum(y, 0)
# multiply by 1/total (or zero) to avoid infinities in the division:
inv_total = np.zeros_like(total)
mask = total > 0
inv_total[mask] = 1.0 / total[mask]
increase = np.hstack((y[:, 0:1], np.diff(y)))
below_size = total - stack
below_size += 0.5 * y
move_up = below_size * inv_total
move_up[:, 0] = 0.5
center = (move_up - 0.5) * increase
center = np.cumsum(center.sum(0))
first_line = center - 0.5 * total
stack += first_line
else:
errstr = "Baseline method %s not recognised. " % baseline
errstr += "Expected 'zero', 'sym', 'wiggle' or 'weighted_wiggle'"
raise ValueError(errstr)
# Color between x = 0 and the first array.
color = axes._get_lines.get_next_color()
coll = axes.fill_between(x, first_line, stack[0, :],
facecolor=color, label=next(labels, None),
**kwargs)
coll.sticky_edges.y[:] = [0]
r = [coll]
# Color between array i-1 and array i
for i in range(len(y) - 1):
color = axes._get_lines.get_next_color()
r.append(axes.fill_between(x, stack[i, :], stack[i + 1, :],
facecolor=color, label=next(labels, None),
**kwargs))
return r
|
4f0210f704fc62b4d02af30d567d97a7ef454cdbb5d43670563b5be9dfaec970
|
"""
Classes for the ticks and x and y axis.
"""
import datetime
import logging
import numpy as np
from matplotlib import rcParams
import matplotlib.artist as martist
import matplotlib.cbook as cbook
import matplotlib.font_manager as font_manager
import matplotlib.lines as mlines
import matplotlib.scale as mscale
import matplotlib.text as mtext
import matplotlib.ticker as mticker
import matplotlib.transforms as mtransforms
import matplotlib.units as munits
_log = logging.getLogger(__name__)
GRIDLINE_INTERPOLATION_STEPS = 180
# This list is being used for compatibility with Axes.grid, which
# allows all Line2D kwargs.
_line_AI = martist.ArtistInspector(mlines.Line2D)
_line_param_names = _line_AI.get_setters()
_line_param_aliases = [list(d)[0] for d in _line_AI.aliasd.values()]
_gridline_param_names = ['grid_' + name
for name in _line_param_names + _line_param_aliases]
class Tick(martist.Artist):
"""
Abstract base class for the axis ticks, grid lines and labels.
Ticks mark a position on an Axis. They contain two lines as markers and
two labels; one each for the bottom and top positions (in case of an
`.XAxis`) or for the left and right positions (in case of a `.YAxis`).
Attributes
----------
tick1line : `.Line2D`
The left/bottom tick marker.
tick2line : `.Line2D`
The right/top tick marker.
gridline : `.Line2D`
The grid line associated with the label position.
label1 : `.Text`
The left/bottom tick label.
label2 : `.Text`
The right/top tick label.
"""
def __init__(self, axes, loc, label,
size=None, # points
width=None,
color=None,
tickdir=None,
pad=None,
labelsize=None,
labelcolor=None,
zorder=None,
gridOn=None, # defaults to axes.grid depending on
# axes.grid.which
tick1On=True,
tick2On=True,
label1On=True,
label2On=False,
major=True,
labelrotation=0,
grid_color=None,
grid_linestyle=None,
grid_linewidth=None,
grid_alpha=None,
**kw # Other Line2D kwargs applied to gridlines.
):
"""
bbox is the Bound2D bounding box in display coords of the Axes
loc is the tick location in data coords
size is the tick size in points
"""
martist.Artist.__init__(self)
if gridOn is None:
if major and (rcParams['axes.grid.which'] in ('both', 'major')):
gridOn = rcParams['axes.grid']
elif (not major) and (rcParams['axes.grid.which']
in ('both', 'minor')):
gridOn = rcParams['axes.grid']
else:
gridOn = False
self.set_figure(axes.figure)
self.axes = axes
name = self.__name__.lower()
self._name = name
self._loc = loc
if size is None:
if major:
size = rcParams['%s.major.size' % name]
else:
size = rcParams['%s.minor.size' % name]
self._size = size
if width is None:
if major:
width = rcParams['%s.major.width' % name]
else:
width = rcParams['%s.minor.width' % name]
self._width = width
if color is None:
color = rcParams['%s.color' % name]
self._color = color
if pad is None:
if major:
pad = rcParams['%s.major.pad' % name]
else:
pad = rcParams['%s.minor.pad' % name]
self._base_pad = pad
if labelcolor is None:
labelcolor = rcParams['%s.color' % name]
self._labelcolor = labelcolor
if labelsize is None:
labelsize = rcParams['%s.labelsize' % name]
self._labelsize = labelsize
self._set_labelrotation(labelrotation)
if zorder is None:
if major:
zorder = mlines.Line2D.zorder + 0.01
else:
zorder = mlines.Line2D.zorder
self._zorder = zorder
self._grid_color = (rcParams['grid.color']
if grid_color is None else grid_color)
self._grid_linestyle = (rcParams['grid.linestyle']
if grid_linestyle is None else grid_linestyle)
self._grid_linewidth = (rcParams['grid.linewidth']
if grid_linewidth is None else grid_linewidth)
self._grid_alpha = (rcParams['grid.alpha']
if grid_alpha is None else grid_alpha)
self._grid_kw = {k[5:]: v for k, v in kw.items()}
self.apply_tickdir(tickdir)
self.tick1line = self._get_tick1line()
self.tick2line = self._get_tick2line()
self.gridline = self._get_gridline()
self.label1 = self._get_text1()
self.label2 = self._get_text2()
self.gridline.set_visible(gridOn)
self.tick1line.set_visible(tick1On)
self.tick2line.set_visible(tick2On)
self.label1.set_visible(label1On)
self.label2.set_visible(label2On)
self.update_position(loc)
for _old_name, _new_name in [
("gridOn", "gridline"),
("tick1On", "tick1line"),
("tick2On", "tick2line"),
("label1On", "label1"),
("label2On", "label2")]:
locals()[_old_name] = property(
cbook.deprecated(
"3.1",
name=_old_name,
alternative="Tick.{}.get_visible".format(_new_name))(
lambda self, _new_name=_new_name:
getattr(self, _new_name).get_visible()),
cbook.deprecated(
"3.1",
name=_old_name,
alternative="Tick.{}.set_visible".format(_new_name))(
lambda self, value, _new_name=_new_name:
getattr(self, _new_name).set_visible(value)))
del _old_name, _new_name
@property
@cbook.deprecated("3.1", alternative="Tick.label1", pending=True)
def label(self):
return self.label1
def _set_labelrotation(self, labelrotation):
if isinstance(labelrotation, str):
mode = labelrotation
angle = 0
elif isinstance(labelrotation, (tuple, list)):
mode, angle = labelrotation
else:
mode = 'default'
angle = labelrotation
cbook._check_in_list(['auto', 'default'], labelrotation=mode)
self._labelrotation = (mode, angle)
def apply_tickdir(self, tickdir):
"""Calculate self._pad and self._tickmarkers."""
def get_tickdir(self):
return self._tickdir
def get_tick_padding(self):
"""Get the length of the tick outside of the axes."""
padding = {
'in': 0.0,
'inout': 0.5,
'out': 1.0
}
return self._size * padding[self._tickdir]
def get_children(self):
children = [self.tick1line, self.tick2line,
self.gridline, self.label1, self.label2]
return children
def set_clip_path(self, clippath, transform=None):
# docstring inherited
martist.Artist.set_clip_path(self, clippath, transform)
self.gridline.set_clip_path(clippath, transform)
self.stale = True
def get_pad_pixels(self):
return self.figure.dpi * self._base_pad / 72
def contains(self, mouseevent):
"""
Test whether the mouse event occurred in the Tick marks.
This function always returns false. It is more useful to test if the
axis as a whole contains the mouse rather than the set of tick marks.
"""
if self._contains is not None:
return self._contains(self, mouseevent)
return False, {}
def set_pad(self, val):
"""
Set the tick label pad in points
Parameters
----------
val : float
"""
self._apply_params(pad=val)
self.stale = True
def get_pad(self):
'Get the value of the tick label pad in points'
return self._base_pad
def _get_text1(self):
'Get the default Text 1 instance'
pass
def _get_text2(self):
'Get the default Text 2 instance'
pass
def _get_tick1line(self):
'Get the default line2D instance for tick1'
pass
def _get_tick2line(self):
'Get the default line2D instance for tick2'
pass
def _get_gridline(self):
'Get the default grid Line2d instance for this tick'
pass
def get_loc(self):
'Return the tick location (data coords) as a scalar'
return self._loc
@martist.allow_rasterization
def draw(self, renderer):
if not self.get_visible():
self.stale = False
return
renderer.open_group(self.__name__)
for artist in [self.gridline, self.tick1line, self.tick2line,
self.label1, self.label2]:
artist.draw(renderer)
renderer.close_group(self.__name__)
self.stale = False
def set_label1(self, s):
"""
Set the label1 text.
Parameters
----------
s : str
"""
self.label1.set_text(s)
self.stale = True
set_label = set_label1
def set_label2(self, s):
"""
Set the label2 text.
Parameters
----------
s : str
"""
self.label2.set_text(s)
self.stale = True
def _set_artist_props(self, a):
a.set_figure(self.figure)
def get_view_interval(self):
'return the view Interval instance for the axis this tick is ticking'
raise NotImplementedError('Derived must override')
def _apply_params(self, **kw):
for name, target in [("gridOn", self.gridline),
("tick1On", self.tick1line),
("tick2On", self.tick2line),
("label1On", self.label1),
("label2On", self.label2)]:
if name in kw:
target.set_visible(kw.pop(name))
if any(k in kw for k in ['size', 'width', 'pad', 'tickdir']):
self._size = kw.pop('size', self._size)
# Width could be handled outside this block, but it is
# convenient to leave it here.
self._width = kw.pop('width', self._width)
self._base_pad = kw.pop('pad', self._base_pad)
# apply_tickdir uses _size and _base_pad to make _pad,
# and also makes _tickmarkers.
self.apply_tickdir(kw.pop('tickdir', self._tickdir))
self.tick1line.set_marker(self._tickmarkers[0])
self.tick2line.set_marker(self._tickmarkers[1])
for line in (self.tick1line, self.tick2line):
line.set_markersize(self._size)
line.set_markeredgewidth(self._width)
# _get_text1_transform uses _pad from apply_tickdir.
trans = self._get_text1_transform()[0]
self.label1.set_transform(trans)
trans = self._get_text2_transform()[0]
self.label2.set_transform(trans)
tick_kw = {k: v for k, v in kw.items() if k in ['color', 'zorder']}
self.tick1line.set(**tick_kw)
self.tick2line.set(**tick_kw)
for k, v in tick_kw.items():
setattr(self, '_' + k, v)
if 'labelrotation' in kw:
self._set_labelrotation(kw.pop('labelrotation'))
self.label1.set(rotation=self._labelrotation[1])
self.label2.set(rotation=self._labelrotation[1])
label_kw = {k[5:]: v for k, v in kw.items()
if k in ['labelsize', 'labelcolor']}
self.label1.set(**label_kw)
self.label2.set(**label_kw)
for k, v in label_kw.items():
# for labelsize the text objects covert str ('small')
# -> points. grab the integer from the `Text` object
# instead of saving the string representation
v = getattr(self.label1, 'get_' + k)()
setattr(self, '_label' + k, v)
grid_kw = {k[5:]: v for k, v in kw.items()
if k in _gridline_param_names}
self.gridline.set(**grid_kw)
for k, v in grid_kw.items():
setattr(self, '_grid_' + k, v)
def update_position(self, loc):
'Set the location of tick in data coords with scalar *loc*'
raise NotImplementedError('Derived must override')
def _get_text1_transform(self):
raise NotImplementedError('Derived must override')
def _get_text2_transform(self):
raise NotImplementedError('Derived must override')
class XTick(Tick):
"""
Contains all the Artists needed to make an x tick - the tick line,
the label text and the grid line
"""
__name__ = 'xtick'
def _get_text1_transform(self):
return self.axes.get_xaxis_text1_transform(self._pad)
def _get_text2_transform(self):
return self.axes.get_xaxis_text2_transform(self._pad)
def apply_tickdir(self, tickdir):
if tickdir is None:
tickdir = rcParams['%s.direction' % self._name]
self._tickdir = tickdir
if self._tickdir == 'in':
self._tickmarkers = (mlines.TICKUP, mlines.TICKDOWN)
elif self._tickdir == 'inout':
self._tickmarkers = ('|', '|')
else:
self._tickmarkers = (mlines.TICKDOWN, mlines.TICKUP)
self._pad = self._base_pad + self.get_tick_padding()
self.stale = True
def _get_text1(self):
'Get the default Text instance'
# the y loc is 3 points below the min of y axis
# get the affine as an a,b,c,d,tx,ty list
# x in data coords, y in axes coords
trans, vert, horiz = self._get_text1_transform()
t = mtext.Text(
x=0, y=0,
fontproperties=font_manager.FontProperties(size=self._labelsize),
color=self._labelcolor,
verticalalignment=vert,
horizontalalignment=horiz,
)
t.set_transform(trans)
self._set_artist_props(t)
return t
def _get_text2(self):
'Get the default Text 2 instance'
# x in data coords, y in axes coords
trans, vert, horiz = self._get_text2_transform()
t = mtext.Text(
x=0, y=1,
fontproperties=font_manager.FontProperties(size=self._labelsize),
color=self._labelcolor,
verticalalignment=vert,
horizontalalignment=horiz,
)
t.set_transform(trans)
self._set_artist_props(t)
return t
def _get_tick1line(self):
'Get the default line2D instance'
# x in data coords, y in axes coords
l = mlines.Line2D(xdata=(0,), ydata=(0,), color=self._color,
linestyle='None', marker=self._tickmarkers[0],
markersize=self._size,
markeredgewidth=self._width, zorder=self._zorder)
l.set_transform(self.axes.get_xaxis_transform(which='tick1'))
self._set_artist_props(l)
return l
def _get_tick2line(self):
'Get the default line2D instance'
# x in data coords, y in axes coords
l = mlines.Line2D(xdata=(0,), ydata=(1,),
color=self._color,
linestyle='None',
marker=self._tickmarkers[1],
markersize=self._size,
markeredgewidth=self._width,
zorder=self._zorder)
l.set_transform(self.axes.get_xaxis_transform(which='tick2'))
self._set_artist_props(l)
return l
def _get_gridline(self):
'Get the default line2D instance'
# x in data coords, y in axes coords
l = mlines.Line2D(xdata=(0.0, 0.0), ydata=(0, 1.0),
color=self._grid_color,
linestyle=self._grid_linestyle,
linewidth=self._grid_linewidth,
alpha=self._grid_alpha,
markersize=0,
**self._grid_kw)
l.set_transform(self.axes.get_xaxis_transform(which='grid'))
l.get_path()._interpolation_steps = GRIDLINE_INTERPOLATION_STEPS
self._set_artist_props(l)
return l
def update_position(self, loc):
"""Set the location of tick in data coords with scalar *loc*."""
self.tick1line.set_xdata((loc,))
self.tick2line.set_xdata((loc,))
self.gridline.set_xdata((loc,))
self.label1.set_x(loc)
self.label2.set_x(loc)
self._loc = loc
self.stale = True
def get_view_interval(self):
# docstring inherited
return self.axes.viewLim.intervalx
class YTick(Tick):
"""
Contains all the Artists needed to make a Y tick - the tick line,
the label text and the grid line
"""
__name__ = 'ytick'
def _get_text1_transform(self):
return self.axes.get_yaxis_text1_transform(self._pad)
def _get_text2_transform(self):
return self.axes.get_yaxis_text2_transform(self._pad)
def apply_tickdir(self, tickdir):
if tickdir is None:
tickdir = rcParams['%s.direction' % self._name]
self._tickdir = tickdir
if self._tickdir == 'in':
self._tickmarkers = (mlines.TICKRIGHT, mlines.TICKLEFT)
elif self._tickdir == 'inout':
self._tickmarkers = ('_', '_')
else:
self._tickmarkers = (mlines.TICKLEFT, mlines.TICKRIGHT)
self._pad = self._base_pad + self.get_tick_padding()
self.stale = True
# how far from the y axis line the right of the ticklabel are
def _get_text1(self):
'Get the default Text instance'
# x in axes coords, y in data coords
trans, vert, horiz = self._get_text1_transform()
t = mtext.Text(
x=0, y=0,
fontproperties=font_manager.FontProperties(size=self._labelsize),
color=self._labelcolor,
verticalalignment=vert,
horizontalalignment=horiz,
)
t.set_transform(trans)
self._set_artist_props(t)
return t
def _get_text2(self):
'Get the default Text instance'
# x in axes coords, y in data coords
trans, vert, horiz = self._get_text2_transform()
t = mtext.Text(
x=1, y=0,
fontproperties=font_manager.FontProperties(size=self._labelsize),
color=self._labelcolor,
verticalalignment=vert,
horizontalalignment=horiz,
)
t.set_transform(trans)
self._set_artist_props(t)
return t
def _get_tick1line(self):
'Get the default line2D instance'
# x in axes coords, y in data coords
l = mlines.Line2D((0,), (0,),
color=self._color,
marker=self._tickmarkers[0],
linestyle='None',
markersize=self._size,
markeredgewidth=self._width,
zorder=self._zorder)
l.set_transform(self.axes.get_yaxis_transform(which='tick1'))
self._set_artist_props(l)
return l
def _get_tick2line(self):
'Get the default line2D instance'
# x in axes coords, y in data coords
l = mlines.Line2D((1,), (0,),
color=self._color,
marker=self._tickmarkers[1],
linestyle='None',
markersize=self._size,
markeredgewidth=self._width,
zorder=self._zorder)
l.set_transform(self.axes.get_yaxis_transform(which='tick2'))
self._set_artist_props(l)
return l
def _get_gridline(self):
'Get the default line2D instance'
# x in axes coords, y in data coords
l = mlines.Line2D(xdata=(0, 1), ydata=(0, 0),
color=self._grid_color,
linestyle=self._grid_linestyle,
linewidth=self._grid_linewidth,
alpha=self._grid_alpha,
markersize=0,
**self._grid_kw)
l.set_transform(self.axes.get_yaxis_transform(which='grid'))
l.get_path()._interpolation_steps = GRIDLINE_INTERPOLATION_STEPS
self._set_artist_props(l)
return l
def update_position(self, loc):
"""Set the location of tick in data coords with scalar *loc*."""
self.tick1line.set_ydata((loc,))
self.tick2line.set_ydata((loc,))
self.gridline.set_ydata((loc,))
self.label1.set_y(loc)
self.label2.set_y(loc)
self._loc = loc
self.stale = True
def get_view_interval(self):
"""Return the Interval instance for this axis view limits."""
return self.axes.viewLim.intervaly
class Ticker(object):
"""
A container for the objects defining tick position and format.
Attributes
----------
locator : `matplotlib.ticker.Locator` subclass
Determines the positions of the ticks.
formatter : `matplotlib.ticker.Formatter` subclass
Determines the format of the tick labels.
"""
locator = None
formatter = None
class _LazyTickList(object):
"""
A descriptor for lazy instantiation of tick lists.
See comment above definition of the ``majorTicks`` and ``minorTicks``
attributes.
"""
def __init__(self, major):
self._major = major
def __get__(self, instance, cls):
if instance is None:
return self
else:
# instance._get_tick() can itself try to access the majorTicks
# attribute (e.g. in certain projection classes which override
# e.g. get_xaxis_text1_transform). In order to avoid infinite
# recursion, first set the majorTicks on the instance to an empty
# list, then create the tick and append it.
if self._major:
instance.majorTicks = []
tick = instance._get_tick(major=True)
instance.majorTicks.append(tick)
return instance.majorTicks
else:
instance.minorTicks = []
tick = instance._get_tick(major=False)
instance.minorTicks.append(tick)
return instance.minorTicks
class Axis(martist.Artist):
"""
Base class for `.XAxis` and `.YAxis`.
Attributes
----------
isDefault_label : bool
axes : `matplotlib.axes.Axes`
The `~.axes.Axes` to which the Axis belongs.
major : `matplotlib.axis.Ticker`
Determines the major tick positions and their label format.
minor : `matplotlib.axis.Ticker`
Determines the minor tick positions and their label format.
callbacks : `matplotlib.cbook.CallbackRegistry`
label : `.Text`
The axis label.
labelpad : float
The distance between the axis label and the tick labels.
Defaults to :rc:`axes.labelpad` = 4.
offsetText : `.Text`
A `.Text` object containing the data offset of the ticks (if any).
pickradius : float
The acceptance radius for containment tests. See also `.Axis.contains`.
majorTicks : list of `.Tick`
The major ticks.
minorTicks : list of `.Tick`
The minor ticks.
"""
OFFSETTEXTPAD = 3
def __str__(self):
return self.__class__.__name__ \
+ "(%f,%f)" % tuple(self.axes.transAxes.transform_point((0, 0)))
def __init__(self, axes, pickradius=15):
"""
Parameters
----------
axes : `matplotlib.axes.Axes`
The `~.axes.Axes` to which the created Axis belongs.
pickradius : float
The acceptance radius for containment tests. See also
`.Axis.contains`.
"""
martist.Artist.__init__(self)
self._remove_overlapping_locs = True
self.set_figure(axes.figure)
self.isDefault_label = True
self.axes = axes
self.major = Ticker()
self.minor = Ticker()
self.callbacks = cbook.CallbackRegistry()
self._autolabelpos = True
self._smart_bounds = False
self.label = self._get_label()
self.labelpad = rcParams['axes.labelpad']
self.offsetText = self._get_offset_text()
self.pickradius = pickradius
# Initialize here for testing; later add API
self._major_tick_kw = dict()
self._minor_tick_kw = dict()
self.cla()
self._set_scale('linear')
# During initialization, Axis objects often create ticks that are later
# unused; this turns out to be a very slow step. Instead, use a custom
# descriptor to make the tick lists lazy and instantiate them as needed.
majorTicks = _LazyTickList(major=True)
minorTicks = _LazyTickList(major=False)
def get_remove_overlapping_locs(self):
return self._remove_overlapping_locs
def set_remove_overlapping_locs(self, val):
self._remove_overlapping_locs = bool(val)
remove_overlapping_locs = property(
get_remove_overlapping_locs, set_remove_overlapping_locs,
doc=('If minor ticker locations that overlap with major '
'ticker locations should be trimmed.'))
def set_label_coords(self, x, y, transform=None):
"""
Set the coordinates of the label.
By default, the x coordinate of the y label is determined by the tick
label bounding boxes, but this can lead to poor alignment of multiple
ylabels if there are multiple axes. Ditto for the y coordinate of
the x label.
You can also specify the coordinate system of the label with
the transform. If None, the default coordinate system will be
the axes coordinate system (0,0) is (left,bottom), (0.5, 0.5)
is middle, etc
"""
self._autolabelpos = False
if transform is None:
transform = self.axes.transAxes
self.label.set_transform(transform)
self.label.set_position((x, y))
self.stale = True
def get_transform(self):
return self._scale.get_transform()
def get_scale(self):
return self._scale.name
def _set_scale(self, value, **kwargs):
self._scale = mscale.scale_factory(value, self, **kwargs)
self._scale.set_default_locators_and_formatters(self)
self.isDefault_majloc = True
self.isDefault_minloc = True
self.isDefault_majfmt = True
self.isDefault_minfmt = True
def limit_range_for_scale(self, vmin, vmax):
return self._scale.limit_range_for_scale(vmin, vmax, self.get_minpos())
def get_children(self):
children = [self.label, self.offsetText]
majorticks = self.get_major_ticks()
minorticks = self.get_minor_ticks()
children.extend(majorticks)
children.extend(minorticks)
return children
def cla(self):
'clear the current axis'
self.label.set_text('') # self.set_label_text would change isDefault_
self._set_scale('linear')
# Clear the callback registry for this axis, or it may "leak"
self.callbacks = cbook.CallbackRegistry()
# whether the grids are on
self._gridOnMajor = (rcParams['axes.grid'] and
rcParams['axes.grid.which'] in ('both', 'major'))
self._gridOnMinor = (rcParams['axes.grid'] and
rcParams['axes.grid.which'] in ('both', 'minor'))
self.reset_ticks()
self.converter = None
self.units = None
self.set_units(None)
self.stale = True
def reset_ticks(self):
"""
Re-initialize the major and minor Tick lists.
Each list starts with a single fresh Tick.
"""
# Restore the lazy tick lists.
try:
del self.majorTicks
except AttributeError:
pass
try:
del self.minorTicks
except AttributeError:
pass
try:
self.set_clip_path(self.axes.patch)
except AttributeError:
pass
def set_tick_params(self, which='major', reset=False, **kw):
"""
Set appearance parameters for ticks, ticklabels, and gridlines.
For documentation of keyword arguments, see
:meth:`matplotlib.axes.Axes.tick_params`.
"""
dicts = []
if which == 'major' or which == 'both':
dicts.append(self._major_tick_kw)
if which == 'minor' or which == 'both':
dicts.append(self._minor_tick_kw)
kwtrans = self._translate_tick_kw(kw)
# this stashes the parameter changes so any new ticks will
# automatically get them
for d in dicts:
if reset:
d.clear()
d.update(kwtrans)
if reset:
self.reset_ticks()
else:
# apply the new kwargs to the existing ticks
if which == 'major' or which == 'both':
for tick in self.majorTicks:
tick._apply_params(**kwtrans)
if which == 'minor' or which == 'both':
for tick in self.minorTicks:
tick._apply_params(**kwtrans)
# special-case label color to also apply to the offset
# text
if 'labelcolor' in kwtrans:
self.offsetText.set_color(kwtrans['labelcolor'])
self.stale = True
@staticmethod
def _translate_tick_kw(kw):
# The following lists may be moved to a more accessible location.
kwkeys = ['size', 'width', 'color', 'tickdir', 'pad',
'labelsize', 'labelcolor', 'zorder', 'gridOn',
'tick1On', 'tick2On', 'label1On', 'label2On',
'length', 'direction', 'left', 'bottom', 'right', 'top',
'labelleft', 'labelbottom', 'labelright', 'labeltop',
'labelrotation'] + _gridline_param_names
kwtrans = {}
if 'length' in kw:
kwtrans['size'] = kw.pop('length')
if 'direction' in kw:
kwtrans['tickdir'] = kw.pop('direction')
if 'rotation' in kw:
kwtrans['labelrotation'] = kw.pop('rotation')
if 'left' in kw:
kwtrans['tick1On'] = kw.pop('left')
if 'bottom' in kw:
kwtrans['tick1On'] = kw.pop('bottom')
if 'right' in kw:
kwtrans['tick2On'] = kw.pop('right')
if 'top' in kw:
kwtrans['tick2On'] = kw.pop('top')
if 'labelleft' in kw:
kwtrans['label1On'] = kw.pop('labelleft')
if 'labelbottom' in kw:
kwtrans['label1On'] = kw.pop('labelbottom')
if 'labelright' in kw:
kwtrans['label2On'] = kw.pop('labelright')
if 'labeltop' in kw:
kwtrans['label2On'] = kw.pop('labeltop')
if 'colors' in kw:
c = kw.pop('colors')
kwtrans['color'] = c
kwtrans['labelcolor'] = c
# Maybe move the checking up to the caller of this method.
for key in kw:
if key not in kwkeys:
raise ValueError(
"keyword %s is not recognized; valid keywords are %s"
% (key, kwkeys))
kwtrans.update(kw)
return kwtrans
def set_clip_path(self, clippath, transform=None):
martist.Artist.set_clip_path(self, clippath, transform)
for child in self.majorTicks + self.minorTicks:
child.set_clip_path(clippath, transform)
self.stale = True
def get_view_interval(self):
"""Return the Interval instance for this axis view limits."""
raise NotImplementedError('Derived must override')
def set_view_interval(self, vmin, vmax, ignore=False):
"""
Set the axis view limits. This method is for internal use; Matplotlib
users should typically use e.g. `~Axes.set_xlim` and `~Axes.set_ylim`.
If *ignore* is False (the default), this method will never reduce the
preexisting view limits, only expand them if *vmin* or *vmax* are not
within them. Moreover, the order of *vmin* and *vmax* does not matter;
the orientation of the axis will not change.
If *ignore* is True, the view limits will be set exactly to ``(vmin,
vmax)`` in that order.
"""
raise NotImplementedError('Derived must override')
def get_data_interval(self):
"""Return the Interval instance for this axis data limits."""
raise NotImplementedError('Derived must override')
def set_data_interval(self, vmin, vmax, ignore=False):
"""
Set the axis data limits. This method is for internal use.
If *ignore* is False (the default), this method will never reduce the
preexisting data limits, only expand them if *vmin* or *vmax* are not
within them. Moreover, the order of *vmin* and *vmax* does not matter;
the orientation of the axis will not change.
If *ignore* is True, the data limits will be set exactly to ``(vmin,
vmax)`` in that order.
"""
raise NotImplementedError('Derived must override')
def get_inverted(self):
"""
Return whether the axis is oriented in the "inverse" direction.
The "normal" direction is increasing to the right for the x-axis and to
the top for the y-axis; the "inverse" direction is increasing to the
left for the x-axis and to the bottom for the y-axis.
"""
low, high = self.get_view_interval()
return high < low
def set_inverted(self, inverted):
"""
Set whether the axis is oriented in the "inverse" direction.
The "normal" direction is increasing to the right for the x-axis and to
the top for the y-axis; the "inverse" direction is increasing to the
left for the x-axis and to the bottom for the y-axis.
"""
a, b = self.get_view_interval()
if inverted:
self.set_view_interval(max(a, b), min(a, b), ignore=True)
else:
self.set_view_interval(min(a, b), max(a, b), ignore=True)
def set_default_intervals(self):
"""
Set the default limits for the axis data and view interval if they
have not been not mutated yet.
"""
# this is mainly in support of custom object plotting. For
# example, if someone passes in a datetime object, we do not
# know automagically how to set the default min/max of the
# data and view limits. The unit conversion AxisInfo
# interface provides a hook for custom types to register
# default limits through the AxisInfo.default_limits
# attribute, and the derived code below will check for that
# and use it if is available (else just use 0..1)
def _set_artist_props(self, a):
if a is None:
return
a.set_figure(self.figure)
@cbook.deprecated("3.1")
def iter_ticks(self):
"""
Yield ``(Tick, location, label)`` tuples for major and minor ticks.
"""
major_locs = self.get_majorticklocs()
major_labels = self.major.formatter.format_ticks(major_locs)
major_ticks = self.get_major_ticks(len(major_locs))
yield from zip(major_ticks, major_locs, major_labels)
minor_locs = self.get_minorticklocs()
minor_labels = self.minor.formatter.format_ticks(minor_locs)
minor_ticks = self.get_minor_ticks(len(minor_locs))
yield from zip(minor_ticks, minor_locs, minor_labels)
def get_ticklabel_extents(self, renderer):
"""
Get the extents of the tick labels on either side
of the axes.
"""
ticks_to_draw = self._update_ticks()
ticklabelBoxes, ticklabelBoxes2 = self._get_tick_bboxes(ticks_to_draw,
renderer)
if len(ticklabelBoxes):
bbox = mtransforms.Bbox.union(ticklabelBoxes)
else:
bbox = mtransforms.Bbox.from_extents(0, 0, 0, 0)
if len(ticklabelBoxes2):
bbox2 = mtransforms.Bbox.union(ticklabelBoxes2)
else:
bbox2 = mtransforms.Bbox.from_extents(0, 0, 0, 0)
return bbox, bbox2
def set_smart_bounds(self, value):
"""set the axis to have smart bounds"""
self._smart_bounds = value
self.stale = True
def get_smart_bounds(self):
"""get whether the axis has smart bounds"""
return self._smart_bounds
def _update_ticks(self):
"""
Update ticks (position and labels) using the current data interval of
the axes. Return the list of ticks that will be drawn.
"""
major_locs = self.get_majorticklocs()
major_labels = self.major.formatter.format_ticks(major_locs)
major_ticks = self.get_major_ticks(len(major_locs))
self.major.formatter.set_locs(major_locs)
for tick, loc, label in zip(major_ticks, major_locs, major_labels):
tick.update_position(loc)
tick.set_label1(label)
tick.set_label2(label)
minor_locs = self.get_minorticklocs()
minor_labels = self.minor.formatter.format_ticks(minor_locs)
minor_ticks = self.get_minor_ticks(len(minor_locs))
self.minor.formatter.set_locs(minor_locs)
for tick, loc, label in zip(minor_ticks, minor_locs, minor_labels):
tick.update_position(loc)
tick.set_label1(label)
tick.set_label2(label)
ticks = [*major_ticks, *minor_ticks]
# mark the ticks that we will not be using as not visible
for t in (self.minorTicks[len(minor_locs):] +
self.majorTicks[len(major_locs):]):
t.set_visible(False)
view_low, view_high = self.get_view_interval()
if view_low > view_high:
view_low, view_high = view_high, view_low
if self._smart_bounds and ticks:
# handle inverted limits
data_low, data_high = sorted(self.get_data_interval())
locs = np.sort([tick.get_loc() for tick in ticks])
if data_low <= view_low:
# data extends beyond view, take view as limit
ilow = view_low
else:
# data stops within view, take best tick
good_locs = locs[locs <= data_low]
if len(good_locs):
# last tick prior or equal to first data point
ilow = good_locs[-1]
else:
# No ticks (why not?), take first tick
ilow = locs[0]
if data_high >= view_high:
# data extends beyond view, take view as limit
ihigh = view_high
else:
# data stops within view, take best tick
good_locs = locs[locs >= data_high]
if len(good_locs):
# first tick after or equal to last data point
ihigh = good_locs[0]
else:
# No ticks (why not?), take last tick
ihigh = locs[-1]
ticks = [tick for tick in ticks if ilow <= tick.get_loc() <= ihigh]
interval_t = self.get_transform().transform([view_low, view_high])
ticks_to_draw = []
for tick in ticks:
try:
loc_t = self.get_transform().transform(tick.get_loc())
except AssertionError:
# transforms.transform doesn't allow masked values but
# some scales might make them, so we need this try/except.
pass
else:
if mtransforms._interval_contains_close(interval_t, loc_t):
ticks_to_draw.append(tick)
return ticks_to_draw
def _get_tick_bboxes(self, ticks, renderer):
"""Return lists of bboxes for ticks' label1's and label2's."""
return ([tick.label1.get_window_extent(renderer)
for tick in ticks if tick.label1.get_visible()],
[tick.label2.get_window_extent(renderer)
for tick in ticks if tick.label2.get_visible()])
def get_tightbbox(self, renderer):
"""
Return a bounding box that encloses the axis. It only accounts
tick labels, axis label, and offsetText.
"""
if not self.get_visible():
return
ticks_to_draw = self._update_ticks()
self._update_label_position(renderer)
# go back to just this axis's tick labels
ticklabelBoxes, ticklabelBoxes2 = self._get_tick_bboxes(
ticks_to_draw, renderer)
self._update_offset_text_position(ticklabelBoxes, ticklabelBoxes2)
self.offsetText.set_text(self.major.formatter.get_offset())
bboxes = [
*(a.get_window_extent(renderer)
for a in [self.label, self.offsetText]
if a.get_visible()),
*ticklabelBoxes,
*ticklabelBoxes2,
]
bboxes = [b for b in bboxes
if 0 < b.width < np.inf and 0 < b.height < np.inf]
if bboxes:
return mtransforms.Bbox.union(bboxes)
else:
return None
def get_tick_padding(self):
values = []
if len(self.majorTicks):
values.append(self.majorTicks[0].get_tick_padding())
if len(self.minorTicks):
values.append(self.minorTicks[0].get_tick_padding())
return max(values, default=0)
@martist.allow_rasterization
def draw(self, renderer, *args, **kwargs):
'Draw the axis lines, grid lines, tick lines and labels'
if not self.get_visible():
return
renderer.open_group(__name__)
ticks_to_draw = self._update_ticks()
ticklabelBoxes, ticklabelBoxes2 = self._get_tick_bboxes(ticks_to_draw,
renderer)
for tick in ticks_to_draw:
tick.draw(renderer)
# scale up the axis label box to also find the neighbors, not
# just the tick labels that actually overlap note we need a
# *copy* of the axis label box because we don't wan't to scale
# the actual bbox
self._update_label_position(renderer)
self.label.draw(renderer)
self._update_offset_text_position(ticklabelBoxes, ticklabelBoxes2)
self.offsetText.set_text(self.major.formatter.get_offset())
self.offsetText.draw(renderer)
renderer.close_group(__name__)
self.stale = False
def _get_label(self):
raise NotImplementedError('Derived must override')
def _get_offset_text(self):
raise NotImplementedError('Derived must override')
def get_gridlines(self):
'Return the grid lines as a list of Line2D instance'
ticks = self.get_major_ticks()
return cbook.silent_list('Line2D gridline',
[tick.gridline for tick in ticks])
def get_label(self):
'Return the axis label as a Text instance'
return self.label
def get_offset_text(self):
'Return the axis offsetText as a Text instance'
return self.offsetText
def get_pickradius(self):
'Return the depth of the axis used by the picker'
return self.pickradius
def get_majorticklabels(self):
'Return a list of Text instances for the major ticklabels.'
ticks = self.get_major_ticks()
labels1 = [tick.label1 for tick in ticks if tick.label1.get_visible()]
labels2 = [tick.label2 for tick in ticks if tick.label2.get_visible()]
return cbook.silent_list('Text major ticklabel', labels1 + labels2)
def get_minorticklabels(self):
'Return a list of Text instances for the minor ticklabels.'
ticks = self.get_minor_ticks()
labels1 = [tick.label1 for tick in ticks if tick.label1.get_visible()]
labels2 = [tick.label2 for tick in ticks if tick.label2.get_visible()]
return cbook.silent_list('Text minor ticklabel', labels1 + labels2)
def get_ticklabels(self, minor=False, which=None):
"""
Get the tick labels as a list of `~matplotlib.text.Text` instances.
Parameters
----------
minor : bool
If True return the minor ticklabels,
else return the major ticklabels
which : None, ('minor', 'major', 'both')
Overrides `minor`.
Selects which ticklabels to return
Returns
-------
ret : list
List of `~matplotlib.text.Text` instances.
"""
if which is not None:
if which == 'minor':
return self.get_minorticklabels()
elif which == 'major':
return self.get_majorticklabels()
elif which == 'both':
return self.get_majorticklabels() + self.get_minorticklabels()
else:
cbook._check_in_list(['major', 'minor', 'both'], which=which)
if minor:
return self.get_minorticklabels()
return self.get_majorticklabels()
def get_majorticklines(self):
'Return the major tick lines as a list of Line2D instances'
lines = []
ticks = self.get_major_ticks()
for tick in ticks:
lines.append(tick.tick1line)
lines.append(tick.tick2line)
return cbook.silent_list('Line2D ticklines', lines)
def get_minorticklines(self):
'Return the minor tick lines as a list of Line2D instances'
lines = []
ticks = self.get_minor_ticks()
for tick in ticks:
lines.append(tick.tick1line)
lines.append(tick.tick2line)
return cbook.silent_list('Line2D ticklines', lines)
def get_ticklines(self, minor=False):
'Return the tick lines as a list of Line2D instances'
if minor:
return self.get_minorticklines()
return self.get_majorticklines()
def get_majorticklocs(self):
"""Get the array of major tick locations in data coordinates."""
return self.major.locator()
def get_minorticklocs(self):
"""Get the array of minor tick locations in data coordinates."""
# Remove minor ticks duplicating major ticks.
major_locs = self.major.locator()
minor_locs = self.minor.locator()
transform = self._scale.get_transform()
tr_minor_locs = transform.transform(minor_locs)
tr_major_locs = transform.transform(major_locs)
lo, hi = sorted(transform.transform(self.get_view_interval()))
# Use the transformed view limits as scale. 1e-5 is the default rtol
# for np.isclose.
tol = (hi - lo) * 1e-5
if self.remove_overlapping_locs:
minor_locs = [
loc for loc, tr_loc in zip(minor_locs, tr_minor_locs)
if ~np.isclose(tr_loc, tr_major_locs, atol=tol, rtol=0).any()]
return minor_locs
def get_ticklocs(self, minor=False):
"""Get the array of tick locations in data coordinates."""
return self.get_minorticklocs() if minor else self.get_majorticklocs()
def get_ticks_direction(self, minor=False):
"""
Get the tick directions as a numpy array
Parameters
----------
minor : boolean
True to return the minor tick directions,
False to return the major tick directions,
Default is False
Returns
-------
numpy array of tick directions
"""
if minor:
return np.array(
[tick._tickdir for tick in self.get_minor_ticks()])
else:
return np.array(
[tick._tickdir for tick in self.get_major_ticks()])
def _get_tick(self, major):
'return the default tick instance'
raise NotImplementedError('derived must override')
def _copy_tick_props(self, src, dest):
'Copy the props from src tick to dest tick'
if src is None or dest is None:
return
dest.label1.update_from(src.label1)
dest.label2.update_from(src.label2)
dest.tick1line.update_from(src.tick1line)
dest.tick2line.update_from(src.tick2line)
dest.gridline.update_from(src.gridline)
def get_label_text(self):
'Get the text of the label'
return self.label.get_text()
def get_major_locator(self):
'Get the locator of the major ticker'
return self.major.locator
def get_minor_locator(self):
'Get the locator of the minor ticker'
return self.minor.locator
def get_major_formatter(self):
'Get the formatter of the major ticker'
return self.major.formatter
def get_minor_formatter(self):
'Get the formatter of the minor ticker'
return self.minor.formatter
def get_major_ticks(self, numticks=None):
'Get the tick instances; grow as necessary.'
if numticks is None:
numticks = len(self.get_majorticklocs())
while len(self.majorTicks) < numticks:
# Update the new tick label properties from the old.
tick = self._get_tick(major=True)
self.majorTicks.append(tick)
tick.gridline.set_visible(self._gridOnMajor)
self._copy_tick_props(self.majorTicks[0], tick)
return self.majorTicks[:numticks]
def get_minor_ticks(self, numticks=None):
'Get the minor tick instances; grow as necessary.'
if numticks is None:
numticks = len(self.get_minorticklocs())
while len(self.minorTicks) < numticks:
# Update the new tick label properties from the old.
tick = self._get_tick(major=False)
self.minorTicks.append(tick)
tick.gridline.set_visible(self._gridOnMinor)
self._copy_tick_props(self.minorTicks[0], tick)
return self.minorTicks[:numticks]
def grid(self, b=None, which='major', **kwargs):
"""
Configure the grid lines.
Parameters
----------
b : bool or None
Whether to show the grid lines. If any *kwargs* are supplied,
it is assumed you want the grid on and *b* will be set to True.
If *b* is *None* and there are no *kwargs*, this toggles the
visibility of the lines.
which : {'major', 'minor', 'both'}
The grid lines to apply the changes on.
**kwargs : `.Line2D` properties
Define the line properties of the grid, e.g.::
grid(color='r', linestyle='-', linewidth=2)
"""
if len(kwargs):
if not b and b is not None: # something false-like but not None
cbook._warn_external('First parameter to grid() is false, '
'but line properties are supplied. The '
'grid will be enabled.')
b = True
which = which.lower()
cbook._check_in_list(['major', 'minor', 'both'], which=which)
gridkw = {'grid_' + item[0]: item[1] for item in kwargs.items()}
if which in ['minor', 'both']:
if b is None:
self._gridOnMinor = not self._gridOnMinor
else:
self._gridOnMinor = b
self.set_tick_params(which='minor', gridOn=self._gridOnMinor,
**gridkw)
if which in ['major', 'both']:
if b is None:
self._gridOnMajor = not self._gridOnMajor
else:
self._gridOnMajor = b
self.set_tick_params(which='major', gridOn=self._gridOnMajor,
**gridkw)
self.stale = True
def update_units(self, data):
"""
introspect *data* for units converter and update the
axis.converter instance if necessary. Return *True*
if *data* is registered for unit conversion.
"""
converter = munits.registry.get_converter(data)
if converter is None:
return False
neednew = self.converter != converter
self.converter = converter
default = self.converter.default_units(data, self)
if default is not None and self.units is None:
self.set_units(default)
if neednew:
self._update_axisinfo()
self.stale = True
return True
def _update_axisinfo(self):
"""
check the axis converter for the stored units to see if the
axis info needs to be updated
"""
if self.converter is None:
return
info = self.converter.axisinfo(self.units, self)
if info is None:
return
if info.majloc is not None and \
self.major.locator != info.majloc and self.isDefault_majloc:
self.set_major_locator(info.majloc)
self.isDefault_majloc = True
if info.minloc is not None and \
self.minor.locator != info.minloc and self.isDefault_minloc:
self.set_minor_locator(info.minloc)
self.isDefault_minloc = True
if info.majfmt is not None and \
self.major.formatter != info.majfmt and self.isDefault_majfmt:
self.set_major_formatter(info.majfmt)
self.isDefault_majfmt = True
if info.minfmt is not None and \
self.minor.formatter != info.minfmt and self.isDefault_minfmt:
self.set_minor_formatter(info.minfmt)
self.isDefault_minfmt = True
if info.label is not None and self.isDefault_label:
self.set_label_text(info.label)
self.isDefault_label = True
self.set_default_intervals()
def have_units(self):
return self.converter is not None or self.units is not None
def convert_units(self, x):
# If x is already a number, doesn't need converting
if munits.ConversionInterface.is_numlike(x):
return x
if self.converter is None:
self.converter = munits.registry.get_converter(x)
if self.converter is None:
return x
try:
ret = self.converter.convert(x, self.units, self)
except Exception as e:
raise munits.ConversionError('Failed to convert value(s) to axis '
f'units: {x!r}') from e
return ret
def set_units(self, u):
"""
Set the units for axis.
Parameters
----------
u : units tag
"""
pchanged = False
if u is None:
self.units = None
pchanged = True
else:
if u != self.units:
self.units = u
pchanged = True
if pchanged:
self._update_axisinfo()
self.callbacks.process('units')
self.callbacks.process('units finalize')
self.stale = True
def get_units(self):
"""Return the units for axis."""
return self.units
def set_label_text(self, label, fontdict=None, **kwargs):
"""
Set the text value of the axis label.
Parameters
----------
label : str
Text string.
fontdict : dict
Text properties.
**kwargs
Merged into fontdict.
"""
self.isDefault_label = False
self.label.set_text(label)
if fontdict is not None:
self.label.update(fontdict)
self.label.update(kwargs)
self.stale = True
return self.label
def set_major_formatter(self, formatter):
"""
Set the formatter of the major ticker.
Parameters
----------
formatter : ~matplotlib.ticker.Formatter
"""
if not isinstance(formatter, mticker.Formatter):
raise TypeError("formatter argument should be instance of "
"matplotlib.ticker.Formatter")
self.isDefault_majfmt = False
self.major.formatter = formatter
formatter.set_axis(self)
self.stale = True
def set_minor_formatter(self, formatter):
"""
Set the formatter of the minor ticker.
Parameters
----------
formatter : ~matplotlib.ticker.Formatter
"""
if not isinstance(formatter, mticker.Formatter):
raise TypeError("formatter argument should be instance of "
"matplotlib.ticker.Formatter")
self.isDefault_minfmt = False
self.minor.formatter = formatter
formatter.set_axis(self)
self.stale = True
def set_major_locator(self, locator):
"""
Set the locator of the major ticker.
Parameters
----------
locator : ~matplotlib.ticker.Locator
"""
if not isinstance(locator, mticker.Locator):
raise TypeError("locator argument should be instance of "
"matplotlib.ticker.Locator")
self.isDefault_majloc = False
self.major.locator = locator
if self.major.formatter:
self.major.formatter._set_locator(locator)
locator.set_axis(self)
self.stale = True
def set_minor_locator(self, locator):
"""
Set the locator of the minor ticker.
Parameters
----------
locator : ~matplotlib.ticker.Locator
"""
if not isinstance(locator, mticker.Locator):
raise TypeError("locator argument should be instance of "
"matplotlib.ticker.Locator")
self.isDefault_minloc = False
self.minor.locator = locator
if self.minor.formatter:
self.minor.formatter._set_locator(locator)
locator.set_axis(self)
self.stale = True
def set_pickradius(self, pickradius):
"""
Set the depth of the axis used by the picker.
Parameters
----------
pickradius : float
"""
self.pickradius = pickradius
def set_ticklabels(self, ticklabels, *args, minor=False, **kwargs):
r"""
Set the text values of the tick labels.
Parameters
----------
ticklabels : sequence of str or of `Text`\s
List of texts for tick labels; must include values for non-visible
labels.
minor : bool
If True, set minor ticks instead of major ticks.
**kwargs
Text properties.
Returns
-------
labels : list of `Text`\s
For each tick, includes ``tick.label1`` if it is visible, then
``tick.label2`` if it is visible, in that order.
"""
if args:
cbook.warn_deprecated(
"3.1", message="Additional positional arguments to "
"set_ticklabels are ignored, and deprecated since Matplotlib "
"3.1; passing them will raise a TypeError in Matplotlib 3.3.")
get_labels = []
for t in ticklabels:
# try calling get_text() to check whether it is Text object
# if it is Text, get label content
try:
get_labels.append(t.get_text())
# otherwise add the label to the list directly
except AttributeError:
get_labels.append(t)
# replace the ticklabels list with the processed one
ticklabels = get_labels
if minor:
self.set_minor_formatter(mticker.FixedFormatter(ticklabels))
ticks = self.get_minor_ticks()
else:
self.set_major_formatter(mticker.FixedFormatter(ticklabels))
ticks = self.get_major_ticks()
ret = []
for tick_label, tick in zip(ticklabels, ticks):
# deal with label1
tick.label1.set_text(tick_label)
tick.label1.update(kwargs)
# deal with label2
tick.label2.set_text(tick_label)
tick.label2.update(kwargs)
# only return visible tick labels
if tick.label1.get_visible():
ret.append(tick.label1)
if tick.label2.get_visible():
ret.append(tick.label2)
self.stale = True
return ret
def set_ticks(self, ticks, minor=False):
"""
Set the locations of the tick marks from sequence ticks
Parameters
----------
ticks : sequence of floats
minor : bool
"""
# XXX if the user changes units, the information will be lost here
ticks = self.convert_units(ticks)
if len(ticks) > 1:
xleft, xright = self.get_view_interval()
if xright > xleft:
self.set_view_interval(min(ticks), max(ticks))
else:
self.set_view_interval(max(ticks), min(ticks))
if minor:
self.set_minor_locator(mticker.FixedLocator(ticks))
return self.get_minor_ticks(len(ticks))
else:
self.set_major_locator(mticker.FixedLocator(ticks))
return self.get_major_ticks(len(ticks))
def _get_tick_boxes_siblings(self, xdir, renderer):
"""
Get the bounding boxes for this `.axis` and its siblings
as set by `.Figure.align_xlabels` or `.Figure.align_ylablels`.
By default it just gets bboxes for self.
"""
raise NotImplementedError('Derived must override')
def _update_label_position(self, renderer):
"""
Update the label position based on the bounding box enclosing
all the ticklabels and axis spine
"""
raise NotImplementedError('Derived must override')
def _update_offset_text_position(self, bboxes, bboxes2):
"""
Update the label position based on the sequence of bounding
boxes of all the ticklabels
"""
raise NotImplementedError('Derived must override')
def pan(self, numsteps):
'Pan *numsteps* (can be positive or negative)'
self.major.locator.pan(numsteps)
def zoom(self, direction):
"Zoom in/out on axis; if *direction* is >0 zoom in, else zoom out"
self.major.locator.zoom(direction)
def axis_date(self, tz=None):
"""
Sets up x-axis ticks and labels that treat the x data as dates.
Parameters
----------
tz : tzinfo or str or None
The timezone used to create date labels.
"""
# By providing a sample datetime instance with the desired timezone,
# the registered converter can be selected, and the "units" attribute,
# which is the timezone, can be set.
if isinstance(tz, str):
import dateutil.tz
tz = dateutil.tz.gettz(tz)
self.update_units(datetime.datetime(2009, 1, 1, 0, 0, 0, 0, tz))
def get_tick_space(self):
"""
Return the estimated number of ticks that can fit on the axis.
"""
# Must be overridden in the subclass
raise NotImplementedError()
def _get_ticks_position(self):
"""
Helper for `XAxis.get_ticks_position` and `YAxis.get_ticks_position`.
Check the visibility of tick1line, label1, tick2line, and label2 on
the first major and the first minor ticks, and return
- 1 if only tick1line and label1 are visible (which corresponds to
"bottom" for the x-axis and "left" for the y-axis);
- 2 if only tick2line and label2 are visible (which corresponds to
"top" for the x-axis and "right" for the y-axis);
- "default" if only tick1line, tick2line and label1 are visible;
- "unknown" otherwise.
"""
major = self.majorTicks[0]
minor = self.minorTicks[0]
if all(tick.tick1line.get_visible()
and not tick.tick2line.get_visible()
and tick.label1.get_visible()
and not tick.label2.get_visible()
for tick in [major, minor]):
return 1
elif all(tick.tick2line.get_visible()
and not tick.tick1line.get_visible()
and tick.label2.get_visible()
and not tick.label1.get_visible()
for tick in [major, minor]):
return 2
elif all(tick.tick1line.get_visible()
and tick.tick2line.get_visible()
and tick.label1.get_visible()
and not tick.label2.get_visible()
for tick in [major, minor]):
return "default"
else:
return "unknown"
def get_label_position(self):
"""
Return the label position (top or bottom)
"""
return self.label_position
def set_label_position(self, position):
"""
Set the label position (top or bottom)
Parameters
----------
position : {'top', 'bottom'}
"""
raise NotImplementedError()
def get_minpos(self):
raise NotImplementedError()
class XAxis(Axis):
__name__ = 'xaxis'
axis_name = 'x'
def contains(self, mouseevent):
"""Test whether the mouse event occurred in the x axis.
"""
if self._contains is not None:
return self._contains(self, mouseevent)
x, y = mouseevent.x, mouseevent.y
try:
trans = self.axes.transAxes.inverted()
xaxes, yaxes = trans.transform_point((x, y))
except ValueError:
return False, {}
l, b = self.axes.transAxes.transform_point((0, 0))
r, t = self.axes.transAxes.transform_point((1, 1))
inaxis = 0 <= xaxes <= 1 and (
b - self.pickradius < y < b or
t < y < t + self.pickradius)
return inaxis, {}
def _get_tick(self, major):
if major:
tick_kw = self._major_tick_kw
else:
tick_kw = self._minor_tick_kw
return XTick(self.axes, 0, '', major=major, **tick_kw)
def _get_label(self):
# x in axes coords, y in display coords (to be updated at draw
# time by _update_label_positions)
label = mtext.Text(x=0.5, y=0,
fontproperties=font_manager.FontProperties(
size=rcParams['axes.labelsize'],
weight=rcParams['axes.labelweight']),
color=rcParams['axes.labelcolor'],
verticalalignment='top',
horizontalalignment='center')
label.set_transform(mtransforms.blended_transform_factory(
self.axes.transAxes, mtransforms.IdentityTransform()))
self._set_artist_props(label)
self.label_position = 'bottom'
return label
def _get_offset_text(self):
# x in axes coords, y in display coords (to be updated at draw time)
offsetText = mtext.Text(x=1, y=0,
fontproperties=font_manager.FontProperties(
size=rcParams['xtick.labelsize']),
color=rcParams['xtick.color'],
verticalalignment='top',
horizontalalignment='right')
offsetText.set_transform(mtransforms.blended_transform_factory(
self.axes.transAxes, mtransforms.IdentityTransform())
)
self._set_artist_props(offsetText)
self.offset_text_position = 'bottom'
return offsetText
def set_label_position(self, position):
"""
Set the label position (top or bottom)
Parameters
----------
position : {'top', 'bottom'}
"""
if position == 'top':
self.label.set_verticalalignment('baseline')
elif position == 'bottom':
self.label.set_verticalalignment('top')
else:
raise ValueError("Position accepts only 'top' or 'bottom'")
self.label_position = position
self.stale = True
def _get_tick_boxes_siblings(self, renderer):
"""
Get the bounding boxes for this `.axis` and its siblings
as set by `.Figure.align_xlabels` or `.Figure.align_ylablels`.
By default it just gets bboxes for self.
"""
bboxes = []
bboxes2 = []
# get the Grouper that keeps track of x-label groups for this figure
grp = self.figure._align_xlabel_grp
# if we want to align labels from other axes:
for nn, axx in enumerate(grp.get_siblings(self.axes)):
ticks_to_draw = axx.xaxis._update_ticks()
tlb, tlb2 = axx.xaxis._get_tick_bboxes(ticks_to_draw, renderer)
bboxes.extend(tlb)
bboxes2.extend(tlb2)
return bboxes, bboxes2
def _update_label_position(self, renderer):
"""
Update the label position based on the bounding box enclosing
all the ticklabels and axis spine
"""
if not self._autolabelpos:
return
# get bounding boxes for this axis and any siblings
# that have been set by `fig.align_xlabels()`
bboxes, bboxes2 = self._get_tick_boxes_siblings(renderer=renderer)
x, y = self.label.get_position()
if self.label_position == 'bottom':
try:
spine = self.axes.spines['bottom']
spinebbox = spine.get_transform().transform_path(
spine.get_path()).get_extents()
except KeyError:
# use axes if spine doesn't exist
spinebbox = self.axes.bbox
bbox = mtransforms.Bbox.union(bboxes + [spinebbox])
bottom = bbox.y0
self.label.set_position(
(x, bottom - self.labelpad * self.figure.dpi / 72)
)
else:
try:
spine = self.axes.spines['top']
spinebbox = spine.get_transform().transform_path(
spine.get_path()).get_extents()
except KeyError:
# use axes if spine doesn't exist
spinebbox = self.axes.bbox
bbox = mtransforms.Bbox.union(bboxes2 + [spinebbox])
top = bbox.y1
self.label.set_position(
(x, top + self.labelpad * self.figure.dpi / 72)
)
def _update_offset_text_position(self, bboxes, bboxes2):
"""
Update the offset_text position based on the sequence of bounding
boxes of all the ticklabels
"""
x, y = self.offsetText.get_position()
if not len(bboxes):
bottom = self.axes.bbox.ymin
else:
bbox = mtransforms.Bbox.union(bboxes)
bottom = bbox.y0
self.offsetText.set_position(
(x, bottom - self.OFFSETTEXTPAD * self.figure.dpi / 72)
)
def get_text_heights(self, renderer):
"""
Returns the amount of space one should reserve for text
above and below the axes. Returns a tuple (above, below)
"""
bbox, bbox2 = self.get_ticklabel_extents(renderer)
# MGDTODO: Need a better way to get the pad
padPixels = self.majorTicks[0].get_pad_pixels()
above = 0.0
if bbox2.height:
above += bbox2.height + padPixels
below = 0.0
if bbox.height:
below += bbox.height + padPixels
if self.get_label_position() == 'top':
above += self.label.get_window_extent(renderer).height + padPixels
else:
below += self.label.get_window_extent(renderer).height + padPixels
return above, below
def set_ticks_position(self, position):
"""
Set the ticks position (top, bottom, both, default or none)
both sets the ticks to appear on both positions, but does not
change the tick labels. 'default' resets the tick positions to
the default: ticks on both positions, labels at bottom. 'none'
can be used if you don't want any ticks. 'none' and 'both'
affect only the ticks, not the labels.
Parameters
----------
position : {'top', 'bottom', 'both', 'default', 'none'}
"""
if position == 'top':
self.set_tick_params(which='both', top=True, labeltop=True,
bottom=False, labelbottom=False)
elif position == 'bottom':
self.set_tick_params(which='both', top=False, labeltop=False,
bottom=True, labelbottom=True)
elif position == 'both':
self.set_tick_params(which='both', top=True,
bottom=True)
elif position == 'none':
self.set_tick_params(which='both', top=False,
bottom=False)
elif position == 'default':
self.set_tick_params(which='both', top=True, labeltop=False,
bottom=True, labelbottom=True)
else:
raise ValueError("invalid position: %s" % position)
self.stale = True
def tick_top(self):
"""
Move ticks and ticklabels (if present) to the top of the axes.
"""
label = True
if 'label1On' in self._major_tick_kw:
label = (self._major_tick_kw['label1On']
or self._major_tick_kw['label2On'])
self.set_ticks_position('top')
# If labels were turned off before this was called, leave them off.
self.set_tick_params(which='both', labeltop=label)
def tick_bottom(self):
"""
Move ticks and ticklabels (if present) to the bottom of the axes.
"""
label = True
if 'label1On' in self._major_tick_kw:
label = (self._major_tick_kw['label1On']
or self._major_tick_kw['label2On'])
self.set_ticks_position('bottom')
# If labels were turned off before this was called, leave them off.
self.set_tick_params(which='both', labelbottom=label)
def get_ticks_position(self):
"""
Return the ticks position ("top", "bottom", "default", or "unknown").
"""
return {1: "bottom", 2: "top",
"default": "default", "unknown": "unknown"}[
self._get_ticks_position()]
def get_view_interval(self):
# docstring inherited
return self.axes.viewLim.intervalx
def set_view_interval(self, vmin, vmax, ignore=False):
# docstring inherited
if ignore:
self.axes.viewLim.intervalx = vmin, vmax
else:
Vmin, Vmax = self.get_view_interval()
if Vmin < Vmax:
self.axes.viewLim.intervalx = (min(vmin, vmax, Vmin),
max(vmin, vmax, Vmax))
else:
self.axes.viewLim.intervalx = (max(vmin, vmax, Vmin),
min(vmin, vmax, Vmax))
def get_minpos(self):
return self.axes.dataLim.minposx
def get_data_interval(self):
# docstring inherited
return self.axes.dataLim.intervalx
def set_data_interval(self, vmin, vmax, ignore=False):
# docstring inherited
if ignore:
self.axes.dataLim.intervalx = vmin, vmax
else:
Vmin, Vmax = self.get_data_interval()
self.axes.dataLim.intervalx = min(vmin, Vmin), max(vmax, Vmax)
self.stale = True
def set_default_intervals(self):
# docstring inherited
xmin, xmax = 0., 1.
dataMutated = self.axes.dataLim.mutatedx()
viewMutated = self.axes.viewLim.mutatedx()
if not dataMutated or not viewMutated:
if self.converter is not None:
info = self.converter.axisinfo(self.units, self)
if info.default_limits is not None:
valmin, valmax = info.default_limits
xmin = self.converter.convert(valmin, self.units, self)
xmax = self.converter.convert(valmax, self.units, self)
if not dataMutated:
self.axes.dataLim.intervalx = xmin, xmax
if not viewMutated:
self.axes.viewLim.intervalx = xmin, xmax
self.stale = True
def get_tick_space(self):
ends = self.axes.transAxes.transform([[0, 0], [1, 0]])
length = ((ends[1][0] - ends[0][0]) / self.axes.figure.dpi) * 72
tick = self._get_tick(True)
# There is a heuristic here that the aspect ratio of tick text
# is no more than 3:1
size = tick.label1.get_size() * 3
if size > 0:
return int(np.floor(length / size))
else:
return 2**31 - 1
class YAxis(Axis):
__name__ = 'yaxis'
axis_name = 'y'
def contains(self, mouseevent):
"""Test whether the mouse event occurred in the y axis.
Returns *True* | *False*
"""
if self._contains is not None:
return self._contains(self, mouseevent)
x, y = mouseevent.x, mouseevent.y
try:
trans = self.axes.transAxes.inverted()
xaxes, yaxes = trans.transform_point((x, y))
except ValueError:
return False, {}
l, b = self.axes.transAxes.transform_point((0, 0))
r, t = self.axes.transAxes.transform_point((1, 1))
inaxis = 0 <= yaxes <= 1 and (
l - self.pickradius < x < l or
r < x < r + self.pickradius)
return inaxis, {}
def _get_tick(self, major):
if major:
tick_kw = self._major_tick_kw
else:
tick_kw = self._minor_tick_kw
return YTick(self.axes, 0, '', major=major, **tick_kw)
def _get_label(self):
# x in display coords (updated by _update_label_position)
# y in axes coords
label = mtext.Text(x=0, y=0.5,
# todo: get the label position
fontproperties=font_manager.FontProperties(
size=rcParams['axes.labelsize'],
weight=rcParams['axes.labelweight']),
color=rcParams['axes.labelcolor'],
verticalalignment='bottom',
horizontalalignment='center',
rotation='vertical',
rotation_mode='anchor')
label.set_transform(mtransforms.blended_transform_factory(
mtransforms.IdentityTransform(), self.axes.transAxes))
self._set_artist_props(label)
self.label_position = 'left'
return label
def _get_offset_text(self):
# x in display coords, y in axes coords (to be updated at draw time)
offsetText = mtext.Text(x=0, y=0.5,
fontproperties=font_manager.FontProperties(
size=rcParams['ytick.labelsize']
),
color=rcParams['ytick.color'],
verticalalignment='baseline',
horizontalalignment='left')
offsetText.set_transform(mtransforms.blended_transform_factory(
self.axes.transAxes, mtransforms.IdentityTransform())
)
self._set_artist_props(offsetText)
self.offset_text_position = 'left'
return offsetText
def set_label_position(self, position):
"""
Set the label position (left or right)
Parameters
----------
position : {'left', 'right'}
"""
self.label.set_rotation_mode('anchor')
self.label.set_horizontalalignment('center')
if position == 'left':
self.label.set_verticalalignment('bottom')
elif position == 'right':
self.label.set_verticalalignment('top')
else:
raise ValueError("Position accepts only 'left' or 'right'")
self.label_position = position
self.stale = True
def _get_tick_boxes_siblings(self, renderer):
"""
Get the bounding boxes for this `.axis` and its siblings
as set by `.Figure.align_xlabels` or `.Figure.align_ylablels`.
By default it just gets bboxes for self.
"""
bboxes = []
bboxes2 = []
# get the Grouper that keeps track of y-label groups for this figure
grp = self.figure._align_ylabel_grp
# if we want to align labels from other axes:
for axx in grp.get_siblings(self.axes):
ticks_to_draw = axx.yaxis._update_ticks()
tlb, tlb2 = axx.yaxis._get_tick_bboxes(ticks_to_draw, renderer)
bboxes.extend(tlb)
bboxes2.extend(tlb2)
return bboxes, bboxes2
def _update_label_position(self, renderer):
"""
Update the label position based on the bounding box enclosing
all the ticklabels and axis spine
"""
if not self._autolabelpos:
return
# get bounding boxes for this axis and any siblings
# that have been set by `fig.align_ylabels()`
bboxes, bboxes2 = self._get_tick_boxes_siblings(renderer=renderer)
x, y = self.label.get_position()
if self.label_position == 'left':
try:
spine = self.axes.spines['left']
spinebbox = spine.get_transform().transform_path(
spine.get_path()).get_extents()
except KeyError:
# use axes if spine doesn't exist
spinebbox = self.axes.bbox
bbox = mtransforms.Bbox.union(bboxes + [spinebbox])
left = bbox.x0
self.label.set_position(
(left - self.labelpad * self.figure.dpi / 72, y)
)
else:
try:
spine = self.axes.spines['right']
spinebbox = spine.get_transform().transform_path(
spine.get_path()).get_extents()
except KeyError:
# use axes if spine doesn't exist
spinebbox = self.axes.bbox
bbox = mtransforms.Bbox.union(bboxes2 + [spinebbox])
right = bbox.x1
self.label.set_position(
(right + self.labelpad * self.figure.dpi / 72, y)
)
def _update_offset_text_position(self, bboxes, bboxes2):
"""
Update the offset_text position based on the sequence of bounding
boxes of all the ticklabels
"""
x, y = self.offsetText.get_position()
top = self.axes.bbox.ymax
self.offsetText.set_position(
(x, top + self.OFFSETTEXTPAD * self.figure.dpi / 72)
)
def set_offset_position(self, position):
"""
Parameters
----------
position : {'left', 'right'}
"""
x, y = self.offsetText.get_position()
if position == 'left':
x = 0
elif position == 'right':
x = 1
else:
raise ValueError("Position accepts only [ 'left' | 'right' ]")
self.offsetText.set_ha(position)
self.offsetText.set_position((x, y))
self.stale = True
def get_text_widths(self, renderer):
bbox, bbox2 = self.get_ticklabel_extents(renderer)
# MGDTODO: Need a better way to get the pad
padPixels = self.majorTicks[0].get_pad_pixels()
left = 0.0
if bbox.width:
left += bbox.width + padPixels
right = 0.0
if bbox2.width:
right += bbox2.width + padPixels
if self.get_label_position() == 'left':
left += self.label.get_window_extent(renderer).width + padPixels
else:
right += self.label.get_window_extent(renderer).width + padPixels
return left, right
def set_ticks_position(self, position):
"""
Set the ticks position (left, right, both, default or none)
'both' sets the ticks to appear on both positions, but does not
change the tick labels. 'default' resets the tick positions to
the default: ticks on both positions, labels at left. 'none'
can be used if you don't want any ticks. 'none' and 'both'
affect only the ticks, not the labels.
Parameters
----------
position : {'left', 'right', 'both', 'default', 'none'}
"""
if position == 'right':
self.set_tick_params(which='both', right=True, labelright=True,
left=False, labelleft=False)
self.set_offset_position(position)
elif position == 'left':
self.set_tick_params(which='both', right=False, labelright=False,
left=True, labelleft=True)
self.set_offset_position(position)
elif position == 'both':
self.set_tick_params(which='both', right=True,
left=True)
elif position == 'none':
self.set_tick_params(which='both', right=False,
left=False)
elif position == 'default':
self.set_tick_params(which='both', right=True, labelright=False,
left=True, labelleft=True)
else:
raise ValueError("invalid position: %s" % position)
self.stale = True
def tick_right(self):
"""
Move ticks and ticklabels (if present) to the right of the axes.
"""
label = True
if 'label1On' in self._major_tick_kw:
label = (self._major_tick_kw['label1On']
or self._major_tick_kw['label2On'])
self.set_ticks_position('right')
# if labels were turned off before this was called
# leave them off
self.set_tick_params(which='both', labelright=label)
def tick_left(self):
"""
Move ticks and ticklabels (if present) to the left of the axes.
"""
label = True
if 'label1On' in self._major_tick_kw:
label = (self._major_tick_kw['label1On']
or self._major_tick_kw['label2On'])
self.set_ticks_position('left')
# if labels were turned off before this was called
# leave them off
self.set_tick_params(which='both', labelleft=label)
def get_ticks_position(self):
"""
Return the ticks position ("left", "right", "default", or "unknown").
"""
return {1: "left", 2: "right",
"default": "default", "unknown": "unknown"}[
self._get_ticks_position()]
def get_view_interval(self):
# docstring inherited
return self.axes.viewLim.intervaly
def set_view_interval(self, vmin, vmax, ignore=False):
# docstring inherited
if ignore:
self.axes.viewLim.intervaly = vmin, vmax
else:
Vmin, Vmax = self.get_view_interval()
if Vmin < Vmax:
self.axes.viewLim.intervaly = (min(vmin, vmax, Vmin),
max(vmin, vmax, Vmax))
else:
self.axes.viewLim.intervaly = (max(vmin, vmax, Vmin),
min(vmin, vmax, Vmax))
self.stale = True
def get_minpos(self):
return self.axes.dataLim.minposy
def get_data_interval(self):
# docstring inherited
return self.axes.dataLim.intervaly
def set_data_interval(self, vmin, vmax, ignore=False):
# docstring inherited
if ignore:
self.axes.dataLim.intervaly = vmin, vmax
else:
Vmin, Vmax = self.get_data_interval()
self.axes.dataLim.intervaly = min(vmin, Vmin), max(vmax, Vmax)
self.stale = True
def set_default_intervals(self):
# docstring inherited
ymin, ymax = 0., 1.
dataMutated = self.axes.dataLim.mutatedy()
viewMutated = self.axes.viewLim.mutatedy()
if not dataMutated or not viewMutated:
if self.converter is not None:
info = self.converter.axisinfo(self.units, self)
if info.default_limits is not None:
valmin, valmax = info.default_limits
ymin = self.converter.convert(valmin, self.units, self)
ymax = self.converter.convert(valmax, self.units, self)
if not dataMutated:
self.axes.dataLim.intervaly = ymin, ymax
if not viewMutated:
self.axes.viewLim.intervaly = ymin, ymax
self.stale = True
def get_tick_space(self):
ends = self.axes.transAxes.transform([[0, 0], [0, 1]])
length = ((ends[1][1] - ends[0][1]) / self.axes.figure.dpi) * 72
tick = self._get_tick(True)
# Having a spacing of at least 2 just looks good.
size = tick.label1.get_size() * 2.0
if size > 0:
return int(np.floor(length / size))
else:
return 2**31 - 1
|
27f310253efd541211f23e8a4869a48937bafe01f982154bcee11121fb783544
|
"""
This is a procedural interface to the matplotlib object-oriented
plotting library.
The following plotting commands are provided; the majority have
MATLAB |reg| [*]_ analogs and similar arguments.
.. |reg| unicode:: 0xAE
_Plotting commands
acorr - plot the autocorrelation function
annotate - annotate something in the figure
arrow - add an arrow to the axes
axes - Create a new axes
axhline - draw a horizontal line across axes
axvline - draw a vertical line across axes
axhspan - draw a horizontal bar across axes
axvspan - draw a vertical bar across axes
axis - Set or return the current axis limits
autoscale - turn axis autoscaling on or off, and apply it
bar - make a bar chart
barh - a horizontal bar chart
broken_barh - a set of horizontal bars with gaps
box - set the axes frame on/off state
boxplot - make a box and whisker plot
violinplot - make a violin plot
cla - clear current axes
clabel - label a contour plot
clf - clear a figure window
clim - adjust the color limits of the current image
close - close a figure window
colorbar - add a colorbar to the current figure
cohere - make a plot of coherence
contour - make a contour plot
contourf - make a filled contour plot
csd - make a plot of cross spectral density
delaxes - delete an axes from the current figure
draw - Force a redraw of the current figure
errorbar - make an errorbar graph
figlegend - make legend on the figure rather than the axes
figimage - make a figure image
figtext - add text in figure coords
figure - create or change active figure
fill - make filled polygons
findobj - recursively find all objects matching some criteria
gca - return the current axes
gcf - return the current figure
gci - get the current image, or None
getp - get a graphics property
grid - set whether gridding is on
hist - make a histogram
ioff - turn interaction mode off
ion - turn interaction mode on
isinteractive - return True if interaction mode is on
imread - load image file into array
imsave - save array as an image file
imshow - plot image data
legend - make an axes legend
locator_params - adjust parameters used in locating axis ticks
loglog - a log log plot
matshow - display a matrix in a new figure preserving aspect
margins - set margins used in autoscaling
pause - pause for a specified interval
pcolor - make a pseudocolor plot
pcolormesh - make a pseudocolor plot using a quadrilateral mesh
pie - make a pie chart
plot - make a line plot
plot_date - plot dates
plotfile - plot column data from an ASCII tab/space/comma delimited file
pie - pie charts
polar - make a polar plot on a PolarAxes
psd - make a plot of power spectral density
quiver - make a direction field (arrows) plot
rc - control the default params
rgrids - customize the radial grids and labels for polar
savefig - save the current figure
scatter - make a scatter plot
setp - set a graphics property
semilogx - log x axis
semilogy - log y axis
show - show the figures
specgram - a spectrogram plot
spy - plot sparsity pattern using markers or image
stem - make a stem plot
subplot - make one subplot (numrows, numcols, axesnum)
subplots - make a figure with a set of (numrows, numcols) subplots
subplots_adjust - change the params controlling the subplot positions of current figure
subplot_tool - launch the subplot configuration tool
suptitle - add a figure title
table - add a table to the plot
text - add some text at location x,y to the current axes
thetagrids - customize the radial theta grids and labels for polar
tick_params - control the appearance of ticks and tick labels
ticklabel_format - control the format of tick labels
title - add a title to the current axes
tricontour - make a contour plot on a triangular grid
tricontourf - make a filled contour plot on a triangular grid
tripcolor - make a pseudocolor plot on a triangular grid
triplot - plot a triangular grid
xcorr - plot the autocorrelation function of x and y
xlim - set/get the xlimits
ylim - set/get the ylimits
xticks - set/get the xticks
yticks - set/get the yticks
xlabel - add an xlabel to the current axes
ylabel - add a ylabel to the current axes
autumn - set the default colormap to autumn
bone - set the default colormap to bone
cool - set the default colormap to cool
copper - set the default colormap to copper
flag - set the default colormap to flag
gray - set the default colormap to gray
hot - set the default colormap to hot
hsv - set the default colormap to hsv
jet - set the default colormap to jet
pink - set the default colormap to pink
prism - set the default colormap to prism
spring - set the default colormap to spring
summer - set the default colormap to summer
winter - set the default colormap to winter
_Event handling
connect - register an event handler
disconnect - remove a connected event handler
_Matrix commands
cumprod - the cumulative product along a dimension
cumsum - the cumulative sum along a dimension
detrend - remove the mean or besdt fit line from an array
diag - the k-th diagonal of matrix
diff - the n-th difference of an array
eig - the eigenvalues and eigen vectors of v
eye - a matrix where the k-th diagonal is ones, else zero
find - return the indices where a condition is nonzero
fliplr - flip the rows of a matrix up/down
flipud - flip the columns of a matrix left/right
linspace - a linear spaced vector of N values from min to max inclusive
logspace - a log spaced vector of N values from min to max inclusive
meshgrid - repeat x and y to make regular matrices
ones - an array of ones
rand - an array from the uniform distribution [0,1]
randn - an array from the normal distribution
rot90 - rotate matrix k*90 degrees counterclockwise
squeeze - squeeze an array removing any dimensions of length 1
tri - a triangular matrix
tril - a lower triangular matrix
triu - an upper triangular matrix
vander - the Vandermonde matrix of vector x
svd - singular value decomposition
zeros - a matrix of zeros
_Probability
rand - random numbers from the uniform distribution
randn - random numbers from the normal distribution
_Statistics
amax - the maximum along dimension m
amin - the minimum along dimension m
corrcoef - correlation coefficient
cov - covariance matrix
mean - the mean along dimension m
median - the median along dimension m
norm - the norm of vector x
prod - the product along dimension m
ptp - the max-min along dimension m
std - the standard deviation along dimension m
asum - the sum along dimension m
ksdensity - the kernel density estimate
_Time series analysis
bartlett - M-point Bartlett window
blackman - M-point Blackman window
cohere - the coherence using average periodogram
csd - the cross spectral density using average periodogram
fft - the fast Fourier transform of vector x
hamming - M-point Hamming window
hanning - M-point Hanning window
hist - compute the histogram of x
kaiser - M length Kaiser window
psd - the power spectral density using average periodogram
sinc - the sinc function of array x
_Dates
date2num - convert python datetimes to numeric representation
drange - create an array of numbers for date plots
num2date - convert numeric type (float days since 0001) to datetime
_Other
angle - the angle of a complex array
load - Deprecated--please use loadtxt.
loadtxt - load ASCII data into array.
polyfit - fit x, y to an n-th order polynomial
polyval - evaluate an n-th order polynomial
roots - the roots of the polynomial coefficients in p
save - Deprecated--please use savetxt.
savetxt - save an array to an ASCII file.
trapz - trapezoidal integration
__end
.. [*] MATLAB is a registered trademark of The MathWorks, Inc.
"""
from matplotlib.cbook import flatten, silent_list, iterable, dedent
import matplotlib as mpl
from matplotlib.dates import (
date2num, num2date, datestr2num, strpdate2num, drange, epoch2num,
num2epoch, mx2num, DateFormatter, IndexDateFormatter, DateLocator,
RRuleLocator, YearLocator, MonthLocator, WeekdayLocator, DayLocator,
HourLocator, MinuteLocator, SecondLocator, rrule, MO, TU, WE, TH, FR,
SA, SU, YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, SECONDLY,
relativedelta)
# bring all the symbols in so folks can import them from
# pylab in one fell swoop
## We are still importing too many things from mlab; more cleanup is needed.
from matplotlib.mlab import (
demean, detrend, detrend_linear, detrend_mean, detrend_none,
window_hanning, window_none)
from matplotlib import cbook, mlab, pyplot as plt
from matplotlib.pyplot import *
from numpy import *
from numpy.fft import *
from numpy.random import *
from numpy.linalg import *
import numpy as np
import numpy.ma as ma
# don't let numpy's datetime hide stdlib
import datetime
# This is needed, or bytes will be numpy.random.bytes from
# "from numpy.random import *" above
bytes = __import__("builtins").bytes
|
eb51fc2e00aec5fe0b746d9943b1063249a54c082ca7229eba1a6e0fd24a91ac
|
import matplotlib.cbook as cbook
import matplotlib.artist as martist
class Container(tuple):
"""
Base class for containers.
Containers are classes that collect semantically related Artists such as
the bars of a bar plot.
"""
def __repr__(self):
return ("<{} object of {} artists>"
.format(type(self).__name__, len(self)))
def __new__(cls, *args, **kwargs):
return tuple.__new__(cls, args[0])
def __init__(self, kl, label=None):
self.eventson = False # fire events only if eventson
self._oid = 0 # an observer id
self._propobservers = {} # a dict from oids to funcs
self._remove_method = None
self.set_label(label)
@cbook.deprecated("3.0")
def set_remove_method(self, f):
self._remove_method = f
def remove(self):
for c in cbook.flatten(
self, scalarp=lambda x: isinstance(x, martist.Artist)):
if c is not None:
c.remove()
if self._remove_method:
self._remove_method(self)
def get_label(self):
"""
Get the label used for this artist in the legend.
"""
return self._label
def set_label(self, s):
"""
Set the label to *s* for auto legend.
Parameters
----------
s : object
Any object other than None gets converted to its `str`.
"""
if s is not None:
self._label = str(s)
else:
self._label = None
self.pchanged()
def add_callback(self, func):
"""
Adds a callback function that will be called whenever one of
the :class:`Artist`'s properties changes.
Returns an *id* that is useful for removing the callback with
:meth:`remove_callback` later.
"""
oid = self._oid
self._propobservers[oid] = func
self._oid += 1
return oid
def remove_callback(self, oid):
"""
Remove a callback based on its *id*.
.. seealso::
:meth:`add_callback`
For adding callbacks
"""
try:
del self._propobservers[oid]
except KeyError:
pass
def pchanged(self):
"""
Fire an event when property changed, calling all of the
registered callbacks.
"""
for oid, func in list(self._propobservers.items()):
func(self)
def get_children(self):
return [child for child in cbook.flatten(self) if child is not None]
class BarContainer(Container):
"""
Container for the artists of bar plots (e.g. created by `.Axes.bar`).
The container can be treated as a tuple of the *patches* themselves.
Additionally, you can access these and further parameters by the
attributes.
Attributes
----------
patches : list of :class:`~matplotlib.patches.Rectangle`
The artists of the bars.
errorbar : None or :class:`~matplotlib.container.ErrorbarContainer`
A container for the error bar artists if error bars are present.
*None* otherwise.
"""
def __init__(self, patches, errorbar=None, **kwargs):
self.patches = patches
self.errorbar = errorbar
Container.__init__(self, patches, **kwargs)
class ErrorbarContainer(Container):
"""
Container for the artists of error bars (e.g. created by `.Axes.errorbar`).
The container can be treated as the *lines* tuple itself.
Additionally, you can access these and further parameters by the
attributes.
Attributes
----------
lines : tuple
Tuple of ``(data_line, caplines, barlinecols)``.
- data_line : :class:`~matplotlib.lines.Line2D` instance of
x, y plot markers and/or line.
- caplines : tuple of :class:`~matplotlib.lines.Line2D` instances of
the error bar caps.
- barlinecols : list of :class:`~matplotlib.collections.LineCollection`
with the horizontal and vertical error ranges.
has_xerr, has_yerr : bool
``True`` if the errorbar has x/y errors.
"""
def __init__(self, lines, has_xerr=False, has_yerr=False, **kwargs):
self.lines = lines
self.has_xerr = has_xerr
self.has_yerr = has_yerr
Container.__init__(self, lines, **kwargs)
class StemContainer(Container):
"""
Container for the artists created in a :meth:`.Axes.stem` plot.
The container can be treated like a namedtuple ``(markerline, stemlines,
baseline)``.
Attributes
----------
markerline : :class:`~matplotlib.lines.Line2D`
The artist of the markers at the stem heads.
stemlines : list of :class:`~matplotlib.lines.Line2D`
The artists of the vertical lines for all stems.
baseline : :class:`~matplotlib.lines.Line2D`
The artist of the horizontal baseline.
"""
def __init__(self, markerline_stemlines_baseline, **kwargs):
"""
Parameters
----------
markerline_stemlines_baseline : tuple
Tuple of ``(markerline, stemlines, baseline)``.
``markerline`` contains the `LineCollection` of the markers,
``stemlines`` is a `LineCollection` of the main lines,
``baseline`` is the `Line2D` of the baseline.
"""
markerline, stemlines, baseline = markerline_stemlines_baseline
self.markerline = markerline
self.stemlines = stemlines
self.baseline = baseline
Container.__init__(self, markerline_stemlines_baseline, **kwargs)
|
03a4b5bd061bb58a945637ea9598a09854397efe645f4713c5567f1d5f7d0f3f
|
# Note: The first part of this file can be modified in place, but the latter
# part is autogenerated by the boilerplate.py script.
"""
`matplotlib.pyplot` is a state-based interface to matplotlib. It provides
a MATLAB-like way of plotting.
pyplot is mainly intended for interactive plots and simple cases of
programmatic plot generation::
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 5, 0.1)
y = np.sin(x)
plt.plot(x, y)
The object-oriented API is recommended for more complex plots.
"""
import functools
import importlib
import inspect
import logging
from numbers import Number
import re
import sys
import time
from cycler import cycler
import matplotlib
import matplotlib.colorbar
import matplotlib.image
from matplotlib import rcsetup, style
from matplotlib import _pylab_helpers, interactive
from matplotlib import cbook
from matplotlib.cbook import dedent, deprecated, silent_list, warn_deprecated
from matplotlib import docstring
from matplotlib.backend_bases import FigureCanvasBase
from matplotlib.figure import Figure, figaspect
from matplotlib.gridspec import GridSpec
from matplotlib import rcParams, rcParamsDefault, get_backend, rcParamsOrig
from matplotlib import rc_context
from matplotlib.rcsetup import interactive_bk as _interactive_bk
from matplotlib.artist import getp, get, Artist
from matplotlib.artist import setp as _setp
from matplotlib.axes import Axes, Subplot
from matplotlib.projections import PolarAxes
from matplotlib import mlab # for _csv2rec, detrend_none, window_hanning
from matplotlib.scale import get_scale_docs, get_scale_names
from matplotlib import cm
from matplotlib.cm import get_cmap, register_cmap
import numpy as np
# We may not need the following imports here:
from matplotlib.colors import Normalize
from matplotlib.lines import Line2D
from matplotlib.text import Text, Annotation
from matplotlib.patches import Polygon, Rectangle, Circle, Arrow
from matplotlib.widgets import SubplotTool, Button, Slider, Widget
from .ticker import TickHelper, Formatter, FixedFormatter, NullFormatter,\
FuncFormatter, FormatStrFormatter, ScalarFormatter,\
LogFormatter, LogFormatterExponent, LogFormatterMathtext,\
Locator, IndexLocator, FixedLocator, NullLocator,\
LinearLocator, LogLocator, AutoLocator, MultipleLocator,\
MaxNLocator
from matplotlib.backends import pylab_setup, _get_running_interactive_framework
_log = logging.getLogger(__name__)
## Global ##
_IP_REGISTERED = None
_INSTALL_FIG_OBSERVER = False
def install_repl_displayhook():
"""
Install a repl display hook so that any stale figure are automatically
redrawn when control is returned to the repl.
This works both with IPython and with vanilla python shells.
"""
global _IP_REGISTERED
global _INSTALL_FIG_OBSERVER
class _NotIPython(Exception):
pass
# see if we have IPython hooks around, if use them
try:
if 'IPython' in sys.modules:
from IPython import get_ipython
ip = get_ipython()
if ip is None:
raise _NotIPython()
if _IP_REGISTERED:
return
def post_execute():
if matplotlib.is_interactive():
draw_all()
# IPython >= 2
try:
ip.events.register('post_execute', post_execute)
except AttributeError:
# IPython 1.x
ip.register_post_execute(post_execute)
_IP_REGISTERED = post_execute
_INSTALL_FIG_OBSERVER = False
# trigger IPython's eventloop integration, if available
from IPython.core.pylabtools import backend2gui
ipython_gui_name = backend2gui.get(get_backend())
if ipython_gui_name:
ip.enable_gui(ipython_gui_name)
else:
_INSTALL_FIG_OBSERVER = True
# import failed or ipython is not running
except (ImportError, _NotIPython):
_INSTALL_FIG_OBSERVER = True
def uninstall_repl_displayhook():
"""
Uninstall the matplotlib display hook.
.. warning
Need IPython >= 2 for this to work. For IPython < 2 will raise a
``NotImplementedError``
.. warning
If you are using vanilla python and have installed another
display hook this will reset ``sys.displayhook`` to what ever
function was there when matplotlib installed it's displayhook,
possibly discarding your changes.
"""
global _IP_REGISTERED
global _INSTALL_FIG_OBSERVER
if _IP_REGISTERED:
from IPython import get_ipython
ip = get_ipython()
try:
ip.events.unregister('post_execute', _IP_REGISTERED)
except AttributeError:
raise NotImplementedError("Can not unregister events "
"in IPython < 2.0")
_IP_REGISTERED = None
if _INSTALL_FIG_OBSERVER:
_INSTALL_FIG_OBSERVER = False
draw_all = _pylab_helpers.Gcf.draw_all
@functools.wraps(matplotlib.set_loglevel)
def set_loglevel(*args, **kwargs): # Ensure this appears in the pyplot docs.
return matplotlib.set_loglevel(*args, **kwargs)
@docstring.copy(Artist.findobj)
def findobj(o=None, match=None, include_self=True):
if o is None:
o = gcf()
return o.findobj(match, include_self=include_self)
def switch_backend(newbackend):
"""
Close all open figures and set the Matplotlib backend.
The argument is case-insensitive. Switching to an interactive backend is
possible only if no event loop for another interactive backend has started.
Switching to and from non-interactive backends is always possible.
Parameters
----------
newbackend : str
The name of the backend to use.
"""
close("all")
if newbackend is rcsetup._auto_backend_sentinel:
# Don't try to fallback on the cairo-based backends as they each have
# an additional dependency (pycairo) over the agg-based backend, and
# are of worse quality.
for candidate in ["macosx", "qt5agg", "qt4agg", "gtk3agg", "tkagg",
"wxagg", "agg"]:
try:
switch_backend(candidate)
except ImportError:
continue
else:
rcParamsOrig['backend'] = candidate
return
backend_name = (
newbackend[9:] if newbackend.startswith("module://")
else "matplotlib.backends.backend_{}".format(newbackend.lower()))
backend_mod = importlib.import_module(backend_name)
Backend = type(
"Backend", (matplotlib.backends._Backend,), vars(backend_mod))
_log.debug("Loaded backend %s version %s.",
newbackend, Backend.backend_version)
required_framework = Backend.required_interactive_framework
if required_framework is not None:
current_framework = \
matplotlib.backends._get_running_interactive_framework()
if (current_framework and required_framework
and current_framework != required_framework):
raise ImportError(
"Cannot load backend {!r} which requires the {!r} interactive "
"framework, as {!r} is currently running".format(
newbackend, required_framework, current_framework))
rcParams['backend'] = rcParamsDefault['backend'] = newbackend
global _backend_mod, new_figure_manager, draw_if_interactive, _show
_backend_mod = backend_mod
new_figure_manager = Backend.new_figure_manager
draw_if_interactive = Backend.draw_if_interactive
_show = Backend.show
# Need to keep a global reference to the backend for compatibility reasons.
# See https://github.com/matplotlib/matplotlib/issues/6092
matplotlib.backends.backend = newbackend
def show(*args, **kw):
"""
Display a figure.
When running in ipython with its pylab mode, display all
figures and return to the ipython prompt.
In non-interactive mode, display all figures and block until
the figures have been closed; in interactive mode it has no
effect unless figures were created prior to a change from
non-interactive to interactive mode (not recommended). In
that case it displays the figures but does not block.
A single experimental keyword argument, *block*, may be
set to True or False to override the blocking behavior
described above.
"""
global _show
return _show(*args, **kw)
def isinteractive():
"""Return the status of interactive mode."""
return matplotlib.is_interactive()
def ioff():
"""Turn the interactive mode off."""
matplotlib.interactive(False)
uninstall_repl_displayhook()
def ion():
"""Turn the interactive mode on."""
matplotlib.interactive(True)
install_repl_displayhook()
def pause(interval):
"""
Pause for *interval* seconds.
If there is an active figure, it will be updated and displayed before the
pause, and the GUI event loop (if any) will run during the pause.
This can be used for crude animation. For more complex animation, see
:mod:`matplotlib.animation`.
Notes
-----
This function is experimental; its behavior may be changed or extended in a
future release.
"""
manager = _pylab_helpers.Gcf.get_active()
if manager is not None:
canvas = manager.canvas
if canvas.figure.stale:
canvas.draw_idle()
show(block=False)
canvas.start_event_loop(interval)
else:
time.sleep(interval)
@docstring.copy(matplotlib.rc)
def rc(group, **kwargs):
matplotlib.rc(group, **kwargs)
@docstring.copy(matplotlib.rc_context)
def rc_context(rc=None, fname=None):
return matplotlib.rc_context(rc, fname)
@docstring.copy(matplotlib.rcdefaults)
def rcdefaults():
matplotlib.rcdefaults()
if matplotlib.is_interactive():
draw_all()
## Current image ##
def gci():
"""
Get the current colorable artist. Specifically, returns the
current :class:`~matplotlib.cm.ScalarMappable` instance (image or
patch collection), or *None* if no images or patch collections
have been defined. The commands :func:`~matplotlib.pyplot.imshow`
and :func:`~matplotlib.pyplot.figimage` create
:class:`~matplotlib.image.Image` instances, and the commands
:func:`~matplotlib.pyplot.pcolor` and
:func:`~matplotlib.pyplot.scatter` create
:class:`~matplotlib.collections.Collection` instances. The
current image is an attribute of the current axes, or the nearest
earlier axes in the current figure that contains an image.
"""
return gcf()._gci()
## Any Artist ##
# (getp is simply imported)
@docstring.copy(_setp)
def setp(obj, *args, **kwargs):
return _setp(obj, *args, **kwargs)
def xkcd(scale=1, length=100, randomness=2):
"""
Turn on `xkcd <https://xkcd.com/>`_ sketch-style drawing mode.
This will only have effect on things drawn after this function is
called.
For best results, the "Humor Sans" font should be installed: it is
not included with matplotlib.
Parameters
----------
scale : float, optional
The amplitude of the wiggle perpendicular to the source line.
length : float, optional
The length of the wiggle along the line.
randomness : float, optional
The scale factor by which the length is shrunken or expanded.
Notes
-----
This function works by a number of rcParams, so it will probably
override others you have set before.
If you want the effects of this function to be temporary, it can
be used as a context manager, for example::
with plt.xkcd():
# This figure will be in XKCD-style
fig1 = plt.figure()
# ...
# This figure will be in regular style
fig2 = plt.figure()
"""
if rcParams['text.usetex']:
raise RuntimeError(
"xkcd mode is not compatible with text.usetex = True")
from matplotlib import patheffects
return rc_context({
'font.family': ['xkcd', 'Humor Sans', 'Comic Sans MS'],
'font.size': 14.0,
'path.sketch': (scale, length, randomness),
'path.effects': [patheffects.withStroke(linewidth=4, foreground="w")],
'axes.linewidth': 1.5,
'lines.linewidth': 2.0,
'figure.facecolor': 'white',
'grid.linewidth': 0.0,
'axes.grid': False,
'axes.unicode_minus': False,
'axes.edgecolor': 'black',
'xtick.major.size': 8,
'xtick.major.width': 3,
'ytick.major.size': 8,
'ytick.major.width': 3,
})
## Figures ##
def figure(num=None, # autoincrement if None, else integer from 1-N
figsize=None, # defaults to rc figure.figsize
dpi=None, # defaults to rc figure.dpi
facecolor=None, # defaults to rc figure.facecolor
edgecolor=None, # defaults to rc figure.edgecolor
frameon=True,
FigureClass=Figure,
clear=False,
**kwargs
):
"""
Create a new figure.
Parameters
----------
num : integer or string, optional, default: None
If not provided, a new figure will be created, and the figure number
will be incremented. The figure objects holds this number in a `number`
attribute.
If num is provided, and a figure with this id already exists, make
it active, and returns a reference to it. If this figure does not
exists, create it and returns it.
If num is a string, the window title will be set to this figure's
`num`.
figsize : (float, float), optional, default: None
width, height in inches. If not provided, defaults to
:rc:`figure.figsize` = ``[6.4, 4.8]``.
dpi : integer, optional, default: None
resolution of the figure. If not provided, defaults to
:rc:`figure.dpi` = ``100``.
facecolor : color spec
the background color. If not provided, defaults to
:rc:`figure.facecolor` = ``'w'``.
edgecolor : color spec
the border color. If not provided, defaults to
:rc:`figure.edgecolor` = ``'w'``.
frameon : bool, optional, default: True
If False, suppress drawing the figure frame.
FigureClass : subclass of `~matplotlib.figure.Figure`
Optionally use a custom `.Figure` instance.
clear : bool, optional, default: False
If True and the figure already exists, then it is cleared.
Returns
-------
figure : `~matplotlib.figure.Figure`
The `.Figure` instance returned will also be passed to
new_figure_manager in the backends, which allows to hook custom
`.Figure` classes into the pyplot interface. Additional kwargs will be
passed to the `.Figure` init function.
Notes
-----
If you are creating many figures, make sure you explicitly call
:func:`.pyplot.close` on the figures you are not using, because this will
enable pyplot to properly clean up the memory.
`~matplotlib.rcParams` defines the default values, which can be modified
in the matplotlibrc file.
"""
if figsize is None:
figsize = rcParams['figure.figsize']
if dpi is None:
dpi = rcParams['figure.dpi']
if facecolor is None:
facecolor = rcParams['figure.facecolor']
if edgecolor is None:
edgecolor = rcParams['figure.edgecolor']
allnums = get_fignums()
next_num = max(allnums) + 1 if allnums else 1
figLabel = ''
if num is None:
num = next_num
elif isinstance(num, str):
figLabel = num
allLabels = get_figlabels()
if figLabel not in allLabels:
if figLabel == 'all':
cbook._warn_external(
"close('all') closes all existing figures")
num = next_num
else:
inum = allLabels.index(figLabel)
num = allnums[inum]
else:
num = int(num) # crude validation of num argument
figManager = _pylab_helpers.Gcf.get_fig_manager(num)
if figManager is None:
max_open_warning = rcParams['figure.max_open_warning']
if len(allnums) >= max_open_warning >= 1:
cbook._warn_external(
"More than %d figures have been opened. Figures "
"created through the pyplot interface "
"(`matplotlib.pyplot.figure`) are retained until "
"explicitly closed and may consume too much memory. "
"(To control this warning, see the rcParam "
"`figure.max_open_warning`)." %
max_open_warning, RuntimeWarning)
if get_backend().lower() == 'ps':
dpi = 72
figManager = new_figure_manager(num, figsize=figsize,
dpi=dpi,
facecolor=facecolor,
edgecolor=edgecolor,
frameon=frameon,
FigureClass=FigureClass,
**kwargs)
if figLabel:
figManager.set_window_title(figLabel)
figManager.canvas.figure.set_label(figLabel)
# make this figure current on button press event
def make_active(event):
_pylab_helpers.Gcf.set_active(figManager)
cid = figManager.canvas.mpl_connect('button_press_event', make_active)
figManager._cidgcf = cid
_pylab_helpers.Gcf.set_active(figManager)
fig = figManager.canvas.figure
fig.number = num
# make sure backends (inline) that we don't ship that expect this
# to be called in plotting commands to make the figure call show
# still work. There is probably a better way to do this in the
# FigureManager base class.
if matplotlib.is_interactive():
draw_if_interactive()
if _INSTALL_FIG_OBSERVER:
fig.stale_callback = _auto_draw_if_interactive
if clear:
figManager.canvas.figure.clear()
return figManager.canvas.figure
def _auto_draw_if_interactive(fig, val):
"""
This is an internal helper function for making sure that auto-redrawing
works as intended in the plain python repl.
Parameters
----------
fig : Figure
A figure object which is assumed to be associated with a canvas
"""
if val and matplotlib.is_interactive() and not fig.canvas.is_saving():
fig.canvas.draw_idle()
def gcf():
"""Get a reference to the current figure."""
figManager = _pylab_helpers.Gcf.get_active()
if figManager is not None:
return figManager.canvas.figure
else:
return figure()
def fignum_exists(num):
"""Return whether the figure with the given id exists."""
return _pylab_helpers.Gcf.has_fignum(num) or num in get_figlabels()
def get_fignums():
"""Return a list of existing figure numbers."""
return sorted(_pylab_helpers.Gcf.figs)
def get_figlabels():
"""Return a list of existing figure labels."""
figManagers = _pylab_helpers.Gcf.get_all_fig_managers()
figManagers.sort(key=lambda m: m.num)
return [m.canvas.figure.get_label() for m in figManagers]
def get_current_fig_manager():
"""
Return the figure manager of the active figure.
If there is currently no active figure, a new one is created.
"""
figManager = _pylab_helpers.Gcf.get_active()
if figManager is None:
gcf() # creates an active figure as a side effect
figManager = _pylab_helpers.Gcf.get_active()
return figManager
@docstring.copy(FigureCanvasBase.mpl_connect)
def connect(s, func):
return get_current_fig_manager().canvas.mpl_connect(s, func)
@docstring.copy(FigureCanvasBase.mpl_disconnect)
def disconnect(cid):
return get_current_fig_manager().canvas.mpl_disconnect(cid)
def close(fig=None):
"""
Close a figure window.
Parameters
----------
fig : None or int or str or `.Figure`
The figure to close. There are a number of ways to specify this:
- *None*: the current figure
- `.Figure`: the given `.Figure` instance
- ``int``: a figure number
- ``str``: a figure name
- 'all': all figures
"""
if fig is None:
figManager = _pylab_helpers.Gcf.get_active()
if figManager is None:
return
else:
_pylab_helpers.Gcf.destroy(figManager.num)
elif fig == 'all':
_pylab_helpers.Gcf.destroy_all()
elif isinstance(fig, int):
_pylab_helpers.Gcf.destroy(fig)
elif hasattr(fig, 'int'):
# if we are dealing with a type UUID, we
# can use its integer representation
_pylab_helpers.Gcf.destroy(fig.int)
elif isinstance(fig, str):
allLabels = get_figlabels()
if fig in allLabels:
num = get_fignums()[allLabels.index(fig)]
_pylab_helpers.Gcf.destroy(num)
elif isinstance(fig, Figure):
_pylab_helpers.Gcf.destroy_fig(fig)
else:
raise TypeError("close() argument must be a Figure, an int, a string, "
"or None, not '%s'")
def clf():
"""Clear the current figure."""
gcf().clf()
def draw():
"""Redraw the current figure.
This is used to update a figure that has been altered, but not
automatically re-drawn. If interactive mode is on (:func:`.ion()`), this
should be only rarely needed, but there may be ways to modify the state of
a figure without marking it as `stale`. Please report these cases as
bugs.
A more object-oriented alternative, given any
:class:`~matplotlib.figure.Figure` instance, :attr:`fig`, that
was created using a :mod:`~matplotlib.pyplot` function, is::
fig.canvas.draw_idle()
"""
get_current_fig_manager().canvas.draw_idle()
@docstring.copy(Figure.savefig)
def savefig(*args, **kwargs):
fig = gcf()
res = fig.savefig(*args, **kwargs)
fig.canvas.draw_idle() # need this if 'transparent=True' to reset colors
return res
## Putting things in figures ##
def figlegend(*args, **kwargs):
return gcf().legend(*args, **kwargs)
if Figure.legend.__doc__:
figlegend.__doc__ = Figure.legend.__doc__.replace("legend(", "figlegend(")
## Axes ##
@docstring.dedent_interpd
def axes(arg=None, **kwargs):
"""
Add an axes to the current figure and make it the current axes.
Call signatures::
plt.axes()
plt.axes(rect, projection=None, polar=False, **kwargs)
plt.axes(ax)
Parameters
----------
arg : { None, 4-tuple, Axes }
The exact behavior of this function depends on the type:
- *None*: A new full window axes is added using
``subplot(111, **kwargs)``
- 4-tuple of floats *rect* = ``[left, bottom, width, height]``.
A new axes is added with dimensions *rect* in normalized
(0, 1) units using `~.Figure.add_axes` on the current figure.
- `~.axes.Axes`: This is equivalent to `.pyplot.sca`.
It sets the current axes to *arg*. Note: This implicitly
changes the current figure to the parent of *arg*.
.. note:: The use of an `.axes.Axes` as an argument is deprecated
and will be removed in v3.0. Please use `.pyplot.sca`
instead.
projection : {None, 'aitoff', 'hammer', 'lambert', 'mollweide', \
'polar', 'rectilinear', str}, optional
The projection type of the `~.axes.Axes`. *str* is the name of
a costum projection, see `~matplotlib.projections`. The default
None results in a 'rectilinear' projection.
polar : boolean, optional
If True, equivalent to projection='polar'.
sharex, sharey : `~.axes.Axes`, optional
Share the x or y `~matplotlib.axis` with sharex and/or sharey.
The axis will have the same limits, ticks, and scale as the axis
of the shared axes.
label : str
A label for the returned axes.
Other Parameters
----------------
**kwargs
This method also takes the keyword arguments for
the returned axes class. The keyword arguments for the
rectilinear axes class `~.axes.Axes` can be found in
the following table but there might also be other keyword
arguments if another projection is used, see the actual axes
class.
%(Axes)s
Returns
-------
axes : `~.axes.Axes` (or a subclass of `~.axes.Axes`)
The returned axes class depends on the projection used. It is
`~.axes.Axes` if rectilinear projection are used and
`.projections.polar.PolarAxes` if polar projection
are used.
Notes
-----
If the figure already has a axes with key (*args*,
*kwargs*) then it will simply make that axes current and
return it. This behavior is deprecated. Meanwhile, if you do
not want this behavior (i.e., you want to force the creation of a
new axes), you must use a unique set of args and kwargs. The axes
*label* attribute has been exposed for this purpose: if you want
two axes that are otherwise identical to be added to the figure,
make sure you give them unique labels.
See Also
--------
.Figure.add_axes
.pyplot.subplot
.Figure.add_subplot
.Figure.subplots
.pyplot.subplots
Examples
--------
::
# Creating a new full window axes
plt.axes()
# Creating a new axes with specified dimensions and some kwargs
plt.axes((left, bottom, width, height), facecolor='w')
"""
if arg is None:
return subplot(111, **kwargs)
else:
return gcf().add_axes(arg, **kwargs)
def delaxes(ax=None):
"""
Remove the `Axes` *ax* (defaulting to the current axes) from its figure.
A KeyError is raised if the axes doesn't exist.
"""
if ax is None:
ax = gca()
ax.figure.delaxes(ax)
def sca(ax):
"""
Set the current Axes instance to *ax*.
The current Figure is updated to the parent of *ax*.
"""
managers = _pylab_helpers.Gcf.get_all_fig_managers()
for m in managers:
if ax in m.canvas.figure.axes:
_pylab_helpers.Gcf.set_active(m)
m.canvas.figure.sca(ax)
return
raise ValueError("Axes instance argument was not found in a figure")
def gca(**kwargs):
"""
Get the current :class:`~matplotlib.axes.Axes` instance on the
current figure matching the given keyword args, or create one.
Examples
--------
To get the current polar axes on the current figure::
plt.gca(projection='polar')
If the current axes doesn't exist, or isn't a polar one, the appropriate
axes will be created and then returned.
See Also
--------
matplotlib.figure.Figure.gca : The figure's gca method.
"""
return gcf().gca(**kwargs)
## More ways of creating axes ##
@docstring.dedent_interpd
def subplot(*args, **kwargs):
"""
Add a subplot to the current figure.
Wrapper of `.Figure.add_subplot` with a difference in behavior
explained in the notes section.
Call signatures::
subplot(nrows, ncols, index, **kwargs)
subplot(pos, **kwargs)
subplot(ax)
Parameters
----------
*args
Either a 3-digit integer or three separate integers
describing the position of the subplot. If the three
integers are *nrows*, *ncols*, and *index* in order, the
subplot will take the *index* position on a grid with *nrows*
rows and *ncols* columns. *index* starts at 1 in the upper left
corner and increases to the right.
*pos* is a three digit integer, where the first digit is the
number of rows, the second the number of columns, and the third
the index of the subplot. i.e. fig.add_subplot(235) is the same as
fig.add_subplot(2, 3, 5). Note that all integers must be less than
10 for this form to work.
projection : {None, 'aitoff', 'hammer', 'lambert', 'mollweide', \
'polar', 'rectilinear', str}, optional
The projection type of the subplot (`~.axes.Axes`). *str* is the name
of a costum projection, see `~matplotlib.projections`. The default
None results in a 'rectilinear' projection.
polar : boolean, optional
If True, equivalent to projection='polar'.
sharex, sharey : `~.axes.Axes`, optional
Share the x or y `~matplotlib.axis` with sharex and/or sharey. The
axis will have the same limits, ticks, and scale as the axis of the
shared axes.
label : str
A label for the returned axes.
Other Parameters
----------------
**kwargs
This method also takes the keyword arguments for
the returned axes base class. The keyword arguments for the
rectilinear base class `~.axes.Axes` can be found in
the following table but there might also be other keyword
arguments if another projection is used.
%(Axes)s
Returns
-------
axes : an `.axes.SubplotBase` subclass of `~.axes.Axes` (or a subclass \
of `~.axes.Axes`)
The axes of the subplot. The returned axes base class depends on
the projection used. It is `~.axes.Axes` if rectilinear projection
are used and `.projections.polar.PolarAxes` if polar projection
are used. The returned axes is then a subplot subclass of the
base class.
Notes
-----
Creating a subplot will delete any pre-existing subplot that overlaps
with it beyond sharing a boundary::
import matplotlib.pyplot as plt
# plot a line, implicitly creating a subplot(111)
plt.plot([1,2,3])
# now create a subplot which represents the top plot of a grid
# with 2 rows and 1 column. Since this subplot will overlap the
# first, the plot (and its axes) previously created, will be removed
plt.subplot(211)
If you do not want this behavior, use the `.Figure.add_subplot` method
or the `.pyplot.axes` function instead.
If the figure already has a subplot with key (*args*,
*kwargs*) then it will simply make that subplot current and
return it. This behavior is deprecated. Meanwhile, if you do
not want this behavior (i.e., you want to force the creation of a
new subplot), you must use a unique set of args and kwargs. The axes
*label* attribute has been exposed for this purpose: if you want
two subplots that are otherwise identical to be added to the figure,
make sure you give them unique labels.
In rare circumstances, `.add_subplot` may be called with a single
argument, a subplot axes instance already created in the
present figure but not in the figure's list of axes.
See Also
--------
.Figure.add_subplot
.pyplot.subplots
.pyplot.axes
.Figure.subplots
Examples
--------
::
plt.subplot(221)
# equivalent but more general
ax1=plt.subplot(2, 2, 1)
# add a subplot with no frame
ax2=plt.subplot(222, frameon=False)
# add a polar subplot
plt.subplot(223, projection='polar')
# add a red subplot that shares the x-axis with ax1
plt.subplot(224, sharex=ax1, facecolor='red')
# delete ax2 from the figure
plt.delaxes(ax2)
# add ax2 to the figure again
plt.subplot(ax2)
"""
# if subplot called without arguments, create subplot(1,1,1)
if len(args) == 0:
args = (1, 1, 1)
# This check was added because it is very easy to type
# subplot(1, 2, False) when subplots(1, 2, False) was intended
# (sharex=False, that is). In most cases, no error will
# ever occur, but mysterious behavior can result because what was
# intended to be the sharex argument is instead treated as a
# subplot index for subplot()
if len(args) >= 3 and isinstance(args[2], bool):
cbook._warn_external("The subplot index argument to subplot() appears "
"to be a boolean. Did you intend to use "
"subplots()?")
fig = gcf()
a = fig.add_subplot(*args, **kwargs)
bbox = a.bbox
byebye = []
for other in fig.axes:
if other == a:
continue
if bbox.fully_overlaps(other.bbox):
byebye.append(other)
for ax in byebye:
delaxes(ax)
return a
def subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True,
subplot_kw=None, gridspec_kw=None, **fig_kw):
"""
Create a figure and a set of subplots.
This utility wrapper makes it convenient to create common layouts of
subplots, including the enclosing figure object, in a single call.
Parameters
----------
nrows, ncols : int, optional, default: 1
Number of rows/columns of the subplot grid.
sharex, sharey : bool or {'none', 'all', 'row', 'col'}, default: False
Controls sharing of properties among x (`sharex`) or y (`sharey`)
axes:
- True or 'all': x- or y-axis will be shared among all
subplots.
- False or 'none': each subplot x- or y-axis will be
independent.
- 'row': each subplot row will share an x- or y-axis.
- 'col': each subplot column will share an x- or y-axis.
When subplots have a shared x-axis along a column, only the x tick
labels of the bottom subplot are created. Similarly, when subplots
have a shared y-axis along a row, only the y tick labels of the first
column subplot are created. To later turn other subplots' ticklabels
on, use `~matplotlib.axes.Axes.tick_params`.
squeeze : bool, optional, default: True
- If True, extra dimensions are squeezed out from the returned
array of `~matplotlib.axes.Axes`:
- if only one subplot is constructed (nrows=ncols=1), the
resulting single Axes object is returned as a scalar.
- for Nx1 or 1xM subplots, the returned object is a 1D numpy
object array of Axes objects.
- for NxM, subplots with N>1 and M>1 are returned as a 2D array.
- If False, no squeezing at all is done: the returned Axes object is
always a 2D array containing Axes instances, even if it ends up
being 1x1.
num : integer or string, optional, default: None
A `.pyplot.figure` keyword that sets the figure number or label.
subplot_kw : dict, optional
Dict with keywords passed to the
`~matplotlib.figure.Figure.add_subplot` call used to create each
subplot.
gridspec_kw : dict, optional
Dict with keywords passed to the `~matplotlib.gridspec.GridSpec`
constructor used to create the grid the subplots are placed on.
**fig_kw
All additional keyword arguments are passed to the
`.pyplot.figure` call.
Returns
-------
fig : `~.figure.Figure`
ax : `.axes.Axes` object or array of Axes objects.
*ax* can be either a single `~matplotlib.axes.Axes` object or an
array of Axes objects if more than one subplot was created. The
dimensions of the resulting array can be controlled with the squeeze
keyword, see above.
Examples
--------
::
# First create some toy data:
x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)
# Creates just a figure and only one subplot
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_title('Simple plot')
# Creates two subplots and unpacks the output array immediately
f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
ax1.plot(x, y)
ax1.set_title('Sharing Y axis')
ax2.scatter(x, y)
# Creates four polar axes, and accesses them through the returned array
fig, axes = plt.subplots(2, 2, subplot_kw=dict(polar=True))
axes[0, 0].plot(x, y)
axes[1, 1].scatter(x, y)
# Share a X axis with each column of subplots
plt.subplots(2, 2, sharex='col')
# Share a Y axis with each row of subplots
plt.subplots(2, 2, sharey='row')
# Share both X and Y axes with all subplots
plt.subplots(2, 2, sharex='all', sharey='all')
# Note that this is the same as
plt.subplots(2, 2, sharex=True, sharey=True)
# Creates figure number 10 with a single subplot
# and clears it if it already exists.
fig, ax=plt.subplots(num=10, clear=True)
See Also
--------
.pyplot.figure
.pyplot.subplot
.pyplot.axes
.Figure.subplots
.Figure.add_subplot
"""
fig = figure(**fig_kw)
axs = fig.subplots(nrows=nrows, ncols=ncols, sharex=sharex, sharey=sharey,
squeeze=squeeze, subplot_kw=subplot_kw,
gridspec_kw=gridspec_kw)
return fig, axs
def subplot2grid(shape, loc, rowspan=1, colspan=1, fig=None, **kwargs):
"""
Create an axis at specific location inside a regular grid.
Parameters
----------
shape : sequence of 2 ints
Shape of grid in which to place axis.
First entry is number of rows, second entry is number of columns.
loc : sequence of 2 ints
Location to place axis within grid.
First entry is row number, second entry is column number.
rowspan : int
Number of rows for the axis to span to the right.
colspan : int
Number of columns for the axis to span downwards.
fig : `Figure`, optional
Figure to place axis in. Defaults to current figure.
**kwargs
Additional keyword arguments are handed to `add_subplot`.
Notes
-----
The following call ::
subplot2grid(shape, loc, rowspan=1, colspan=1)
is identical to ::
gridspec=GridSpec(shape[0], shape[1])
subplotspec=gridspec.new_subplotspec(loc, rowspan, colspan)
subplot(subplotspec)
"""
if fig is None:
fig = gcf()
s1, s2 = shape
subplotspec = GridSpec(s1, s2).new_subplotspec(loc,
rowspan=rowspan,
colspan=colspan)
a = fig.add_subplot(subplotspec, **kwargs)
bbox = a.bbox
byebye = []
for other in fig.axes:
if other == a:
continue
if bbox.fully_overlaps(other.bbox):
byebye.append(other)
for ax in byebye:
delaxes(ax)
return a
def twinx(ax=None):
"""
Make and return a second axes that shares the *x*-axis. The new axes will
overlay *ax* (or the current axes if *ax* is *None*), and its ticks will be
on the right.
Examples
--------
:doc:`/gallery/subplots_axes_and_figures/two_scales`
"""
if ax is None:
ax = gca()
ax1 = ax.twinx()
return ax1
def twiny(ax=None):
"""
Make and return a second axes that shares the *y*-axis. The new axes will
overlay *ax* (or the current axes if *ax* is *None*), and its ticks will be
on the top.
Examples
--------
:doc:`/gallery/subplots_axes_and_figures/two_scales`
"""
if ax is None:
ax = gca()
ax1 = ax.twiny()
return ax1
def subplots_adjust(left=None, bottom=None, right=None, top=None,
wspace=None, hspace=None):
"""
Tune the subplot layout.
The parameter meanings (and suggested defaults) are::
left = 0.125 # the left side of the subplots of the figure
right = 0.9 # the right side of the subplots of the figure
bottom = 0.1 # the bottom of the subplots of the figure
top = 0.9 # the top of the subplots of the figure
wspace = 0.2 # the amount of width reserved for space between subplots,
# expressed as a fraction of the average axis width
hspace = 0.2 # the amount of height reserved for space between subplots,
# expressed as a fraction of the average axis height
The actual defaults are controlled by the rc file
"""
fig = gcf()
fig.subplots_adjust(left, bottom, right, top, wspace, hspace)
def subplot_tool(targetfig=None):
"""
Launch a subplot tool window for a figure.
A :class:`matplotlib.widgets.SubplotTool` instance is returned.
"""
tbar = rcParams['toolbar'] # turn off navigation toolbar for the toolfig
rcParams['toolbar'] = 'None'
if targetfig is None:
manager = get_current_fig_manager()
targetfig = manager.canvas.figure
else:
# find the manager for this figure
for manager in _pylab_helpers.Gcf._activeQue:
if manager.canvas.figure == targetfig:
break
else:
raise RuntimeError('Could not find manager for targetfig')
toolfig = figure(figsize=(6, 3))
toolfig.subplots_adjust(top=0.9)
ret = SubplotTool(targetfig, toolfig)
rcParams['toolbar'] = tbar
_pylab_helpers.Gcf.set_active(manager) # restore the current figure
return ret
def tight_layout(pad=1.08, h_pad=None, w_pad=None, rect=None):
"""
Automatically adjust subplot parameters to give specified padding.
Parameters
----------
pad : float
Padding between the figure edge and the edges of subplots,
as a fraction of the font size.
h_pad, w_pad : float, optional
Padding (height/width) between edges of adjacent subplots,
as a fraction of the font size. Defaults to *pad*.
rect : tuple (left, bottom, right, top), optional
A rectangle (left, bottom, right, top) in the normalized
figure coordinate that the whole subplots area (including
labels) will fit into. Default is (0, 0, 1, 1).
"""
gcf().tight_layout(pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect)
def box(on=None):
"""
Turn the axes box on or off on the current axes.
Parameters
----------
on : bool or None
The new `~matplotlib.axes.Axes` box state. If ``None``, toggle
the state.
See Also
--------
:meth:`matplotlib.axes.Axes.set_frame_on`
:meth:`matplotlib.axes.Axes.get_frame_on`
"""
ax = gca()
if on is None:
on = not ax.get_frame_on()
ax.set_frame_on(on)
## Axis ##
def xlim(*args, **kwargs):
"""
Get or set the x limits of the current axes.
Call signatures::
left, right = xlim() # return the current xlim
xlim((left, right)) # set the xlim to left, right
xlim(left, right) # set the xlim to left, right
If you do not specify args, you can pass *left* or *right* as kwargs,
i.e.::
xlim(right=3) # adjust the right leaving left unchanged
xlim(left=1) # adjust the left leaving right unchanged
Setting limits turns autoscaling off for the x-axis.
Returns
-------
left, right
A tuple of the new x-axis limits.
Notes
-----
Calling this function with no arguments (e.g. ``xlim()``) is the pyplot
equivalent of calling `~.Axes.get_xlim` on the current axes.
Calling this function with arguments is the pyplot equivalent of calling
`~.Axes.set_xlim` on the current axes. All arguments are passed though.
"""
ax = gca()
if not args and not kwargs:
return ax.get_xlim()
ret = ax.set_xlim(*args, **kwargs)
return ret
def ylim(*args, **kwargs):
"""
Get or set the y-limits of the current axes.
Call signatures::
bottom, top = ylim() # return the current ylim
ylim((bottom, top)) # set the ylim to bottom, top
ylim(bottom, top) # set the ylim to bottom, top
If you do not specify args, you can alternatively pass *bottom* or
*top* as kwargs, i.e.::
ylim(top=3) # adjust the top leaving bottom unchanged
ylim(bottom=1) # adjust the bottom leaving top unchanged
Setting limits turns autoscaling off for the y-axis.
Returns
-------
bottom, top
A tuple of the new y-axis limits.
Notes
-----
Calling this function with no arguments (e.g. ``ylim()``) is the pyplot
equivalent of calling `~.Axes.get_ylim` on the current axes.
Calling this function with arguments is the pyplot equivalent of calling
`~.Axes.set_ylim` on the current axes. All arguments are passed though.
"""
ax = gca()
if not args and not kwargs:
return ax.get_ylim()
ret = ax.set_ylim(*args, **kwargs)
return ret
def xticks(ticks=None, labels=None, **kwargs):
"""
Get or set the current tick locations and labels of the x-axis.
Call signatures::
locs, labels = xticks() # Get locations and labels
xticks(ticks, [labels], **kwargs) # Set locations and labels
Parameters
----------
ticks : array_like
A list of positions at which ticks should be placed. You can pass an
empty list to disable xticks.
labels : array_like, optional
A list of explicit labels to place at the given *locs*.
**kwargs
:class:`.Text` properties can be used to control the appearance of
the labels.
Returns
-------
locs
An array of label locations.
labels
A list of `.Text` objects.
Notes
-----
Calling this function with no arguments (e.g. ``xticks()``) is the pyplot
equivalent of calling `~.Axes.get_xticks` and `~.Axes.get_xticklabels` on
the current axes.
Calling this function with arguments is the pyplot equivalent of calling
`~.Axes.set_xticks` and `~.Axes.set_xticklabels` on the current axes.
Examples
--------
Get the current locations and labels:
>>> locs, labels = xticks()
Set label locations:
>>> xticks(np.arange(0, 1, step=0.2))
Set text labels:
>>> xticks(np.arange(5), ('Tom', 'Dick', 'Harry', 'Sally', 'Sue'))
Set text labels and properties:
>>> xticks(np.arange(12), calendar.month_name[1:13], rotation=20)
Disable xticks:
>>> xticks([])
"""
ax = gca()
if ticks is None and labels is None:
locs = ax.get_xticks()
labels = ax.get_xticklabels()
elif labels is None:
locs = ax.set_xticks(ticks)
labels = ax.get_xticklabels()
else:
locs = ax.set_xticks(ticks)
labels = ax.set_xticklabels(labels, **kwargs)
for l in labels:
l.update(kwargs)
return locs, silent_list('Text xticklabel', labels)
def yticks(ticks=None, labels=None, **kwargs):
"""
Get or set the current tick locations and labels of the y-axis.
Call signatures::
locs, labels = yticks() # Get locations and labels
yticks(ticks, [labels], **kwargs) # Set locations and labels
Parameters
----------
ticks : array_like
A list of positions at which ticks should be placed. You can pass an
empty list to disable yticks.
labels : array_like, optional
A list of explicit labels to place at the given *locs*.
**kwargs
:class:`.Text` properties can be used to control the appearance of
the labels.
Returns
-------
locs
An array of label locations.
labels
A list of `.Text` objects.
Notes
-----
Calling this function with no arguments (e.g. ``yticks()``) is the pyplot
equivalent of calling `~.Axes.get_yticks` and `~.Axes.get_yticklabels` on
the current axes.
Calling this function with arguments is the pyplot equivalent of calling
`~.Axes.set_yticks` and `~.Axes.set_yticklabels` on the current axes.
Examples
--------
Get the current locations and labels:
>>> locs, labels = yticks()
Set label locations:
>>> yticks(np.arange(0, 1, step=0.2))
Set text labels:
>>> yticks(np.arange(5), ('Tom', 'Dick', 'Harry', 'Sally', 'Sue'))
Set text labels and properties:
>>> yticks(np.arange(12), calendar.month_name[1:13], rotation=45)
Disable yticks:
>>> yticks([])
"""
ax = gca()
if ticks is None and labels is None:
locs = ax.get_yticks()
labels = ax.get_yticklabels()
elif labels is None:
locs = ax.set_yticks(ticks)
labels = ax.get_yticklabels()
else:
locs = ax.set_yticks(ticks)
labels = ax.set_yticklabels(labels, **kwargs)
for l in labels:
l.update(kwargs)
return locs, silent_list('Text yticklabel', labels)
def rgrids(*args, **kwargs):
"""
Get or set the radial gridlines on the current polar plot.
Call signatures::
lines, labels = rgrids()
lines, labels = rgrids(radii, labels=None, angle=22.5, fmt=None, **kwargs)
When called with no arguments, `.rgrids` simply returns the tuple
(*lines*, *labels*). When called with arguments, the labels will
appear at the specified radial distances and angle.
Parameters
----------
radii : tuple with floats
The radii for the radial gridlines
labels : tuple with strings or None
The labels to use at each radial gridline. The
`matplotlib.ticker.ScalarFormatter` will be used if None.
angle : float
The angular position of the radius labels in degrees.
fmt : str or None
Format string used in `matplotlib.ticker.FormatStrFormatter`.
For example '%f'.
Returns
-------
lines, labels : list of `.lines.Line2D`, list of `.text.Text`
*lines* are the radial gridlines and *labels* are the tick labels.
Other Parameters
----------------
**kwargs
*kwargs* are optional `~.Text` properties for the labels.
Examples
--------
::
# set the locations of the radial gridlines
lines, labels = rgrids( (0.25, 0.5, 1.0) )
# set the locations and labels of the radial gridlines
lines, labels = rgrids( (0.25, 0.5, 1.0), ('Tom', 'Dick', 'Harry' ))
See Also
--------
.pyplot.thetagrids
.projections.polar.PolarAxes.set_rgrids
.Axis.get_gridlines
.Axis.get_ticklabels
"""
ax = gca()
if not isinstance(ax, PolarAxes):
raise RuntimeError('rgrids only defined for polar axes')
if len(args) == 0:
lines = ax.yaxis.get_gridlines()
labels = ax.yaxis.get_ticklabels()
else:
lines, labels = ax.set_rgrids(*args, **kwargs)
return (silent_list('Line2D rgridline', lines),
silent_list('Text rgridlabel', labels))
def thetagrids(*args, **kwargs):
"""
Get or set the theta gridlines on the current polar plot.
Call signatures::
lines, labels = thetagrids()
lines, labels = thetagrids(angles, labels=None, fmt=None, **kwargs)
When called with no arguments, `.thetagrids` simply returns the tuple
(*lines*, *labels*). When called with arguments, the labels will
appear at the specified angles.
Parameters
----------
angles : tuple with floats, degrees
The angles of the theta gridlines.
labels : tuple with strings or None
The labels to use at each radial gridline. The
`.projections.polar.ThetaFormatter` will be used if None.
fmt : str or None
Format string used in `matplotlib.ticker.FormatStrFormatter`.
For example '%f'. Note that the angle in radians will be used.
Returns
-------
lines, labels : list of `.lines.Line2D`, list of `.text.Text`
*lines* are the theta gridlines and *labels* are the tick labels.
Other Parameters
----------------
**kwargs
*kwargs* are optional `~.Text` properties for the labels.
Examples
--------
::
# set the locations of the angular gridlines
lines, labels = thetagrids( range(45,360,90) )
# set the locations and labels of the angular gridlines
lines, labels = thetagrids( range(45,360,90), ('NE', 'NW', 'SW','SE') )
See Also
--------
.pyplot.rgrids
.projections.polar.PolarAxes.set_thetagrids
.Axis.get_gridlines
.Axis.get_ticklabels
"""
ax = gca()
if not isinstance(ax, PolarAxes):
raise RuntimeError('thetagrids only defined for polar axes')
if len(args) == 0:
lines = ax.xaxis.get_ticklines()
labels = ax.xaxis.get_ticklabels()
else:
lines, labels = ax.set_thetagrids(*args, **kwargs)
return (silent_list('Line2D thetagridline', lines),
silent_list('Text thetagridlabel', labels))
## Plotting Info ##
def plotting():
pass
def get_plot_commands():
"""
Get a sorted list of all of the plotting commands.
"""
# This works by searching for all functions in this module and removing
# a few hard-coded exclusions, as well as all of the colormap-setting
# functions, and anything marked as private with a preceding underscore.
exclude = {'colormaps', 'colors', 'connect', 'disconnect',
'get_plot_commands', 'get_current_fig_manager', 'ginput',
'plotting', 'waitforbuttonpress'}
exclude |= set(colormaps())
this_module = inspect.getmodule(get_plot_commands)
return sorted(
name for name, obj in globals().items()
if not name.startswith('_') and name not in exclude
and inspect.isfunction(obj)
and inspect.getmodule(obj) is this_module)
def colormaps():
"""
Matplotlib provides a number of colormaps, and others can be added using
:func:`~matplotlib.cm.register_cmap`. This function documents the built-in
colormaps, and will also return a list of all registered colormaps if
called.
You can set the colormap for an image, pcolor, scatter, etc,
using a keyword argument::
imshow(X, cmap=cm.hot)
or using the :func:`set_cmap` function::
imshow(X)
pyplot.set_cmap('hot')
pyplot.set_cmap('jet')
In interactive mode, :func:`set_cmap` will update the colormap post-hoc,
allowing you to see which one works best for your data.
All built-in colormaps can be reversed by appending ``_r``: For instance,
``gray_r`` is the reverse of ``gray``.
There are several common color schemes used in visualization:
Sequential schemes
for unipolar data that progresses from low to high
Diverging schemes
for bipolar data that emphasizes positive or negative deviations from a
central value
Cyclic schemes
for plotting values that wrap around at the endpoints, such as phase
angle, wind direction, or time of day
Qualitative schemes
for nominal data that has no inherent ordering, where color is used
only to distinguish categories
Matplotlib ships with 4 perceptually uniform color maps which are
the recommended color maps for sequential data:
========= ===================================================
Colormap Description
========= ===================================================
inferno perceptually uniform shades of black-red-yellow
magma perceptually uniform shades of black-red-white
plasma perceptually uniform shades of blue-red-yellow
viridis perceptually uniform shades of blue-green-yellow
========= ===================================================
The following colormaps are based on the `ColorBrewer
<http://colorbrewer2.org>`_ color specifications and designs developed by
Cynthia Brewer:
ColorBrewer Diverging (luminance is highest at the midpoint, and
decreases towards differently-colored endpoints):
======== ===================================
Colormap Description
======== ===================================
BrBG brown, white, blue-green
PiYG pink, white, yellow-green
PRGn purple, white, green
PuOr orange, white, purple
RdBu red, white, blue
RdGy red, white, gray
RdYlBu red, yellow, blue
RdYlGn red, yellow, green
Spectral red, orange, yellow, green, blue
======== ===================================
ColorBrewer Sequential (luminance decreases monotonically):
======== ====================================
Colormap Description
======== ====================================
Blues white to dark blue
BuGn white, light blue, dark green
BuPu white, light blue, dark purple
GnBu white, light green, dark blue
Greens white to dark green
Greys white to black (not linear)
Oranges white, orange, dark brown
OrRd white, orange, dark red
PuBu white, light purple, dark blue
PuBuGn white, light purple, dark green
PuRd white, light purple, dark red
Purples white to dark purple
RdPu white, pink, dark purple
Reds white to dark red
YlGn light yellow, dark green
YlGnBu light yellow, light green, dark blue
YlOrBr light yellow, orange, dark brown
YlOrRd light yellow, orange, dark red
======== ====================================
ColorBrewer Qualitative:
(For plotting nominal data, :class:`ListedColormap` is used,
not :class:`LinearSegmentedColormap`. Different sets of colors are
recommended for different numbers of categories.)
* Accent
* Dark2
* Paired
* Pastel1
* Pastel2
* Set1
* Set2
* Set3
A set of colormaps derived from those of the same name provided
with Matlab are also included:
========= =======================================================
Colormap Description
========= =======================================================
autumn sequential linearly-increasing shades of red-orange-yellow
bone sequential increasing black-white color map with
a tinge of blue, to emulate X-ray film
cool linearly-decreasing shades of cyan-magenta
copper sequential increasing shades of black-copper
flag repetitive red-white-blue-black pattern (not cyclic at
endpoints)
gray sequential linearly-increasing black-to-white
grayscale
hot sequential black-red-yellow-white, to emulate blackbody
radiation from an object at increasing temperatures
jet a spectral map with dark endpoints, blue-cyan-yellow-red;
based on a fluid-jet simulation by NCSA [#]_
pink sequential increasing pastel black-pink-white, meant
for sepia tone colorization of photographs
prism repetitive red-yellow-green-blue-purple-...-green pattern
(not cyclic at endpoints)
spring linearly-increasing shades of magenta-yellow
summer sequential linearly-increasing shades of green-yellow
winter linearly-increasing shades of blue-green
========= =======================================================
A set of palettes from the `Yorick scientific visualisation
package <https://dhmunro.github.io/yorick-doc/>`_, an evolution of
the GIST package, both by David H. Munro are included:
============ =======================================================
Colormap Description
============ =======================================================
gist_earth mapmaker's colors from dark blue deep ocean to green
lowlands to brown highlands to white mountains
gist_heat sequential increasing black-red-orange-white, to emulate
blackbody radiation from an iron bar as it grows hotter
gist_ncar pseudo-spectral black-blue-green-yellow-red-purple-white
colormap from National Center for Atmospheric
Research [#]_
gist_rainbow runs through the colors in spectral order from red to
violet at full saturation (like *hsv* but not cyclic)
gist_stern "Stern special" color table from Interactive Data
Language software
============ =======================================================
A set of cyclic color maps:
================ =================================================
Colormap Description
================ =================================================
hsv red-yellow-green-cyan-blue-magenta-red, formed by
changing the hue component in the HSV color space
twilight perceptually uniform shades of
white-blue-black-red-white
twilight_shifted perceptually uniform shades of
black-blue-white-red-black
================ =================================================
Other miscellaneous schemes:
============= =======================================================
Colormap Description
============= =======================================================
afmhot sequential black-orange-yellow-white blackbody
spectrum, commonly used in atomic force microscopy
brg blue-red-green
bwr diverging blue-white-red
coolwarm diverging blue-gray-red, meant to avoid issues with 3D
shading, color blindness, and ordering of colors [#]_
CMRmap "Default colormaps on color images often reproduce to
confusing grayscale images. The proposed colormap
maintains an aesthetically pleasing color image that
automatically reproduces to a monotonic grayscale with
discrete, quantifiable saturation levels." [#]_
cubehelix Unlike most other color schemes cubehelix was designed
by D.A. Green to be monotonically increasing in terms
of perceived brightness. Also, when printed on a black
and white postscript printer, the scheme results in a
greyscale with monotonically increasing brightness.
This color scheme is named cubehelix because the r,g,b
values produced can be visualised as a squashed helix
around the diagonal in the r,g,b color cube.
gnuplot gnuplot's traditional pm3d scheme
(black-blue-red-yellow)
gnuplot2 sequential color printable as gray
(black-blue-violet-yellow-white)
ocean green-blue-white
rainbow spectral purple-blue-green-yellow-orange-red colormap
with diverging luminance
seismic diverging blue-white-red
nipy_spectral black-purple-blue-green-yellow-red-white spectrum,
originally from the Neuroimaging in Python project
terrain mapmaker's colors, blue-green-yellow-brown-white,
originally from IGOR Pro
============= =======================================================
The following colormaps are redundant and may be removed in future
versions. It's recommended to use the names in the descriptions
instead, which produce identical output:
========= =======================================================
Colormap Description
========= =======================================================
gist_gray identical to *gray*
gist_yarg identical to *gray_r*
binary identical to *gray_r*
========= =======================================================
.. rubric:: Footnotes
.. [#] Rainbow colormaps, ``jet`` in particular, are considered a poor
choice for scientific visualization by many researchers: `Rainbow Color
Map (Still) Considered Harmful
<http://ieeexplore.ieee.org/document/4118486/?arnumber=4118486>`_
.. [#] Resembles "BkBlAqGrYeOrReViWh200" from NCAR Command
Language. See `Color Table Gallery
<https://www.ncl.ucar.edu/Document/Graphics/color_table_gallery.shtml>`_
.. [#] See `Diverging Color Maps for Scientific Visualization
<http://www.kennethmoreland.com/color-maps/>`_ by Kenneth Moreland.
.. [#] See `A Color Map for Effective Black-and-White Rendering of
Color-Scale Images
<https://www.mathworks.com/matlabcentral/fileexchange/2662-cmrmap-m>`_
by Carey Rappaport
"""
return sorted(cm.cmap_d)
def _setup_pyplot_info_docstrings():
"""
Generates the plotting docstring.
These must be done after the entire module is imported, so it is
called from the end of this module, which is generated by
boilerplate.py.
"""
commands = get_plot_commands()
first_sentence = re.compile(r"(?:\s*).+?\.(?:\s+|$)", flags=re.DOTALL)
# Collect the first sentence of the docstring for all of the
# plotting commands.
rows = []
max_name = len("Function")
max_summary = len("Description")
for name in commands:
doc = globals()[name].__doc__
summary = ''
if doc is not None:
match = first_sentence.match(doc)
if match is not None:
summary = inspect.cleandoc(match.group(0)).replace('\n', ' ')
name = '`%s`' % name
rows.append([name, summary])
max_name = max(max_name, len(name))
max_summary = max(max_summary, len(summary))
separator = '=' * max_name + ' ' + '=' * max_summary
lines = [
separator,
'{:{}} {:{}}'.format('Function', max_name, 'Description', max_summary),
separator,
] + [
'{:{}} {:{}}'.format(name, max_name, summary, max_summary)
for name, summary in rows
] + [
separator,
]
plotting.__doc__ = '\n'.join(lines)
## Plotting part 1: manually generated functions and wrappers ##
def colorbar(mappable=None, cax=None, ax=None, **kw):
if mappable is None:
mappable = gci()
if mappable is None:
raise RuntimeError('No mappable was found to use for colorbar '
'creation. First define a mappable such as '
'an image (with imshow) or a contour set ('
'with contourf).')
if ax is None:
ax = gca()
ret = gcf().colorbar(mappable, cax=cax, ax=ax, **kw)
return ret
colorbar.__doc__ = matplotlib.colorbar.colorbar_doc
def clim(vmin=None, vmax=None):
"""
Set the color limits of the current image.
To apply clim to all axes images do::
clim(0, 0.5)
If either *vmin* or *vmax* is None, the image min/max respectively
will be used for color scaling.
If you want to set the clim of multiple images,
use, for example::
for im in gca().get_images():
im.set_clim(0, 0.05)
"""
im = gci()
if im is None:
raise RuntimeError('You must first define an image, e.g., with imshow')
im.set_clim(vmin, vmax)
def set_cmap(cmap):
"""
Set the default colormap. Applies to the current image if any.
See help(colormaps) for more information.
*cmap* must be a :class:`~matplotlib.colors.Colormap` instance, or
the name of a registered colormap.
See :func:`matplotlib.cm.register_cmap` and
:func:`matplotlib.cm.get_cmap`.
"""
cmap = cm.get_cmap(cmap)
rc('image', cmap=cmap.name)
im = gci()
if im is not None:
im.set_cmap(cmap)
@docstring.copy(matplotlib.image.imread)
def imread(fname, format=None):
return matplotlib.image.imread(fname, format)
@docstring.copy(matplotlib.image.imsave)
def imsave(fname, arr, **kwargs):
return matplotlib.image.imsave(fname, arr, **kwargs)
def matshow(A, fignum=None, **kwargs):
"""
Display an array as a matrix in a new figure window.
The origin is set at the upper left hand corner and rows (first
dimension of the array) are displayed horizontally. The aspect
ratio of the figure window is that of the array, unless this would
make an excessively short or narrow figure.
Tick labels for the xaxis are placed on top.
Parameters
----------
A : array-like(M, N)
The matrix to be displayed.
fignum : None or int or False
If *None*, create a new figure window with automatic numbering.
If a nonzero integer, draw into the figure with the given number
(create it if it does not exist).
If 0, use the current axes (or create one if it does not exist).
.. note::
Because of how `.Axes.matshow` tries to set the figure aspect
ratio to be the one of the array, strange things may happen if you
reuse an existing figure.
Returns
-------
image : `~matplotlib.image.AxesImage`
Other Parameters
----------------
**kwargs : `~matplotlib.axes.Axes.imshow` arguments
"""
A = np.asanyarray(A)
if fignum == 0:
ax = gca()
else:
# Extract actual aspect ratio of array and make appropriately sized
# figure.
fig = figure(fignum, figsize=figaspect(A))
ax = fig.add_axes([0.15, 0.09, 0.775, 0.775])
im = ax.matshow(A, **kwargs)
sci(im)
return im
def polar(*args, **kwargs):
"""
Make a polar plot.
call signature::
polar(theta, r, **kwargs)
Multiple *theta*, *r* arguments are supported, with format
strings, as in :func:`~matplotlib.pyplot.plot`.
"""
# If an axis already exists, check if it has a polar projection
if gcf().get_axes():
if not isinstance(gca(), PolarAxes):
cbook._warn_external('Trying to create polar plot on an axis '
'that does not have a polar projection.')
ax = gca(polar=True)
ret = ax.plot(*args, **kwargs)
return ret
def plotfile(fname, cols=(0,), plotfuncs=None,
comments='#', skiprows=0, checkrows=5, delimiter=',',
names=None, subplots=True, newfig=True, **kwargs):
"""
Plot the data in a file.
*cols* is a sequence of column identifiers to plot. An identifier
is either an int or a string. If it is an int, it indicates the
column number. If it is a string, it indicates the column header.
matplotlib will make column headers lower case, replace spaces with
underscores, and remove all illegal characters; so ``'Adj Close*'``
will have name ``'adj_close'``.
- If len(*cols*) == 1, only that column will be plotted on the *y* axis.
- If len(*cols*) > 1, the first element will be an identifier for
data for the *x* axis and the remaining elements will be the
column indexes for multiple subplots if *subplots* is *True*
(the default), or for lines in a single subplot if *subplots*
is *False*.
*plotfuncs*, if not *None*, is a dictionary mapping identifier to
an :class:`~matplotlib.axes.Axes` plotting function as a string.
Default is 'plot', other choices are 'semilogy', 'fill', 'bar',
etc. You must use the same type of identifier in the *cols*
vector as you use in the *plotfuncs* dictionary, e.g., integer
column numbers in both or column names in both. If *subplots*
is *False*, then including any function such as 'semilogy'
that changes the axis scaling will set the scaling for all
columns.
- *comments*: the character used to indicate the start of a comment
in the file, or *None* to switch off the removal of comments
- *skiprows*: is the number of rows from the top to skip
- *checkrows*: is the number of rows to check to validate the column
data type. When set to zero all rows are validated.
- *delimiter*: is the character(s) separating row items
- *names*: if not None, is a list of header names. In this case, no
header will be read from the file
If *newfig* is *True*, the plot always will be made in a new figure;
if *False*, it will be made in the current figure if one exists,
else in a new figure.
kwargs are passed on to plotting functions.
Example usage::
# plot the 2nd and 4th column against the 1st in two subplots
plotfile(fname, (0,1,3))
# plot using column names; specify an alternate plot type for volume
plotfile(fname, ('date', 'volume', 'adj_close'),
plotfuncs={'volume': 'semilogy'})
Note: plotfile is intended as a convenience for quickly plotting
data from flat files; it is not intended as an alternative
interface to general plotting with pyplot or matplotlib.
"""
if newfig:
fig = figure()
else:
fig = gcf()
if len(cols) < 1:
raise ValueError('must have at least one column of data')
if plotfuncs is None:
plotfuncs = {}
with cbook._suppress_matplotlib_deprecation_warning():
r = mlab._csv2rec(fname, comments=comments, skiprows=skiprows,
checkrows=checkrows, delimiter=delimiter,
names=names)
def getname_val(identifier):
'return the name and column data for identifier'
if isinstance(identifier, str):
return identifier, r[identifier]
elif isinstance(identifier, Number):
name = r.dtype.names[int(identifier)]
return name, r[name]
else:
raise TypeError('identifier must be a string or integer')
xname, x = getname_val(cols[0])
ynamelist = []
if len(cols) == 1:
ax1 = fig.add_subplot(1, 1, 1)
funcname = plotfuncs.get(cols[0], 'plot')
func = getattr(ax1, funcname)
func(x, **kwargs)
ax1.set_ylabel(xname)
else:
N = len(cols)
for i in range(1, N):
if subplots:
if i == 1:
ax = ax1 = fig.add_subplot(N - 1, 1, i)
else:
ax = fig.add_subplot(N - 1, 1, i, sharex=ax1)
elif i == 1:
ax = fig.add_subplot(1, 1, 1)
yname, y = getname_val(cols[i])
ynamelist.append(yname)
funcname = plotfuncs.get(cols[i], 'plot')
func = getattr(ax, funcname)
func(x, y, **kwargs)
if subplots:
ax.set_ylabel(yname)
if ax.is_last_row():
ax.set_xlabel(xname)
else:
ax.set_xlabel('')
if not subplots:
ax.legend(ynamelist)
if xname == 'date':
fig.autofmt_xdate()
# If rcParams['backend_fallback'] is true, and an interactive backend is
# requested, ignore rcParams['backend'] and force selection of a backend that
# is compatible with the current running interactive framework.
if (rcParams["backend_fallback"]
and dict.__getitem__(rcParams, "backend") in _interactive_bk
and _get_running_interactive_framework()):
dict.__setitem__(rcParams, "backend", rcsetup._auto_backend_sentinel)
# Set up the backend.
switch_backend(rcParams["backend"])
# Just to be safe. Interactive mode can be turned on without
# calling `plt.ion()` so register it again here.
# This is safe because multiple calls to `install_repl_displayhook`
# are no-ops and the registered function respect `mpl.is_interactive()`
# to determine if they should trigger a draw.
install_repl_displayhook()
################# REMAINING CONTENT GENERATED BY boilerplate.py ##############
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Figure.figimage)
def figimage(
X, xo=0, yo=0, alpha=None, norm=None, cmap=None, vmin=None,
vmax=None, origin=None, resize=False, **kwargs):
return gcf().figimage(
X, xo=xo, yo=yo, alpha=alpha, norm=norm, cmap=cmap, vmin=vmin,
vmax=vmax, origin=origin, resize=resize, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Figure.text)
def figtext(
x, y, s, fontdict=None,
withdash=cbook.deprecation._deprecated_parameter, **kwargs):
return gcf().text(
x, y, s, fontdict=fontdict, withdash=withdash, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Figure.ginput)
def ginput(
n=1, timeout=30, show_clicks=True, mouse_add=1, mouse_pop=3,
mouse_stop=2):
return gcf().ginput(
n=n, timeout=timeout, show_clicks=show_clicks,
mouse_add=mouse_add, mouse_pop=mouse_pop,
mouse_stop=mouse_stop)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Figure.suptitle)
def suptitle(t, **kwargs):
return gcf().suptitle(t, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Figure.waitforbuttonpress)
def waitforbuttonpress(timeout=-1):
return gcf().waitforbuttonpress(timeout=timeout)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.acorr)
def acorr(x, *, data=None, **kwargs):
return gca().acorr(
x, **({"data": data} if data is not None else {}), **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.angle_spectrum)
def angle_spectrum(
x, Fs=None, Fc=None, window=None, pad_to=None, sides=None, *,
data=None, **kwargs):
return gca().angle_spectrum(
x, Fs=Fs, Fc=Fc, window=window, pad_to=pad_to, sides=sides,
**({"data": data} if data is not None else {}), **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.annotate)
def annotate(s, xy, *args, **kwargs):
return gca().annotate(s, xy, *args, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.arrow)
def arrow(x, y, dx, dy, **kwargs):
return gca().arrow(x, y, dx, dy, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.autoscale)
def autoscale(enable=True, axis='both', tight=None):
return gca().autoscale(enable=enable, axis=axis, tight=tight)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.axhline)
def axhline(y=0, xmin=0, xmax=1, **kwargs):
return gca().axhline(y=y, xmin=xmin, xmax=xmax, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.axhspan)
def axhspan(ymin, ymax, xmin=0, xmax=1, **kwargs):
return gca().axhspan(ymin, ymax, xmin=xmin, xmax=xmax, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.axis)
def axis(*args, **kwargs):
return gca().axis(*args, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.axvline)
def axvline(x=0, ymin=0, ymax=1, **kwargs):
return gca().axvline(x=x, ymin=ymin, ymax=ymax, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.axvspan)
def axvspan(xmin, xmax, ymin=0, ymax=1, **kwargs):
return gca().axvspan(xmin, xmax, ymin=ymin, ymax=ymax, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.bar)
def bar(
x, height, width=0.8, bottom=None, *, align='center',
data=None, **kwargs):
return gca().bar(
x, height, width=width, bottom=bottom, align=align,
**({"data": data} if data is not None else {}), **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.barbs)
def barbs(*args, data=None, **kw):
return gca().barbs(
*args, **({"data": data} if data is not None else {}), **kw)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.barh)
def barh(y, width, height=0.8, left=None, *, align='center', **kwargs):
return gca().barh(
y, width, height=height, left=left, align=align, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.boxplot)
def boxplot(
x, notch=None, sym=None, vert=None, whis=None,
positions=None, widths=None, patch_artist=None,
bootstrap=None, usermedians=None, conf_intervals=None,
meanline=None, showmeans=None, showcaps=None, showbox=None,
showfliers=None, boxprops=None, labels=None, flierprops=None,
medianprops=None, meanprops=None, capprops=None,
whiskerprops=None, manage_ticks=True, autorange=False,
zorder=None, *, data=None):
return gca().boxplot(
x, notch=notch, sym=sym, vert=vert, whis=whis,
positions=positions, widths=widths, patch_artist=patch_artist,
bootstrap=bootstrap, usermedians=usermedians,
conf_intervals=conf_intervals, meanline=meanline,
showmeans=showmeans, showcaps=showcaps, showbox=showbox,
showfliers=showfliers, boxprops=boxprops, labels=labels,
flierprops=flierprops, medianprops=medianprops,
meanprops=meanprops, capprops=capprops,
whiskerprops=whiskerprops, manage_ticks=manage_ticks,
autorange=autorange, zorder=zorder, **({"data": data} if data
is not None else {}))
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.broken_barh)
def broken_barh(xranges, yrange, *, data=None, **kwargs):
return gca().broken_barh(
xranges, yrange, **({"data": data} if data is not None else
{}), **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.cla)
def cla():
return gca().cla()
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.clabel)
def clabel(CS, *args, **kwargs):
return gca().clabel(CS, *args, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.cohere)
def cohere(
x, y, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none,
window=mlab.window_hanning, noverlap=0, pad_to=None,
sides='default', scale_by_freq=None, *, data=None, **kwargs):
return gca().cohere(
x, y, NFFT=NFFT, Fs=Fs, Fc=Fc, detrend=detrend, window=window,
noverlap=noverlap, pad_to=pad_to, sides=sides,
scale_by_freq=scale_by_freq, **({"data": data} if data is not
None else {}), **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.contour)
def contour(*args, data=None, **kwargs):
__ret = gca().contour(
*args, **({"data": data} if data is not None else {}),
**kwargs)
if __ret._A is not None: sci(__ret) # noqa
return __ret
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.contourf)
def contourf(*args, data=None, **kwargs):
__ret = gca().contourf(
*args, **({"data": data} if data is not None else {}),
**kwargs)
if __ret._A is not None: sci(__ret) # noqa
return __ret
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.csd)
def csd(
x, y, NFFT=None, Fs=None, Fc=None, detrend=None, window=None,
noverlap=None, pad_to=None, sides=None, scale_by_freq=None,
return_line=None, *, data=None, **kwargs):
return gca().csd(
x, y, NFFT=NFFT, Fs=Fs, Fc=Fc, detrend=detrend, window=window,
noverlap=noverlap, pad_to=pad_to, sides=sides,
scale_by_freq=scale_by_freq, return_line=return_line,
**({"data": data} if data is not None else {}), **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.errorbar)
def errorbar(
x, y, yerr=None, xerr=None, fmt='', ecolor=None,
elinewidth=None, capsize=None, barsabove=False, lolims=False,
uplims=False, xlolims=False, xuplims=False, errorevery=1,
capthick=None, *, data=None, **kwargs):
return gca().errorbar(
x, y, yerr=yerr, xerr=xerr, fmt=fmt, ecolor=ecolor,
elinewidth=elinewidth, capsize=capsize, barsabove=barsabove,
lolims=lolims, uplims=uplims, xlolims=xlolims,
xuplims=xuplims, errorevery=errorevery, capthick=capthick,
**({"data": data} if data is not None else {}), **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.eventplot)
def eventplot(
positions, orientation='horizontal', lineoffsets=1,
linelengths=1, linewidths=None, colors=None,
linestyles='solid', *, data=None, **kwargs):
return gca().eventplot(
positions, orientation=orientation, lineoffsets=lineoffsets,
linelengths=linelengths, linewidths=linewidths, colors=colors,
linestyles=linestyles, **({"data": data} if data is not None
else {}), **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.fill)
def fill(*args, data=None, **kwargs):
return gca().fill(
*args, **({"data": data} if data is not None else {}),
**kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.fill_between)
def fill_between(
x, y1, y2=0, where=None, interpolate=False, step=None, *,
data=None, **kwargs):
return gca().fill_between(
x, y1, y2=y2, where=where, interpolate=interpolate, step=step,
**({"data": data} if data is not None else {}), **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.fill_betweenx)
def fill_betweenx(
y, x1, x2=0, where=None, step=None, interpolate=False, *,
data=None, **kwargs):
return gca().fill_betweenx(
y, x1, x2=x2, where=where, step=step, interpolate=interpolate,
**({"data": data} if data is not None else {}), **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.grid)
def grid(b=None, which='major', axis='both', **kwargs):
return gca().grid(b=b, which=which, axis=axis, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.hexbin)
def hexbin(
x, y, C=None, gridsize=100, bins=None, xscale='linear',
yscale='linear', extent=None, cmap=None, norm=None, vmin=None,
vmax=None, alpha=None, linewidths=None, edgecolors='face',
reduce_C_function=np.mean, mincnt=None, marginals=False, *,
data=None, **kwargs):
__ret = gca().hexbin(
x, y, C=C, gridsize=gridsize, bins=bins, xscale=xscale,
yscale=yscale, extent=extent, cmap=cmap, norm=norm, vmin=vmin,
vmax=vmax, alpha=alpha, linewidths=linewidths,
edgecolors=edgecolors, reduce_C_function=reduce_C_function,
mincnt=mincnt, marginals=marginals, **({"data": data} if data
is not None else {}), **kwargs)
sci(__ret)
return __ret
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.hist)
def hist(
x, bins=None, range=None, density=None, weights=None,
cumulative=False, bottom=None, histtype='bar', align='mid',
orientation='vertical', rwidth=None, log=False, color=None,
label=None, stacked=False, normed=None, *, data=None,
**kwargs):
return gca().hist(
x, bins=bins, range=range, density=density, weights=weights,
cumulative=cumulative, bottom=bottom, histtype=histtype,
align=align, orientation=orientation, rwidth=rwidth, log=log,
color=color, label=label, stacked=stacked, normed=normed,
**({"data": data} if data is not None else {}), **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.hist2d)
def hist2d(
x, y, bins=10, range=None, density=False, weights=None,
cmin=None, cmax=None, *, data=None, **kwargs):
__ret = gca().hist2d(
x, y, bins=bins, range=range, density=density,
weights=weights, cmin=cmin, cmax=cmax, **({"data": data} if
data is not None else {}), **kwargs)
sci(__ret[-1])
return __ret
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.hlines)
def hlines(
y, xmin, xmax, colors='k', linestyles='solid', label='', *,
data=None, **kwargs):
return gca().hlines(
y, xmin, xmax, colors=colors, linestyles=linestyles,
label=label, **({"data": data} if data is not None else {}),
**kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.imshow)
def imshow(
X, cmap=None, norm=None, aspect=None, interpolation=None,
alpha=None, vmin=None, vmax=None, origin=None, extent=None,
shape=cbook.deprecation._deprecated_parameter, filternorm=1,
filterrad=4.0, imlim=cbook.deprecation._deprecated_parameter,
resample=None, url=None, *, data=None, **kwargs):
__ret = gca().imshow(
X, cmap=cmap, norm=norm, aspect=aspect,
interpolation=interpolation, alpha=alpha, vmin=vmin,
vmax=vmax, origin=origin, extent=extent, shape=shape,
filternorm=filternorm, filterrad=filterrad, imlim=imlim,
resample=resample, url=url, **({"data": data} if data is not
None else {}), **kwargs)
sci(__ret)
return __ret
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.legend)
def legend(*args, **kwargs):
return gca().legend(*args, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.locator_params)
def locator_params(axis='both', tight=None, **kwargs):
return gca().locator_params(axis=axis, tight=tight, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.loglog)
def loglog(*args, **kwargs):
return gca().loglog(*args, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.magnitude_spectrum)
def magnitude_spectrum(
x, Fs=None, Fc=None, window=None, pad_to=None, sides=None,
scale=None, *, data=None, **kwargs):
return gca().magnitude_spectrum(
x, Fs=Fs, Fc=Fc, window=window, pad_to=pad_to, sides=sides,
scale=scale, **({"data": data} if data is not None else {}),
**kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.margins)
def margins(*margins, x=None, y=None, tight=True):
return gca().margins(*margins, x=x, y=y, tight=tight)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.minorticks_off)
def minorticks_off():
return gca().minorticks_off()
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.minorticks_on)
def minorticks_on():
return gca().minorticks_on()
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.pcolor)
def pcolor(
*args, alpha=None, norm=None, cmap=None, vmin=None,
vmax=None, data=None, **kwargs):
__ret = gca().pcolor(
*args, alpha=alpha, norm=norm, cmap=cmap, vmin=vmin,
vmax=vmax, **({"data": data} if data is not None else {}),
**kwargs)
sci(__ret)
return __ret
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.pcolormesh)
def pcolormesh(
*args, alpha=None, norm=None, cmap=None, vmin=None,
vmax=None, shading='flat', antialiased=False, data=None,
**kwargs):
__ret = gca().pcolormesh(
*args, alpha=alpha, norm=norm, cmap=cmap, vmin=vmin,
vmax=vmax, shading=shading, antialiased=antialiased,
**({"data": data} if data is not None else {}), **kwargs)
sci(__ret)
return __ret
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.phase_spectrum)
def phase_spectrum(
x, Fs=None, Fc=None, window=None, pad_to=None, sides=None, *,
data=None, **kwargs):
return gca().phase_spectrum(
x, Fs=Fs, Fc=Fc, window=window, pad_to=pad_to, sides=sides,
**({"data": data} if data is not None else {}), **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.pie)
def pie(
x, explode=None, labels=None, colors=None, autopct=None,
pctdistance=0.6, shadow=False, labeldistance=1.1,
startangle=None, radius=None, counterclock=True,
wedgeprops=None, textprops=None, center=(0, 0), frame=False,
rotatelabels=False, *, data=None):
return gca().pie(
x, explode=explode, labels=labels, colors=colors,
autopct=autopct, pctdistance=pctdistance, shadow=shadow,
labeldistance=labeldistance, startangle=startangle,
radius=radius, counterclock=counterclock,
wedgeprops=wedgeprops, textprops=textprops, center=center,
frame=frame, rotatelabels=rotatelabels, **({"data": data} if
data is not None else {}))
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.plot)
def plot(*args, scalex=True, scaley=True, data=None, **kwargs):
return gca().plot(
*args, scalex=scalex, scaley=scaley, **({"data": data} if data
is not None else {}), **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.plot_date)
def plot_date(
x, y, fmt='o', tz=None, xdate=True, ydate=False, *,
data=None, **kwargs):
return gca().plot_date(
x, y, fmt=fmt, tz=tz, xdate=xdate, ydate=ydate, **({"data":
data} if data is not None else {}), **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.psd)
def psd(
x, NFFT=None, Fs=None, Fc=None, detrend=None, window=None,
noverlap=None, pad_to=None, sides=None, scale_by_freq=None,
return_line=None, *, data=None, **kwargs):
return gca().psd(
x, NFFT=NFFT, Fs=Fs, Fc=Fc, detrend=detrend, window=window,
noverlap=noverlap, pad_to=pad_to, sides=sides,
scale_by_freq=scale_by_freq, return_line=return_line,
**({"data": data} if data is not None else {}), **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.quiver)
def quiver(*args, data=None, **kw):
__ret = gca().quiver(
*args, **({"data": data} if data is not None else {}), **kw)
sci(__ret)
return __ret
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.quiverkey)
def quiverkey(Q, X, Y, U, label, **kw):
return gca().quiverkey(Q, X, Y, U, label, **kw)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.scatter)
def scatter(
x, y, s=None, c=None, marker=None, cmap=None, norm=None,
vmin=None, vmax=None, alpha=None, linewidths=None, verts=None,
edgecolors=None, *, plotnonfinite=False, data=None, **kwargs):
__ret = gca().scatter(
x, y, s=s, c=c, marker=marker, cmap=cmap, norm=norm,
vmin=vmin, vmax=vmax, alpha=alpha, linewidths=linewidths,
verts=verts, edgecolors=edgecolors,
plotnonfinite=plotnonfinite, **({"data": data} if data is not
None else {}), **kwargs)
sci(__ret)
return __ret
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.semilogx)
def semilogx(*args, **kwargs):
return gca().semilogx(*args, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.semilogy)
def semilogy(*args, **kwargs):
return gca().semilogy(*args, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.specgram)
def specgram(
x, NFFT=None, Fs=None, Fc=None, detrend=None, window=None,
noverlap=None, cmap=None, xextent=None, pad_to=None,
sides=None, scale_by_freq=None, mode=None, scale=None,
vmin=None, vmax=None, *, data=None, **kwargs):
__ret = gca().specgram(
x, NFFT=NFFT, Fs=Fs, Fc=Fc, detrend=detrend, window=window,
noverlap=noverlap, cmap=cmap, xextent=xextent, pad_to=pad_to,
sides=sides, scale_by_freq=scale_by_freq, mode=mode,
scale=scale, vmin=vmin, vmax=vmax, **({"data": data} if data
is not None else {}), **kwargs)
sci(__ret[-1])
return __ret
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.spy)
def spy(
Z, precision=0, marker=None, markersize=None, aspect='equal',
origin='upper', **kwargs):
__ret = gca().spy(
Z, precision=precision, marker=marker, markersize=markersize,
aspect=aspect, origin=origin, **kwargs)
if isinstance(__ret, cm.ScalarMappable): sci(__ret) # noqa
return __ret
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.stackplot)
def stackplot(
x, *args, labels=(), colors=None, baseline='zero', data=None,
**kwargs):
return gca().stackplot(
x, *args, labels=labels, colors=colors, baseline=baseline,
**({"data": data} if data is not None else {}), **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.stem)
def stem(
*args, linefmt=None, markerfmt=None, basefmt=None, bottom=0,
label=None, use_line_collection=False, data=None):
return gca().stem(
*args, linefmt=linefmt, markerfmt=markerfmt, basefmt=basefmt,
bottom=bottom, label=label,
use_line_collection=use_line_collection, **({"data": data} if
data is not None else {}))
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.step)
def step(x, y, *args, where='pre', data=None, **kwargs):
return gca().step(
x, y, *args, where=where, **({"data": data} if data is not
None else {}), **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.streamplot)
def streamplot(
x, y, u, v, density=1, linewidth=None, color=None, cmap=None,
norm=None, arrowsize=1, arrowstyle='-|>', minlength=0.1,
transform=None, zorder=None, start_points=None, maxlength=4.0,
integration_direction='both', *, data=None):
__ret = gca().streamplot(
x, y, u, v, density=density, linewidth=linewidth, color=color,
cmap=cmap, norm=norm, arrowsize=arrowsize,
arrowstyle=arrowstyle, minlength=minlength,
transform=transform, zorder=zorder, start_points=start_points,
maxlength=maxlength,
integration_direction=integration_direction, **({"data": data}
if data is not None else {}))
sci(__ret.lines)
return __ret
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.table)
def table(
cellText=None, cellColours=None, cellLoc='right',
colWidths=None, rowLabels=None, rowColours=None,
rowLoc='left', colLabels=None, colColours=None,
colLoc='center', loc='bottom', bbox=None, edges='closed',
**kwargs):
return gca().table(
cellText=cellText, cellColours=cellColours, cellLoc=cellLoc,
colWidths=colWidths, rowLabels=rowLabels,
rowColours=rowColours, rowLoc=rowLoc, colLabels=colLabels,
colColours=colColours, colLoc=colLoc, loc=loc, bbox=bbox,
edges=edges, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.text)
def text(
x, y, s, fontdict=None,
withdash=cbook.deprecation._deprecated_parameter, **kwargs):
return gca().text(x, y, s, fontdict=fontdict, withdash=withdash, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.tick_params)
def tick_params(axis='both', **kwargs):
return gca().tick_params(axis=axis, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.ticklabel_format)
def ticklabel_format(
*, axis='both', style='', scilimits=None, useOffset=None,
useLocale=None, useMathText=None):
return gca().ticklabel_format(
axis=axis, style=style, scilimits=scilimits,
useOffset=useOffset, useLocale=useLocale,
useMathText=useMathText)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.tricontour)
def tricontour(*args, **kwargs):
__ret = gca().tricontour(*args, **kwargs)
if __ret._A is not None: sci(__ret) # noqa
return __ret
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.tricontourf)
def tricontourf(*args, **kwargs):
__ret = gca().tricontourf(*args, **kwargs)
if __ret._A is not None: sci(__ret) # noqa
return __ret
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.tripcolor)
def tripcolor(
*args, alpha=1.0, norm=None, cmap=None, vmin=None, vmax=None,
shading='flat', facecolors=None, **kwargs):
__ret = gca().tripcolor(
*args, alpha=alpha, norm=norm, cmap=cmap, vmin=vmin,
vmax=vmax, shading=shading, facecolors=facecolors, **kwargs)
sci(__ret)
return __ret
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.triplot)
def triplot(*args, **kwargs):
return gca().triplot(*args, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.violinplot)
def violinplot(
dataset, positions=None, vert=True, widths=0.5,
showmeans=False, showextrema=True, showmedians=False,
points=100, bw_method=None, *, data=None):
return gca().violinplot(
dataset, positions=positions, vert=vert, widths=widths,
showmeans=showmeans, showextrema=showextrema,
showmedians=showmedians, points=points, bw_method=bw_method,
**({"data": data} if data is not None else {}))
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.vlines)
def vlines(
x, ymin, ymax, colors='k', linestyles='solid', label='', *,
data=None, **kwargs):
return gca().vlines(
x, ymin, ymax, colors=colors, linestyles=linestyles,
label=label, **({"data": data} if data is not None else {}),
**kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.xcorr)
def xcorr(
x, y, normed=True, detrend=mlab.detrend_none, usevlines=True,
maxlags=10, *, data=None, **kwargs):
return gca().xcorr(
x, y, normed=normed, detrend=detrend, usevlines=usevlines,
maxlags=maxlags, **({"data": data} if data is not None else
{}), **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes._sci)
def sci(im):
return gca()._sci(im)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.set_title)
def title(label, fontdict=None, loc=None, pad=None, **kwargs):
return gca().set_title(
label, fontdict=fontdict, loc=loc, pad=pad, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.set_xlabel)
def xlabel(xlabel, fontdict=None, labelpad=None, **kwargs):
return gca().set_xlabel(
xlabel, fontdict=fontdict, labelpad=labelpad, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.set_ylabel)
def ylabel(ylabel, fontdict=None, labelpad=None, **kwargs):
return gca().set_ylabel(
ylabel, fontdict=fontdict, labelpad=labelpad, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.set_xscale)
def xscale(value, **kwargs):
return gca().set_xscale(value, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.set_yscale)
def yscale(value, **kwargs):
return gca().set_yscale(value, **kwargs)
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
def autumn():
"""
Set the colormap to "autumn".
This changes the default colormap as well as the colormap of the current
image if there is one. See ``help(colormaps)`` for more information.
"""
set_cmap("autumn")
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
def bone():
"""
Set the colormap to "bone".
This changes the default colormap as well as the colormap of the current
image if there is one. See ``help(colormaps)`` for more information.
"""
set_cmap("bone")
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
def cool():
"""
Set the colormap to "cool".
This changes the default colormap as well as the colormap of the current
image if there is one. See ``help(colormaps)`` for more information.
"""
set_cmap("cool")
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
def copper():
"""
Set the colormap to "copper".
This changes the default colormap as well as the colormap of the current
image if there is one. See ``help(colormaps)`` for more information.
"""
set_cmap("copper")
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
def flag():
"""
Set the colormap to "flag".
This changes the default colormap as well as the colormap of the current
image if there is one. See ``help(colormaps)`` for more information.
"""
set_cmap("flag")
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
def gray():
"""
Set the colormap to "gray".
This changes the default colormap as well as the colormap of the current
image if there is one. See ``help(colormaps)`` for more information.
"""
set_cmap("gray")
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
def hot():
"""
Set the colormap to "hot".
This changes the default colormap as well as the colormap of the current
image if there is one. See ``help(colormaps)`` for more information.
"""
set_cmap("hot")
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
def hsv():
"""
Set the colormap to "hsv".
This changes the default colormap as well as the colormap of the current
image if there is one. See ``help(colormaps)`` for more information.
"""
set_cmap("hsv")
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
def jet():
"""
Set the colormap to "jet".
This changes the default colormap as well as the colormap of the current
image if there is one. See ``help(colormaps)`` for more information.
"""
set_cmap("jet")
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
def pink():
"""
Set the colormap to "pink".
This changes the default colormap as well as the colormap of the current
image if there is one. See ``help(colormaps)`` for more information.
"""
set_cmap("pink")
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
def prism():
"""
Set the colormap to "prism".
This changes the default colormap as well as the colormap of the current
image if there is one. See ``help(colormaps)`` for more information.
"""
set_cmap("prism")
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
def spring():
"""
Set the colormap to "spring".
This changes the default colormap as well as the colormap of the current
image if there is one. See ``help(colormaps)`` for more information.
"""
set_cmap("spring")
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
def summer():
"""
Set the colormap to "summer".
This changes the default colormap as well as the colormap of the current
image if there is one. See ``help(colormaps)`` for more information.
"""
set_cmap("summer")
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
def winter():
"""
Set the colormap to "winter".
This changes the default colormap as well as the colormap of the current
image if there is one. See ``help(colormaps)`` for more information.
"""
set_cmap("winter")
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
def magma():
"""
Set the colormap to "magma".
This changes the default colormap as well as the colormap of the current
image if there is one. See ``help(colormaps)`` for more information.
"""
set_cmap("magma")
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
def inferno():
"""
Set the colormap to "inferno".
This changes the default colormap as well as the colormap of the current
image if there is one. See ``help(colormaps)`` for more information.
"""
set_cmap("inferno")
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
def plasma():
"""
Set the colormap to "plasma".
This changes the default colormap as well as the colormap of the current
image if there is one. See ``help(colormaps)`` for more information.
"""
set_cmap("plasma")
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
def viridis():
"""
Set the colormap to "viridis".
This changes the default colormap as well as the colormap of the current
image if there is one. See ``help(colormaps)`` for more information.
"""
set_cmap("viridis")
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
def nipy_spectral():
"""
Set the colormap to "nipy_spectral".
This changes the default colormap as well as the colormap of the current
image if there is one. See ``help(colormaps)`` for more information.
"""
set_cmap("nipy_spectral")
_setup_pyplot_info_docstrings()
|
b5b125726a9bdd4bd0ccc00ddd38623837c551dc4ada1301da475d5e75dd0b2e
|
from collections import OrderedDict
BASE_COLORS = {
'b': (0, 0, 1),
'g': (0, 0.5, 0),
'r': (1, 0, 0),
'c': (0, 0.75, 0.75),
'm': (0.75, 0, 0.75),
'y': (0.75, 0.75, 0),
'k': (0, 0, 0),
'w': (1, 1, 1)}
# These colors are from Tableau
TABLEAU_COLORS = (
('blue', '#1f77b4'),
('orange', '#ff7f0e'),
('green', '#2ca02c'),
('red', '#d62728'),
('purple', '#9467bd'),
('brown', '#8c564b'),
('pink', '#e377c2'),
('gray', '#7f7f7f'),
('olive', '#bcbd22'),
('cyan', '#17becf'),
)
# Normalize name to "tab:<name>" to avoid name collisions.
TABLEAU_COLORS = OrderedDict(
('tab:' + name, value) for name, value in TABLEAU_COLORS)
# This mapping of color names -> hex values is taken from
# a survey run by Randall Munroe see:
# http://blog.xkcd.com/2010/05/03/color-survey-results/
# for more details. The results are hosted at
# https://xkcd.com/color/rgb.txt
#
# License: http://creativecommons.org/publicdomain/zero/1.0/
XKCD_COLORS = {
'cloudy blue': '#acc2d9',
'dark pastel green': '#56ae57',
'dust': '#b2996e',
'electric lime': '#a8ff04',
'fresh green': '#69d84f',
'light eggplant': '#894585',
'nasty green': '#70b23f',
'really light blue': '#d4ffff',
'tea': '#65ab7c',
'warm purple': '#952e8f',
'yellowish tan': '#fcfc81',
'cement': '#a5a391',
'dark grass green': '#388004',
'dusty teal': '#4c9085',
'grey teal': '#5e9b8a',
'macaroni and cheese': '#efb435',
'pinkish tan': '#d99b82',
'spruce': '#0a5f38',
'strong blue': '#0c06f7',
'toxic green': '#61de2a',
'windows blue': '#3778bf',
'blue blue': '#2242c7',
'blue with a hint of purple': '#533cc6',
'booger': '#9bb53c',
'bright sea green': '#05ffa6',
'dark green blue': '#1f6357',
'deep turquoise': '#017374',
'green teal': '#0cb577',
'strong pink': '#ff0789',
'bland': '#afa88b',
'deep aqua': '#08787f',
'lavender pink': '#dd85d7',
'light moss green': '#a6c875',
'light seafoam green': '#a7ffb5',
'olive yellow': '#c2b709',
'pig pink': '#e78ea5',
'deep lilac': '#966ebd',
'desert': '#ccad60',
'dusty lavender': '#ac86a8',
'purpley grey': '#947e94',
'purply': '#983fb2',
'candy pink': '#ff63e9',
'light pastel green': '#b2fba5',
'boring green': '#63b365',
'kiwi green': '#8ee53f',
'light grey green': '#b7e1a1',
'orange pink': '#ff6f52',
'tea green': '#bdf8a3',
'very light brown': '#d3b683',
'egg shell': '#fffcc4',
'eggplant purple': '#430541',
'powder pink': '#ffb2d0',
'reddish grey': '#997570',
'baby shit brown': '#ad900d',
'liliac': '#c48efd',
'stormy blue': '#507b9c',
'ugly brown': '#7d7103',
'custard': '#fffd78',
'darkish pink': '#da467d',
'deep brown': '#410200',
'greenish beige': '#c9d179',
'manilla': '#fffa86',
'off blue': '#5684ae',
'battleship grey': '#6b7c85',
'browny green': '#6f6c0a',
'bruise': '#7e4071',
'kelley green': '#009337',
'sickly yellow': '#d0e429',
'sunny yellow': '#fff917',
'azul': '#1d5dec',
'darkgreen': '#054907',
'green/yellow': '#b5ce08',
'lichen': '#8fb67b',
'light light green': '#c8ffb0',
'pale gold': '#fdde6c',
'sun yellow': '#ffdf22',
'tan green': '#a9be70',
'burple': '#6832e3',
'butterscotch': '#fdb147',
'toupe': '#c7ac7d',
'dark cream': '#fff39a',
'indian red': '#850e04',
'light lavendar': '#efc0fe',
'poison green': '#40fd14',
'baby puke green': '#b6c406',
'bright yellow green': '#9dff00',
'charcoal grey': '#3c4142',
'squash': '#f2ab15',
'cinnamon': '#ac4f06',
'light pea green': '#c4fe82',
'radioactive green': '#2cfa1f',
'raw sienna': '#9a6200',
'baby purple': '#ca9bf7',
'cocoa': '#875f42',
'light royal blue': '#3a2efe',
'orangeish': '#fd8d49',
'rust brown': '#8b3103',
'sand brown': '#cba560',
'swamp': '#698339',
'tealish green': '#0cdc73',
'burnt siena': '#b75203',
'camo': '#7f8f4e',
'dusk blue': '#26538d',
'fern': '#63a950',
'old rose': '#c87f89',
'pale light green': '#b1fc99',
'peachy pink': '#ff9a8a',
'rosy pink': '#f6688e',
'light bluish green': '#76fda8',
'light bright green': '#53fe5c',
'light neon green': '#4efd54',
'light seafoam': '#a0febf',
'tiffany blue': '#7bf2da',
'washed out green': '#bcf5a6',
'browny orange': '#ca6b02',
'nice blue': '#107ab0',
'sapphire': '#2138ab',
'greyish teal': '#719f91',
'orangey yellow': '#fdb915',
'parchment': '#fefcaf',
'straw': '#fcf679',
'very dark brown': '#1d0200',
'terracota': '#cb6843',
'ugly blue': '#31668a',
'clear blue': '#247afd',
'creme': '#ffffb6',
'foam green': '#90fda9',
'grey/green': '#86a17d',
'light gold': '#fddc5c',
'seafoam blue': '#78d1b6',
'topaz': '#13bbaf',
'violet pink': '#fb5ffc',
'wintergreen': '#20f986',
'yellow tan': '#ffe36e',
'dark fuchsia': '#9d0759',
'indigo blue': '#3a18b1',
'light yellowish green': '#c2ff89',
'pale magenta': '#d767ad',
'rich purple': '#720058',
'sunflower yellow': '#ffda03',
'green/blue': '#01c08d',
'leather': '#ac7434',
'racing green': '#014600',
'vivid purple': '#9900fa',
'dark royal blue': '#02066f',
'hazel': '#8e7618',
'muted pink': '#d1768f',
'booger green': '#96b403',
'canary': '#fdff63',
'cool grey': '#95a3a6',
'dark taupe': '#7f684e',
'darkish purple': '#751973',
'true green': '#089404',
'coral pink': '#ff6163',
'dark sage': '#598556',
'dark slate blue': '#214761',
'flat blue': '#3c73a8',
'mushroom': '#ba9e88',
'rich blue': '#021bf9',
'dirty purple': '#734a65',
'greenblue': '#23c48b',
'icky green': '#8fae22',
'light khaki': '#e6f2a2',
'warm blue': '#4b57db',
'dark hot pink': '#d90166',
'deep sea blue': '#015482',
'carmine': '#9d0216',
'dark yellow green': '#728f02',
'pale peach': '#ffe5ad',
'plum purple': '#4e0550',
'golden rod': '#f9bc08',
'neon red': '#ff073a',
'old pink': '#c77986',
'very pale blue': '#d6fffe',
'blood orange': '#fe4b03',
'grapefruit': '#fd5956',
'sand yellow': '#fce166',
'clay brown': '#b2713d',
'dark blue grey': '#1f3b4d',
'flat green': '#699d4c',
'light green blue': '#56fca2',
'warm pink': '#fb5581',
'dodger blue': '#3e82fc',
'gross green': '#a0bf16',
'ice': '#d6fffa',
'metallic blue': '#4f738e',
'pale salmon': '#ffb19a',
'sap green': '#5c8b15',
'algae': '#54ac68',
'bluey grey': '#89a0b0',
'greeny grey': '#7ea07a',
'highlighter green': '#1bfc06',
'light light blue': '#cafffb',
'light mint': '#b6ffbb',
'raw umber': '#a75e09',
'vivid blue': '#152eff',
'deep lavender': '#8d5eb7',
'dull teal': '#5f9e8f',
'light greenish blue': '#63f7b4',
'mud green': '#606602',
'pinky': '#fc86aa',
'red wine': '#8c0034',
'shit green': '#758000',
'tan brown': '#ab7e4c',
'darkblue': '#030764',
'rosa': '#fe86a4',
'lipstick': '#d5174e',
'pale mauve': '#fed0fc',
'claret': '#680018',
'dandelion': '#fedf08',
'orangered': '#fe420f',
'poop green': '#6f7c00',
'ruby': '#ca0147',
'dark': '#1b2431',
'greenish turquoise': '#00fbb0',
'pastel red': '#db5856',
'piss yellow': '#ddd618',
'bright cyan': '#41fdfe',
'dark coral': '#cf524e',
'algae green': '#21c36f',
'darkish red': '#a90308',
'reddy brown': '#6e1005',
'blush pink': '#fe828c',
'camouflage green': '#4b6113',
'lawn green': '#4da409',
'putty': '#beae8a',
'vibrant blue': '#0339f8',
'dark sand': '#a88f59',
'purple/blue': '#5d21d0',
'saffron': '#feb209',
'twilight': '#4e518b',
'warm brown': '#964e02',
'bluegrey': '#85a3b2',
'bubble gum pink': '#ff69af',
'duck egg blue': '#c3fbf4',
'greenish cyan': '#2afeb7',
'petrol': '#005f6a',
'royal': '#0c1793',
'butter': '#ffff81',
'dusty orange': '#f0833a',
'off yellow': '#f1f33f',
'pale olive green': '#b1d27b',
'orangish': '#fc824a',
'leaf': '#71aa34',
'light blue grey': '#b7c9e2',
'dried blood': '#4b0101',
'lightish purple': '#a552e6',
'rusty red': '#af2f0d',
'lavender blue': '#8b88f8',
'light grass green': '#9af764',
'light mint green': '#a6fbb2',
'sunflower': '#ffc512',
'velvet': '#750851',
'brick orange': '#c14a09',
'lightish red': '#fe2f4a',
'pure blue': '#0203e2',
'twilight blue': '#0a437a',
'violet red': '#a50055',
'yellowy brown': '#ae8b0c',
'carnation': '#fd798f',
'muddy yellow': '#bfac05',
'dark seafoam green': '#3eaf76',
'deep rose': '#c74767',
'dusty red': '#b9484e',
'grey/blue': '#647d8e',
'lemon lime': '#bffe28',
'purple/pink': '#d725de',
'brown yellow': '#b29705',
'purple brown': '#673a3f',
'wisteria': '#a87dc2',
'banana yellow': '#fafe4b',
'lipstick red': '#c0022f',
'water blue': '#0e87cc',
'brown grey': '#8d8468',
'vibrant purple': '#ad03de',
'baby green': '#8cff9e',
'barf green': '#94ac02',
'eggshell blue': '#c4fff7',
'sandy yellow': '#fdee73',
'cool green': '#33b864',
'pale': '#fff9d0',
'blue/grey': '#758da3',
'hot magenta': '#f504c9',
'greyblue': '#77a1b5',
'purpley': '#8756e4',
'baby shit green': '#889717',
'brownish pink': '#c27e79',
'dark aquamarine': '#017371',
'diarrhea': '#9f8303',
'light mustard': '#f7d560',
'pale sky blue': '#bdf6fe',
'turtle green': '#75b84f',
'bright olive': '#9cbb04',
'dark grey blue': '#29465b',
'greeny brown': '#696006',
'lemon green': '#adf802',
'light periwinkle': '#c1c6fc',
'seaweed green': '#35ad6b',
'sunshine yellow': '#fffd37',
'ugly purple': '#a442a0',
'medium pink': '#f36196',
'puke brown': '#947706',
'very light pink': '#fff4f2',
'viridian': '#1e9167',
'bile': '#b5c306',
'faded yellow': '#feff7f',
'very pale green': '#cffdbc',
'vibrant green': '#0add08',
'bright lime': '#87fd05',
'spearmint': '#1ef876',
'light aquamarine': '#7bfdc7',
'light sage': '#bcecac',
'yellowgreen': '#bbf90f',
'baby poo': '#ab9004',
'dark seafoam': '#1fb57a',
'deep teal': '#00555a',
'heather': '#a484ac',
'rust orange': '#c45508',
'dirty blue': '#3f829d',
'fern green': '#548d44',
'bright lilac': '#c95efb',
'weird green': '#3ae57f',
'peacock blue': '#016795',
'avocado green': '#87a922',
'faded orange': '#f0944d',
'grape purple': '#5d1451',
'hot green': '#25ff29',
'lime yellow': '#d0fe1d',
'mango': '#ffa62b',
'shamrock': '#01b44c',
'bubblegum': '#ff6cb5',
'purplish brown': '#6b4247',
'vomit yellow': '#c7c10c',
'pale cyan': '#b7fffa',
'key lime': '#aeff6e',
'tomato red': '#ec2d01',
'lightgreen': '#76ff7b',
'merlot': '#730039',
'night blue': '#040348',
'purpleish pink': '#df4ec8',
'apple': '#6ecb3c',
'baby poop green': '#8f9805',
'green apple': '#5edc1f',
'heliotrope': '#d94ff5',
'yellow/green': '#c8fd3d',
'almost black': '#070d0d',
'cool blue': '#4984b8',
'leafy green': '#51b73b',
'mustard brown': '#ac7e04',
'dusk': '#4e5481',
'dull brown': '#876e4b',
'frog green': '#58bc08',
'vivid green': '#2fef10',
'bright light green': '#2dfe54',
'fluro green': '#0aff02',
'kiwi': '#9cef43',
'seaweed': '#18d17b',
'navy green': '#35530a',
'ultramarine blue': '#1805db',
'iris': '#6258c4',
'pastel orange': '#ff964f',
'yellowish orange': '#ffab0f',
'perrywinkle': '#8f8ce7',
'tealish': '#24bca8',
'dark plum': '#3f012c',
'pear': '#cbf85f',
'pinkish orange': '#ff724c',
'midnight purple': '#280137',
'light urple': '#b36ff6',
'dark mint': '#48c072',
'greenish tan': '#bccb7a',
'light burgundy': '#a8415b',
'turquoise blue': '#06b1c4',
'ugly pink': '#cd7584',
'sandy': '#f1da7a',
'electric pink': '#ff0490',
'muted purple': '#805b87',
'mid green': '#50a747',
'greyish': '#a8a495',
'neon yellow': '#cfff04',
'banana': '#ffff7e',
'carnation pink': '#ff7fa7',
'tomato': '#ef4026',
'sea': '#3c9992',
'muddy brown': '#886806',
'turquoise green': '#04f489',
'buff': '#fef69e',
'fawn': '#cfaf7b',
'muted blue': '#3b719f',
'pale rose': '#fdc1c5',
'dark mint green': '#20c073',
'amethyst': '#9b5fc0',
'blue/green': '#0f9b8e',
'chestnut': '#742802',
'sick green': '#9db92c',
'pea': '#a4bf20',
'rusty orange': '#cd5909',
'stone': '#ada587',
'rose red': '#be013c',
'pale aqua': '#b8ffeb',
'deep orange': '#dc4d01',
'earth': '#a2653e',
'mossy green': '#638b27',
'grassy green': '#419c03',
'pale lime green': '#b1ff65',
'light grey blue': '#9dbcd4',
'pale grey': '#fdfdfe',
'asparagus': '#77ab56',
'blueberry': '#464196',
'purple red': '#990147',
'pale lime': '#befd73',
'greenish teal': '#32bf84',
'caramel': '#af6f09',
'deep magenta': '#a0025c',
'light peach': '#ffd8b1',
'milk chocolate': '#7f4e1e',
'ocher': '#bf9b0c',
'off green': '#6ba353',
'purply pink': '#f075e6',
'lightblue': '#7bc8f6',
'dusky blue': '#475f94',
'golden': '#f5bf03',
'light beige': '#fffeb6',
'butter yellow': '#fffd74',
'dusky purple': '#895b7b',
'french blue': '#436bad',
'ugly yellow': '#d0c101',
'greeny yellow': '#c6f808',
'orangish red': '#f43605',
'shamrock green': '#02c14d',
'orangish brown': '#b25f03',
'tree green': '#2a7e19',
'deep violet': '#490648',
'gunmetal': '#536267',
'blue/purple': '#5a06ef',
'cherry': '#cf0234',
'sandy brown': '#c4a661',
'warm grey': '#978a84',
'dark indigo': '#1f0954',
'midnight': '#03012d',
'bluey green': '#2bb179',
'grey pink': '#c3909b',
'soft purple': '#a66fb5',
'blood': '#770001',
'brown red': '#922b05',
'medium grey': '#7d7f7c',
'berry': '#990f4b',
'poo': '#8f7303',
'purpley pink': '#c83cb9',
'light salmon': '#fea993',
'snot': '#acbb0d',
'easter purple': '#c071fe',
'light yellow green': '#ccfd7f',
'dark navy blue': '#00022e',
'drab': '#828344',
'light rose': '#ffc5cb',
'rouge': '#ab1239',
'purplish red': '#b0054b',
'slime green': '#99cc04',
'baby poop': '#937c00',
'irish green': '#019529',
'pink/purple': '#ef1de7',
'dark navy': '#000435',
'greeny blue': '#42b395',
'light plum': '#9d5783',
'pinkish grey': '#c8aca9',
'dirty orange': '#c87606',
'rust red': '#aa2704',
'pale lilac': '#e4cbff',
'orangey red': '#fa4224',
'primary blue': '#0804f9',
'kermit green': '#5cb200',
'brownish purple': '#76424e',
'murky green': '#6c7a0e',
'wheat': '#fbdd7e',
'very dark purple': '#2a0134',
'bottle green': '#044a05',
'watermelon': '#fd4659',
'deep sky blue': '#0d75f8',
'fire engine red': '#fe0002',
'yellow ochre': '#cb9d06',
'pumpkin orange': '#fb7d07',
'pale olive': '#b9cc81',
'light lilac': '#edc8ff',
'lightish green': '#61e160',
'carolina blue': '#8ab8fe',
'mulberry': '#920a4e',
'shocking pink': '#fe02a2',
'auburn': '#9a3001',
'bright lime green': '#65fe08',
'celadon': '#befdb7',
'pinkish brown': '#b17261',
'poo brown': '#885f01',
'bright sky blue': '#02ccfe',
'celery': '#c1fd95',
'dirt brown': '#836539',
'strawberry': '#fb2943',
'dark lime': '#84b701',
'copper': '#b66325',
'medium brown': '#7f5112',
'muted green': '#5fa052',
"robin's egg": '#6dedfd',
'bright aqua': '#0bf9ea',
'bright lavender': '#c760ff',
'ivory': '#ffffcb',
'very light purple': '#f6cefc',
'light navy': '#155084',
'pink red': '#f5054f',
'olive brown': '#645403',
'poop brown': '#7a5901',
'mustard green': '#a8b504',
'ocean green': '#3d9973',
'very dark blue': '#000133',
'dusty green': '#76a973',
'light navy blue': '#2e5a88',
'minty green': '#0bf77d',
'adobe': '#bd6c48',
'barney': '#ac1db8',
'jade green': '#2baf6a',
'bright light blue': '#26f7fd',
'light lime': '#aefd6c',
'dark khaki': '#9b8f55',
'orange yellow': '#ffad01',
'ocre': '#c69c04',
'maize': '#f4d054',
'faded pink': '#de9dac',
'british racing green': '#05480d',
'sandstone': '#c9ae74',
'mud brown': '#60460f',
'light sea green': '#98f6b0',
'robin egg blue': '#8af1fe',
'aqua marine': '#2ee8bb',
'dark sea green': '#11875d',
'soft pink': '#fdb0c0',
'orangey brown': '#b16002',
'cherry red': '#f7022a',
'burnt yellow': '#d5ab09',
'brownish grey': '#86775f',
'camel': '#c69f59',
'purplish grey': '#7a687f',
'marine': '#042e60',
'greyish pink': '#c88d94',
'pale turquoise': '#a5fbd5',
'pastel yellow': '#fffe71',
'bluey purple': '#6241c7',
'canary yellow': '#fffe40',
'faded red': '#d3494e',
'sepia': '#985e2b',
'coffee': '#a6814c',
'bright magenta': '#ff08e8',
'mocha': '#9d7651',
'ecru': '#feffca',
'purpleish': '#98568d',
'cranberry': '#9e003a',
'darkish green': '#287c37',
'brown orange': '#b96902',
'dusky rose': '#ba6873',
'melon': '#ff7855',
'sickly green': '#94b21c',
'silver': '#c5c9c7',
'purply blue': '#661aee',
'purpleish blue': '#6140ef',
'hospital green': '#9be5aa',
'shit brown': '#7b5804',
'mid blue': '#276ab3',
'amber': '#feb308',
'easter green': '#8cfd7e',
'soft blue': '#6488ea',
'cerulean blue': '#056eee',
'golden brown': '#b27a01',
'bright turquoise': '#0ffef9',
'red pink': '#fa2a55',
'red purple': '#820747',
'greyish brown': '#7a6a4f',
'vermillion': '#f4320c',
'russet': '#a13905',
'steel grey': '#6f828a',
'lighter purple': '#a55af4',
'bright violet': '#ad0afd',
'prussian blue': '#004577',
'slate green': '#658d6d',
'dirty pink': '#ca7b80',
'dark blue green': '#005249',
'pine': '#2b5d34',
'yellowy green': '#bff128',
'dark gold': '#b59410',
'bluish': '#2976bb',
'darkish blue': '#014182',
'dull red': '#bb3f3f',
'pinky red': '#fc2647',
'bronze': '#a87900',
'pale teal': '#82cbb2',
'military green': '#667c3e',
'barbie pink': '#fe46a5',
'bubblegum pink': '#fe83cc',
'pea soup green': '#94a617',
'dark mustard': '#a88905',
'shit': '#7f5f00',
'medium purple': '#9e43a2',
'very dark green': '#062e03',
'dirt': '#8a6e45',
'dusky pink': '#cc7a8b',
'red violet': '#9e0168',
'lemon yellow': '#fdff38',
'pistachio': '#c0fa8b',
'dull yellow': '#eedc5b',
'dark lime green': '#7ebd01',
'denim blue': '#3b5b92',
'teal blue': '#01889f',
'lightish blue': '#3d7afd',
'purpley blue': '#5f34e7',
'light indigo': '#6d5acf',
'swamp green': '#748500',
'brown green': '#706c11',
'dark maroon': '#3c0008',
'hot purple': '#cb00f5',
'dark forest green': '#002d04',
'faded blue': '#658cbb',
'drab green': '#749551',
'light lime green': '#b9ff66',
'snot green': '#9dc100',
'yellowish': '#faee66',
'light blue green': '#7efbb3',
'bordeaux': '#7b002c',
'light mauve': '#c292a1',
'ocean': '#017b92',
'marigold': '#fcc006',
'muddy green': '#657432',
'dull orange': '#d8863b',
'steel': '#738595',
'electric purple': '#aa23ff',
'fluorescent green': '#08ff08',
'yellowish brown': '#9b7a01',
'blush': '#f29e8e',
'soft green': '#6fc276',
'bright orange': '#ff5b00',
'lemon': '#fdff52',
'purple grey': '#866f85',
'acid green': '#8ffe09',
'pale lavender': '#eecffe',
'violet blue': '#510ac9',
'light forest green': '#4f9153',
'burnt red': '#9f2305',
'khaki green': '#728639',
'cerise': '#de0c62',
'faded purple': '#916e99',
'apricot': '#ffb16d',
'dark olive green': '#3c4d03',
'grey brown': '#7f7053',
'green grey': '#77926f',
'true blue': '#010fcc',
'pale violet': '#ceaefa',
'periwinkle blue': '#8f99fb',
'light sky blue': '#c6fcff',
'blurple': '#5539cc',
'green brown': '#544e03',
'bluegreen': '#017a79',
'bright teal': '#01f9c6',
'brownish yellow': '#c9b003',
'pea soup': '#929901',
'forest': '#0b5509',
'barney purple': '#a00498',
'ultramarine': '#2000b1',
'purplish': '#94568c',
'puke yellow': '#c2be0e',
'bluish grey': '#748b97',
'dark periwinkle': '#665fd1',
'dark lilac': '#9c6da5',
'reddish': '#c44240',
'light maroon': '#a24857',
'dusty purple': '#825f87',
'terra cotta': '#c9643b',
'avocado': '#90b134',
'marine blue': '#01386a',
'teal green': '#25a36f',
'slate grey': '#59656d',
'lighter green': '#75fd63',
'electric green': '#21fc0d',
'dusty blue': '#5a86ad',
'golden yellow': '#fec615',
'bright yellow': '#fffd01',
'light lavender': '#dfc5fe',
'umber': '#b26400',
'poop': '#7f5e00',
'dark peach': '#de7e5d',
'jungle green': '#048243',
'eggshell': '#ffffd4',
'denim': '#3b638c',
'yellow brown': '#b79400',
'dull purple': '#84597e',
'chocolate brown': '#411900',
'wine red': '#7b0323',
'neon blue': '#04d9ff',
'dirty green': '#667e2c',
'light tan': '#fbeeac',
'ice blue': '#d7fffe',
'cadet blue': '#4e7496',
'dark mauve': '#874c62',
'very light blue': '#d5ffff',
'grey purple': '#826d8c',
'pastel pink': '#ffbacd',
'very light green': '#d1ffbd',
'dark sky blue': '#448ee4',
'evergreen': '#05472a',
'dull pink': '#d5869d',
'aubergine': '#3d0734',
'mahogany': '#4a0100',
'reddish orange': '#f8481c',
'deep green': '#02590f',
'vomit green': '#89a203',
'purple pink': '#e03fd8',
'dusty pink': '#d58a94',
'faded green': '#7bb274',
'camo green': '#526525',
'pinky purple': '#c94cbe',
'pink purple': '#db4bda',
'brownish red': '#9e3623',
'dark rose': '#b5485d',
'mud': '#735c12',
'brownish': '#9c6d57',
'emerald green': '#028f1e',
'pale brown': '#b1916e',
'dull blue': '#49759c',
'burnt umber': '#a0450e',
'medium green': '#39ad48',
'clay': '#b66a50',
'light aqua': '#8cffdb',
'light olive green': '#a4be5c',
'brownish orange': '#cb7723',
'dark aqua': '#05696b',
'purplish pink': '#ce5dae',
'dark salmon': '#c85a53',
'greenish grey': '#96ae8d',
'jade': '#1fa774',
'ugly green': '#7a9703',
'dark beige': '#ac9362',
'emerald': '#01a049',
'pale red': '#d9544d',
'light magenta': '#fa5ff7',
'sky': '#82cafc',
'light cyan': '#acfffc',
'yellow orange': '#fcb001',
'reddish purple': '#910951',
'reddish pink': '#fe2c54',
'orchid': '#c875c4',
'dirty yellow': '#cdc50a',
'orange red': '#fd411e',
'deep red': '#9a0200',
'orange brown': '#be6400',
'cobalt blue': '#030aa7',
'neon pink': '#fe019a',
'rose pink': '#f7879a',
'greyish purple': '#887191',
'raspberry': '#b00149',
'aqua green': '#12e193',
'salmon pink': '#fe7b7c',
'tangerine': '#ff9408',
'brownish green': '#6a6e09',
'red brown': '#8b2e16',
'greenish brown': '#696112',
'pumpkin': '#e17701',
'pine green': '#0a481e',
'charcoal': '#343837',
'baby pink': '#ffb7ce',
'cornflower': '#6a79f7',
'blue violet': '#5d06e9',
'chocolate': '#3d1c02',
'greyish green': '#82a67d',
'scarlet': '#be0119',
'green yellow': '#c9ff27',
'dark olive': '#373e02',
'sienna': '#a9561e',
'pastel purple': '#caa0ff',
'terracotta': '#ca6641',
'aqua blue': '#02d8e9',
'sage green': '#88b378',
'blood red': '#980002',
'deep pink': '#cb0162',
'grass': '#5cac2d',
'moss': '#769958',
'pastel blue': '#a2bffe',
'bluish green': '#10a674',
'green blue': '#06b48b',
'dark tan': '#af884a',
'greenish blue': '#0b8b87',
'pale orange': '#ffa756',
'vomit': '#a2a415',
'forrest green': '#154406',
'dark lavender': '#856798',
'dark violet': '#34013f',
'purple blue': '#632de9',
'dark cyan': '#0a888a',
'olive drab': '#6f7632',
'pinkish': '#d46a7e',
'cobalt': '#1e488f',
'neon purple': '#bc13fe',
'light turquoise': '#7ef4cc',
'apple green': '#76cd26',
'dull green': '#74a662',
'wine': '#80013f',
'powder blue': '#b1d1fc',
'off white': '#ffffe4',
'electric blue': '#0652ff',
'dark turquoise': '#045c5a',
'blue purple': '#5729ce',
'azure': '#069af3',
'bright red': '#ff000d',
'pinkish red': '#f10c45',
'cornflower blue': '#5170d7',
'light olive': '#acbf69',
'grape': '#6c3461',
'greyish blue': '#5e819d',
'purplish blue': '#601ef9',
'yellowish green': '#b0dd16',
'greenish yellow': '#cdfd02',
'medium blue': '#2c6fbb',
'dusty rose': '#c0737a',
'light violet': '#d6b4fc',
'midnight blue': '#020035',
'bluish purple': '#703be7',
'red orange': '#fd3c06',
'dark magenta': '#960056',
'greenish': '#40a368',
'ocean blue': '#03719c',
'coral': '#fc5a50',
'cream': '#ffffc2',
'reddish brown': '#7f2b0a',
'burnt sienna': '#b04e0f',
'brick': '#a03623',
'sage': '#87ae73',
'grey green': '#789b73',
'white': '#ffffff',
"robin's egg blue": '#98eff9',
'moss green': '#658b38',
'steel blue': '#5a7d9a',
'eggplant': '#380835',
'light yellow': '#fffe7a',
'leaf green': '#5ca904',
'light grey': '#d8dcd6',
'puke': '#a5a502',
'pinkish purple': '#d648d7',
'sea blue': '#047495',
'pale purple': '#b790d4',
'slate blue': '#5b7c99',
'blue grey': '#607c8e',
'hunter green': '#0b4008',
'fuchsia': '#ed0dd9',
'crimson': '#8c000f',
'pale yellow': '#ffff84',
'ochre': '#bf9005',
'mustard yellow': '#d2bd0a',
'light red': '#ff474c',
'cerulean': '#0485d1',
'pale pink': '#ffcfdc',
'deep blue': '#040273',
'rust': '#a83c09',
'light teal': '#90e4c1',
'slate': '#516572',
'goldenrod': '#fac205',
'dark yellow': '#d5b60a',
'dark grey': '#363737',
'army green': '#4b5d16',
'grey blue': '#6b8ba4',
'seafoam': '#80f9ad',
'puce': '#a57e52',
'spring green': '#a9f971',
'dark orange': '#c65102',
'sand': '#e2ca76',
'pastel green': '#b0ff9d',
'mint': '#9ffeb0',
'light orange': '#fdaa48',
'bright pink': '#fe01b1',
'chartreuse': '#c1f80a',
'deep purple': '#36013f',
'dark brown': '#341c02',
'taupe': '#b9a281',
'pea green': '#8eab12',
'puke green': '#9aae07',
'kelly green': '#02ab2e',
'seafoam green': '#7af9ab',
'blue green': '#137e6d',
'khaki': '#aaa662',
'burgundy': '#610023',
'dark teal': '#014d4e',
'brick red': '#8f1402',
'royal purple': '#4b006e',
'plum': '#580f41',
'mint green': '#8fff9f',
'gold': '#dbb40c',
'baby blue': '#a2cffe',
'yellow green': '#c0fb2d',
'bright purple': '#be03fd',
'dark red': '#840000',
'pale blue': '#d0fefe',
'grass green': '#3f9b0b',
'navy': '#01153e',
'aquamarine': '#04d8b2',
'burnt orange': '#c04e01',
'neon green': '#0cff0c',
'bright blue': '#0165fc',
'rose': '#cf6275',
'light pink': '#ffd1df',
'mustard': '#ceb301',
'indigo': '#380282',
'lime': '#aaff32',
'sea green': '#53fca1',
'periwinkle': '#8e82fe',
'dark pink': '#cb416b',
'olive green': '#677a04',
'peach': '#ffb07c',
'pale green': '#c7fdb5',
'light brown': '#ad8150',
'hot pink': '#ff028d',
'black': '#000000',
'lilac': '#cea2fd',
'navy blue': '#001146',
'royal blue': '#0504aa',
'beige': '#e6daa6',
'salmon': '#ff796c',
'olive': '#6e750e',
'maroon': '#650021',
'bright green': '#01ff07',
'dark purple': '#35063e',
'mauve': '#ae7181',
'forest green': '#06470c',
'aqua': '#13eac9',
'cyan': '#00ffff',
'tan': '#d1b26f',
'dark blue': '#00035b',
'lavender': '#c79fef',
'turquoise': '#06c2ac',
'dark green': '#033500',
'violet': '#9a0eea',
'light purple': '#bf77f6',
'lime green': '#89fe05',
'grey': '#929591',
'sky blue': '#75bbfd',
'yellow': '#ffff14',
'magenta': '#c20078',
'light green': '#96f97b',
'orange': '#f97306',
'teal': '#029386',
'light blue': '#95d0fc',
'red': '#e50000',
'brown': '#653700',
'pink': '#ff81c0',
'blue': '#0343df',
'green': '#15b01a',
'purple': '#7e1e9c'}
# Normalize name to "xkcd:<name>" to avoid name collisions.
XKCD_COLORS = {'xkcd:' + name: value for name, value in XKCD_COLORS.items()}
# https://drafts.csswg.org/css-color-4/#named-colors
CSS4_COLORS = {
'aliceblue': '#F0F8FF',
'antiquewhite': '#FAEBD7',
'aqua': '#00FFFF',
'aquamarine': '#7FFFD4',
'azure': '#F0FFFF',
'beige': '#F5F5DC',
'bisque': '#FFE4C4',
'black': '#000000',
'blanchedalmond': '#FFEBCD',
'blue': '#0000FF',
'blueviolet': '#8A2BE2',
'brown': '#A52A2A',
'burlywood': '#DEB887',
'cadetblue': '#5F9EA0',
'chartreuse': '#7FFF00',
'chocolate': '#D2691E',
'coral': '#FF7F50',
'cornflowerblue': '#6495ED',
'cornsilk': '#FFF8DC',
'crimson': '#DC143C',
'cyan': '#00FFFF',
'darkblue': '#00008B',
'darkcyan': '#008B8B',
'darkgoldenrod': '#B8860B',
'darkgray': '#A9A9A9',
'darkgreen': '#006400',
'darkgrey': '#A9A9A9',
'darkkhaki': '#BDB76B',
'darkmagenta': '#8B008B',
'darkolivegreen': '#556B2F',
'darkorange': '#FF8C00',
'darkorchid': '#9932CC',
'darkred': '#8B0000',
'darksalmon': '#E9967A',
'darkseagreen': '#8FBC8F',
'darkslateblue': '#483D8B',
'darkslategray': '#2F4F4F',
'darkslategrey': '#2F4F4F',
'darkturquoise': '#00CED1',
'darkviolet': '#9400D3',
'deeppink': '#FF1493',
'deepskyblue': '#00BFFF',
'dimgray': '#696969',
'dimgrey': '#696969',
'dodgerblue': '#1E90FF',
'firebrick': '#B22222',
'floralwhite': '#FFFAF0',
'forestgreen': '#228B22',
'fuchsia': '#FF00FF',
'gainsboro': '#DCDCDC',
'ghostwhite': '#F8F8FF',
'gold': '#FFD700',
'goldenrod': '#DAA520',
'gray': '#808080',
'green': '#008000',
'greenyellow': '#ADFF2F',
'grey': '#808080',
'honeydew': '#F0FFF0',
'hotpink': '#FF69B4',
'indianred': '#CD5C5C',
'indigo': '#4B0082',
'ivory': '#FFFFF0',
'khaki': '#F0E68C',
'lavender': '#E6E6FA',
'lavenderblush': '#FFF0F5',
'lawngreen': '#7CFC00',
'lemonchiffon': '#FFFACD',
'lightblue': '#ADD8E6',
'lightcoral': '#F08080',
'lightcyan': '#E0FFFF',
'lightgoldenrodyellow': '#FAFAD2',
'lightgray': '#D3D3D3',
'lightgreen': '#90EE90',
'lightgrey': '#D3D3D3',
'lightpink': '#FFB6C1',
'lightsalmon': '#FFA07A',
'lightseagreen': '#20B2AA',
'lightskyblue': '#87CEFA',
'lightslategray': '#778899',
'lightslategrey': '#778899',
'lightsteelblue': '#B0C4DE',
'lightyellow': '#FFFFE0',
'lime': '#00FF00',
'limegreen': '#32CD32',
'linen': '#FAF0E6',
'magenta': '#FF00FF',
'maroon': '#800000',
'mediumaquamarine': '#66CDAA',
'mediumblue': '#0000CD',
'mediumorchid': '#BA55D3',
'mediumpurple': '#9370DB',
'mediumseagreen': '#3CB371',
'mediumslateblue': '#7B68EE',
'mediumspringgreen': '#00FA9A',
'mediumturquoise': '#48D1CC',
'mediumvioletred': '#C71585',
'midnightblue': '#191970',
'mintcream': '#F5FFFA',
'mistyrose': '#FFE4E1',
'moccasin': '#FFE4B5',
'navajowhite': '#FFDEAD',
'navy': '#000080',
'oldlace': '#FDF5E6',
'olive': '#808000',
'olivedrab': '#6B8E23',
'orange': '#FFA500',
'orangered': '#FF4500',
'orchid': '#DA70D6',
'palegoldenrod': '#EEE8AA',
'palegreen': '#98FB98',
'paleturquoise': '#AFEEEE',
'palevioletred': '#DB7093',
'papayawhip': '#FFEFD5',
'peachpuff': '#FFDAB9',
'peru': '#CD853F',
'pink': '#FFC0CB',
'plum': '#DDA0DD',
'powderblue': '#B0E0E6',
'purple': '#800080',
'rebeccapurple': '#663399',
'red': '#FF0000',
'rosybrown': '#BC8F8F',
'royalblue': '#4169E1',
'saddlebrown': '#8B4513',
'salmon': '#FA8072',
'sandybrown': '#F4A460',
'seagreen': '#2E8B57',
'seashell': '#FFF5EE',
'sienna': '#A0522D',
'silver': '#C0C0C0',
'skyblue': '#87CEEB',
'slateblue': '#6A5ACD',
'slategray': '#708090',
'slategrey': '#708090',
'snow': '#FFFAFA',
'springgreen': '#00FF7F',
'steelblue': '#4682B4',
'tan': '#D2B48C',
'teal': '#008080',
'thistle': '#D8BFD8',
'tomato': '#FF6347',
'turquoise': '#40E0D0',
'violet': '#EE82EE',
'wheat': '#F5DEB3',
'white': '#FFFFFF',
'whitesmoke': '#F5F5F5',
'yellow': '#FFFF00',
'yellowgreen': '#9ACD32'}
|
b07030e1614cae5dd3916d6eef5493ca3c878dbb232ed1c18ba75fecf103262c
|
"""
Defines classes for path effects. The path effects are supported in
:class:`~matplotlib.text.Text`, :class:`~matplotlib.lines.Line2D`
and :class:`~matplotlib.patches.Patch`.
"""
from matplotlib.backend_bases import RendererBase
from matplotlib import colors as mcolors
from matplotlib import patches as mpatches
from matplotlib import transforms as mtransforms
class AbstractPathEffect(object):
"""
A base class for path effects.
Subclasses should override the ``draw_path`` method to add effect
functionality.
"""
def __init__(self, offset=(0., 0.)):
"""
Parameters
----------
offset : pair of floats
The offset to apply to the path, measured in points.
"""
self._offset = offset
self._offset_trans = mtransforms.Affine2D()
def _offset_transform(self, renderer, transform):
"""Apply the offset to the given transform."""
offset_x = renderer.points_to_pixels(self._offset[0])
offset_y = renderer.points_to_pixels(self._offset[1])
return transform + self._offset_trans.clear().translate(offset_x,
offset_y)
def _update_gc(self, gc, new_gc_dict):
"""
Update the given GraphicsCollection with the given
dictionary of properties. The keys in the dictionary are used to
identify the appropriate set_ method on the gc.
"""
new_gc_dict = new_gc_dict.copy()
dashes = new_gc_dict.pop("dashes", None)
if dashes:
gc.set_dashes(**dashes)
for k, v in new_gc_dict.items():
set_method = getattr(gc, 'set_' + k, None)
if not callable(set_method):
raise AttributeError('Unknown property {0}'.format(k))
set_method(v)
return gc
def draw_path(self, renderer, gc, tpath, affine, rgbFace=None):
"""
Derived should override this method. The arguments are the same
as :meth:`matplotlib.backend_bases.RendererBase.draw_path`
except the first argument is a renderer.
"""
# Get the real renderer, not a PathEffectRenderer.
if isinstance(renderer, PathEffectRenderer):
renderer = renderer._renderer
return renderer.draw_path(gc, tpath, affine, rgbFace)
class PathEffectRenderer(RendererBase):
"""
Implements a Renderer which contains another renderer.
This proxy then intercepts draw calls, calling the appropriate
:class:`AbstractPathEffect` draw method.
.. note::
Not all methods have been overridden on this RendererBase subclass.
It may be necessary to add further methods to extend the PathEffects
capabilities further.
"""
def __init__(self, path_effects, renderer):
"""
Parameters
----------
path_effects : iterable of :class:`AbstractPathEffect`
The path effects which this renderer represents.
renderer : :class:`matplotlib.backend_bases.RendererBase` instance
"""
self._path_effects = path_effects
self._renderer = renderer
def new_gc(self):
# docstring inherited
return self._renderer.new_gc()
def copy_with_path_effect(self, path_effects):
return self.__class__(path_effects, self._renderer)
def draw_path(self, gc, tpath, affine, rgbFace=None):
for path_effect in self._path_effects:
path_effect.draw_path(self._renderer, gc, tpath, affine,
rgbFace)
def draw_markers(
self, gc, marker_path, marker_trans, path, *args, **kwargs):
# We do a little shimmy so that all markers are drawn for each path
# effect in turn. Essentially, we induce recursion (depth 1) which is
# terminated once we have just a single path effect to work with.
if len(self._path_effects) == 1:
# Call the base path effect function - this uses the unoptimised
# approach of calling "draw_path" multiple times.
return RendererBase.draw_markers(self, gc, marker_path,
marker_trans, path, *args,
**kwargs)
for path_effect in self._path_effects:
renderer = self.copy_with_path_effect([path_effect])
# Recursively call this method, only next time we will only have
# one path effect.
renderer.draw_markers(gc, marker_path, marker_trans, path,
*args, **kwargs)
def draw_path_collection(self, gc, master_transform, paths, *args,
**kwargs):
# We do a little shimmy so that all paths are drawn for each path
# effect in turn. Essentially, we induce recursion (depth 1) which is
# terminated once we have just a single path effect to work with.
if len(self._path_effects) == 1:
# Call the base path effect function - this uses the unoptimised
# approach of calling "draw_path" multiple times.
return RendererBase.draw_path_collection(self, gc,
master_transform, paths,
*args, **kwargs)
for path_effect in self._path_effects:
renderer = self.copy_with_path_effect([path_effect])
# Recursively call this method, only next time we will only have
# one path effect.
renderer.draw_path_collection(gc, master_transform, paths,
*args, **kwargs)
def points_to_pixels(self, points):
# docstring inherited
return self._renderer.points_to_pixels(points)
def _draw_text_as_path(self, gc, x, y, s, prop, angle, ismath):
# Implements the naive text drawing as is found in RendererBase.
path, transform = self._get_text_path_transform(x, y, s, prop,
angle, ismath)
color = gc.get_rgb()
gc.set_linewidth(0.0)
self.draw_path(gc, path, transform, rgbFace=color)
def __getattribute__(self, name):
if name in ['_text2path', 'flipy', 'height', 'width']:
return getattr(self._renderer, name)
else:
return object.__getattribute__(self, name)
class Normal(AbstractPathEffect):
"""
The "identity" PathEffect.
The Normal PathEffect's sole purpose is to draw the original artist with
no special path effect.
"""
pass
class Stroke(AbstractPathEffect):
"""A line based PathEffect which re-draws a stroke."""
def __init__(self, offset=(0, 0), **kwargs):
"""
The path will be stroked with its gc updated with the given
keyword arguments, i.e., the keyword arguments should be valid
gc parameter values.
"""
super().__init__(offset)
self._gc = kwargs
def draw_path(self, renderer, gc, tpath, affine, rgbFace):
"""
draw the path with updated gc.
"""
# Do not modify the input! Use copy instead.
gc0 = renderer.new_gc()
gc0.copy_properties(gc)
gc0 = self._update_gc(gc0, self._gc)
trans = self._offset_transform(renderer, affine)
renderer.draw_path(gc0, tpath, trans, rgbFace)
gc0.restore()
class withStroke(Stroke):
"""
Adds a simple :class:`Stroke` and then draws the
original Artist to avoid needing to call :class:`Normal`.
"""
def draw_path(self, renderer, gc, tpath, affine, rgbFace):
Stroke.draw_path(self, renderer, gc, tpath, affine, rgbFace)
renderer.draw_path(gc, tpath, affine, rgbFace)
class SimplePatchShadow(AbstractPathEffect):
"""A simple shadow via a filled patch."""
def __init__(self, offset=(2, -2),
shadow_rgbFace=None, alpha=None,
rho=0.3, **kwargs):
"""
Parameters
----------
offset : pair of floats
The offset of the shadow in points.
shadow_rgbFace : color
The shadow color.
alpha : float
The alpha transparency of the created shadow patch.
Default is 0.3.
http://matplotlib.1069221.n5.nabble.com/path-effects-question-td27630.html
rho : float
A scale factor to apply to the rgbFace color if `shadow_rgbFace`
is not specified. Default is 0.3.
**kwargs
Extra keywords are stored and passed through to
:meth:`AbstractPathEffect._update_gc`.
"""
super().__init__(offset)
if shadow_rgbFace is None:
self._shadow_rgbFace = shadow_rgbFace
else:
self._shadow_rgbFace = mcolors.to_rgba(shadow_rgbFace)
if alpha is None:
alpha = 0.3
self._alpha = alpha
self._rho = rho
#: The dictionary of keywords to update the graphics collection with.
self._gc = kwargs
def draw_path(self, renderer, gc, tpath, affine, rgbFace):
"""
Overrides the standard draw_path to add the shadow offset and
necessary color changes for the shadow.
"""
# IMPORTANT: Do not modify the input - we copy everything instead.
affine0 = self._offset_transform(renderer, affine)
gc0 = renderer.new_gc()
gc0.copy_properties(gc)
if self._shadow_rgbFace is None:
r, g, b = (rgbFace or (1., 1., 1.))[:3]
# Scale the colors by a factor to improve the shadow effect.
shadow_rgbFace = (r * self._rho, g * self._rho, b * self._rho)
else:
shadow_rgbFace = self._shadow_rgbFace
gc0.set_foreground("none")
gc0.set_alpha(self._alpha)
gc0.set_linewidth(0)
gc0 = self._update_gc(gc0, self._gc)
renderer.draw_path(gc0, tpath, affine0, shadow_rgbFace)
gc0.restore()
class withSimplePatchShadow(SimplePatchShadow):
"""
Adds a simple :class:`SimplePatchShadow` and then draws the
original Artist to avoid needing to call :class:`Normal`.
"""
def draw_path(self, renderer, gc, tpath, affine, rgbFace):
SimplePatchShadow.draw_path(self, renderer, gc, tpath, affine, rgbFace)
renderer.draw_path(gc, tpath, affine, rgbFace)
class SimpleLineShadow(AbstractPathEffect):
"""A simple shadow via a line."""
def __init__(self, offset=(2, -2),
shadow_color='k', alpha=0.3, rho=0.3, **kwargs):
"""
Parameters
----------
offset : pair of floats
The offset to apply to the path, in points.
shadow_color : color
The shadow color. Default is black.
A value of ``None`` takes the original artist's color
with a scale factor of `rho`.
alpha : float
The alpha transparency of the created shadow patch.
Default is 0.3.
rho : float
A scale factor to apply to the rgbFace color if `shadow_rgbFace`
is ``None``. Default is 0.3.
**kwargs
Extra keywords are stored and passed through to
:meth:`AbstractPathEffect._update_gc`.
"""
super().__init__(offset)
if shadow_color is None:
self._shadow_color = shadow_color
else:
self._shadow_color = mcolors.to_rgba(shadow_color)
self._alpha = alpha
self._rho = rho
#: The dictionary of keywords to update the graphics collection with.
self._gc = kwargs
def draw_path(self, renderer, gc, tpath, affine, rgbFace):
"""
Overrides the standard draw_path to add the shadow offset and
necessary color changes for the shadow.
"""
# IMPORTANT: Do not modify the input - we copy everything instead.
affine0 = self._offset_transform(renderer, affine)
gc0 = renderer.new_gc()
gc0.copy_properties(gc)
if self._shadow_color is None:
r, g, b = (gc0.get_foreground() or (1., 1., 1.))[:3]
# Scale the colors by a factor to improve the shadow effect.
shadow_rgbFace = (r * self._rho, g * self._rho, b * self._rho)
else:
shadow_rgbFace = self._shadow_color
fill_color = None
gc0.set_foreground(shadow_rgbFace)
gc0.set_alpha(self._alpha)
gc0 = self._update_gc(gc0, self._gc)
renderer.draw_path(gc0, tpath, affine0, fill_color)
gc0.restore()
class PathPatchEffect(AbstractPathEffect):
"""
Draws a :class:`~matplotlib.patches.PathPatch` instance whose Path
comes from the original PathEffect artist.
"""
def __init__(self, offset=(0, 0), **kwargs):
"""
Parameters
----------
offset : pair of floats
The offset to apply to the path, in points.
**kwargs
All keyword arguments are passed through to the
:class:`~matplotlib.patches.PathPatch` constructor. The
properties which cannot be overridden are "path", "clip_box"
"transform" and "clip_path".
"""
super().__init__(offset=offset)
self.patch = mpatches.PathPatch([], **kwargs)
def draw_path(self, renderer, gc, tpath, affine, rgbFace):
affine = self._offset_transform(renderer, affine)
self.patch._path = tpath
self.patch.set_transform(affine)
self.patch.set_clip_box(gc.get_clip_rectangle())
clip_path = gc.get_clip_path()
if clip_path:
self.patch.set_clip_path(*clip_path)
self.patch.draw(renderer)
|
7e84469dc76d93c60aabdc3fc7bc11891d10f193d096bbf3ecdebfa22feb3e2f
|
from collections import OrderedDict
import functools
import logging
import urllib.parse
import numpy as np
from matplotlib import cbook, dviread, font_manager, rcParams
from matplotlib.font_manager import FontProperties, get_font
from matplotlib.ft2font import (
KERNING_DEFAULT, LOAD_NO_HINTING, LOAD_TARGET_LIGHT)
from matplotlib.mathtext import MathTextParser
from matplotlib.path import Path
from matplotlib.transforms import Affine2D
_log = logging.getLogger(__name__)
class TextToPath(object):
"""A class that converts strings to paths."""
FONT_SCALE = 100.
DPI = 72
def __init__(self):
self.mathtext_parser = MathTextParser('path')
self._texmanager = None
@property
@cbook.deprecated("3.0")
def tex_font_map(self):
return dviread.PsfontsMap(dviread.find_tex_file('pdftex.map'))
def _get_font(self, prop):
"""
Find the `FT2Font` matching font properties *prop*, with its size set.
"""
fname = font_manager.findfont(prop)
font = get_font(fname)
font.set_size(self.FONT_SCALE, self.DPI)
return font
def _get_hinting_flag(self):
return LOAD_NO_HINTING
def _get_char_id(self, font, ccode):
"""
Return a unique id for the given font and character-code set.
"""
return urllib.parse.quote('{}-{}'.format(font.postscript_name, ccode))
def _get_char_id_ps(self, font, ccode):
"""
Return a unique id for the given font and character-code set (for tex).
"""
ps_name = font.get_ps_font_info()[2]
char_id = urllib.parse.quote('%s-%d' % (ps_name, ccode))
return char_id
@cbook.deprecated(
"3.1",
alternative="font.get_path() and manual translation of the vertices")
def glyph_to_path(self, font, currx=0.):
"""Convert the *font*'s current glyph to a (vertices, codes) pair."""
verts, codes = font.get_path()
if currx != 0.0:
verts[:, 0] += currx
return verts, codes
def get_text_width_height_descent(self, s, prop, ismath):
if rcParams['text.usetex']:
texmanager = self.get_texmanager()
fontsize = prop.get_size_in_points()
w, h, d = texmanager.get_text_width_height_descent(s, fontsize,
renderer=None)
return w, h, d
fontsize = prop.get_size_in_points()
scale = fontsize / self.FONT_SCALE
if ismath:
prop = prop.copy()
prop.set_size(self.FONT_SCALE)
width, height, descent, trash, used_characters = \
self.mathtext_parser.parse(s, 72, prop)
return width * scale, height * scale, descent * scale
font = self._get_font(prop)
font.set_text(s, 0.0, flags=LOAD_NO_HINTING)
w, h = font.get_width_height()
w /= 64.0 # convert from subpixels
h /= 64.0
d = font.get_descent()
d /= 64.0
return w * scale, h * scale, d * scale
@cbook._delete_parameter("3.1", "usetex")
def get_text_path(self, prop, s, ismath=False, usetex=False):
"""
Convert text *s* to path (a tuple of vertices and codes for
matplotlib.path.Path).
Parameters
----------
prop : `matplotlib.font_manager.FontProperties` instance
The font properties for the text.
s : str
The text to be converted.
ismath : {False, True, "TeX"}
If True, use mathtext parser. If "TeX", use tex for renderering.
usetex : bool, optional
If set, forces *ismath* to True. This parameter is deprecated.
Returns
-------
verts, codes : tuple of lists
*verts* is a list of numpy arrays containing the x and y
coordinates of the vertices. *codes* is a list of path codes.
Examples
--------
Create a list of vertices and codes from a text, and create a `Path`
from those::
from matplotlib.path import Path
from matplotlib.textpath import TextToPath
from matplotlib.font_manager import FontProperties
fp = FontProperties(family="Humor Sans", style="italic")
verts, codes = TextToPath().get_text_path(fp, "ABC")
path = Path(verts, codes, closed=False)
Also see `TextPath` for a more direct way to create a path from a text.
"""
if usetex:
ismath = "TeX"
if ismath == "TeX":
glyph_info, glyph_map, rects = self.get_glyphs_tex(prop, s)
elif not ismath:
font = self._get_font(prop)
glyph_info, glyph_map, rects = self.get_glyphs_with_font(font, s)
else:
glyph_info, glyph_map, rects = self.get_glyphs_mathtext(prop, s)
verts, codes = [], []
for glyph_id, xposition, yposition, scale in glyph_info:
verts1, codes1 = glyph_map[glyph_id]
if len(verts1):
verts1 = np.array(verts1) * scale + [xposition, yposition]
verts.extend(verts1)
codes.extend(codes1)
for verts1, codes1 in rects:
verts.extend(verts1)
codes.extend(codes1)
return verts, codes
def get_glyphs_with_font(self, font, s, glyph_map=None,
return_new_glyphs_only=False):
"""
Convert string *s* to vertices and codes using the provided ttf font.
"""
# Mostly copied from backend_svg.py.
lastgind = None
currx = 0
xpositions = []
glyph_ids = []
if glyph_map is None:
glyph_map = OrderedDict()
if return_new_glyphs_only:
glyph_map_new = OrderedDict()
else:
glyph_map_new = glyph_map
# I'm not sure if I get kernings right. Needs to be verified. -JJL
for c in s:
ccode = ord(c)
gind = font.get_char_index(ccode)
if gind is None:
ccode = ord('?')
gind = 0
if lastgind is not None:
kern = font.get_kerning(lastgind, gind, KERNING_DEFAULT)
else:
kern = 0
glyph = font.load_char(ccode, flags=LOAD_NO_HINTING)
horiz_advance = glyph.linearHoriAdvance / 65536
char_id = self._get_char_id(font, ccode)
if char_id not in glyph_map:
glyph_map_new[char_id] = font.get_path()
currx += kern / 64
xpositions.append(currx)
glyph_ids.append(char_id)
currx += horiz_advance
lastgind = gind
ypositions = [0] * len(xpositions)
sizes = [1.] * len(xpositions)
rects = []
return (list(zip(glyph_ids, xpositions, ypositions, sizes)),
glyph_map_new, rects)
def get_glyphs_mathtext(self, prop, s, glyph_map=None,
return_new_glyphs_only=False):
"""
Parse mathtext string *s* and convert it to a (vertices, codes) pair.
"""
prop = prop.copy()
prop.set_size(self.FONT_SCALE)
width, height, descent, glyphs, rects = self.mathtext_parser.parse(
s, self.DPI, prop)
if not glyph_map:
glyph_map = OrderedDict()
if return_new_glyphs_only:
glyph_map_new = OrderedDict()
else:
glyph_map_new = glyph_map
xpositions = []
ypositions = []
glyph_ids = []
sizes = []
for font, fontsize, ccode, ox, oy in glyphs:
char_id = self._get_char_id(font, ccode)
if char_id not in glyph_map:
font.clear()
font.set_size(self.FONT_SCALE, self.DPI)
glyph = font.load_char(ccode, flags=LOAD_NO_HINTING)
glyph_map_new[char_id] = font.get_path()
xpositions.append(ox)
ypositions.append(oy)
glyph_ids.append(char_id)
size = fontsize / self.FONT_SCALE
sizes.append(size)
myrects = []
for ox, oy, w, h in rects:
vert1 = [(ox, oy), (ox, oy + h), (ox + w, oy + h),
(ox + w, oy), (ox, oy), (0, 0)]
code1 = [Path.MOVETO,
Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO,
Path.CLOSEPOLY]
myrects.append((vert1, code1))
return (list(zip(glyph_ids, xpositions, ypositions, sizes)),
glyph_map_new, myrects)
def get_texmanager(self):
"""Return the cached `~.texmanager.TexManager` instance."""
if self._texmanager is None:
from matplotlib.texmanager import TexManager
self._texmanager = TexManager()
return self._texmanager
def get_glyphs_tex(self, prop, s, glyph_map=None,
return_new_glyphs_only=False):
"""Convert the string *s* to vertices and codes using usetex mode."""
# Mostly borrowed from pdf backend.
dvifile = self.get_texmanager().make_dvi(s, self.FONT_SCALE)
with dviread.Dvi(dvifile, self.DPI) as dvi:
page, = dvi
if glyph_map is None:
glyph_map = OrderedDict()
if return_new_glyphs_only:
glyph_map_new = OrderedDict()
else:
glyph_map_new = glyph_map
glyph_ids, xpositions, ypositions, sizes = [], [], [], []
# Gather font information and do some setup for combining
# characters into strings.
for x1, y1, dvifont, glyph, width in page.text:
font, enc = self._get_ps_font_and_encoding(dvifont.texname)
char_id = self._get_char_id_ps(font, glyph)
if char_id not in glyph_map:
font.clear()
font.set_size(self.FONT_SCALE, self.DPI)
# See comments in _get_ps_font_and_encoding.
if enc is not None:
if glyph not in enc:
_log.warning(
"The glyph %d of font %s cannot be converted with "
"the encoding; glyph may be wrong.",
glyph, font.fname)
font.load_char(glyph, flags=LOAD_TARGET_LIGHT)
else:
index = font.get_name_index(enc[glyph])
font.load_glyph(index, flags=LOAD_TARGET_LIGHT)
else:
index = glyph
font.load_char(index, flags=LOAD_TARGET_LIGHT)
glyph_map_new[char_id] = font.get_path()
glyph_ids.append(char_id)
xpositions.append(x1)
ypositions.append(y1)
sizes.append(dvifont.size / self.FONT_SCALE)
myrects = []
for ox, oy, h, w in page.boxes:
vert1 = [(ox, oy), (ox + w, oy), (ox + w, oy + h),
(ox, oy + h), (ox, oy), (0, 0)]
code1 = [Path.MOVETO,
Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO,
Path.CLOSEPOLY]
myrects.append((vert1, code1))
return (list(zip(glyph_ids, xpositions, ypositions, sizes)),
glyph_map_new, myrects)
@staticmethod
@functools.lru_cache(50)
def _get_ps_font_and_encoding(texname):
tex_font_map = dviread.PsfontsMap(dviread.find_tex_file('pdftex.map'))
font_bunch = tex_font_map[texname]
if font_bunch.filename is None:
raise ValueError(
f"No usable font file found for {font_bunch.psname} "
f"({texname}). The font may lack a Type-1 version.")
font = get_font(font_bunch.filename)
if font_bunch.encoding:
# If psfonts.map specifies an encoding, use it: it gives us a
# mapping of glyph indices to Adobe glyph names; use it to convert
# dvi indices to glyph names and use the FreeType-synthesized
# unicode charmap to convert glyph names to glyph indices (with
# FT_Get_Name_Index/get_name_index), and load the glyph using
# FT_Load_Glyph/load_glyph. (That charmap has a coverage at least
# as good as, and possibly better than, the native charmaps.)
enc = dviread._parse_enc(font_bunch.encoding)
else:
# If psfonts.map specifies no encoding, the indices directly
# map to the font's "native" charmap; so don't use the
# FreeType-synthesized charmap but the native ones (we can't
# directly identify it but it's typically an Adobe charmap), and
# directly load the dvi glyph indices using FT_Load_Char/load_char.
for charmap_name, charmap_code in [
("ADOBE_CUSTOM", 1094992451),
("ADOBE_STANDARD", 1094995778),
]:
try:
font.select_charmap(charmap_code)
except (ValueError, RuntimeError):
pass
else:
break
else:
charmap_name = ""
_log.warning("No supported encoding in font (%s).",
font_bunch.filename)
enc = None
return font, enc
text_to_path = TextToPath()
class TextPath(Path):
"""
Create a path from the text.
"""
def __init__(self, xy, s, size=None, prop=None,
_interpolation_steps=1, usetex=False,
*args, **kwargs):
r"""
Create a path from the text. Note that it simply is a path,
not an artist. You need to use the `~.PathPatch` (or other artists)
to draw this path onto the canvas.
Parameters
----------
xy : tuple or array of two float values
Position of the text. For no offset, use ``xy=(0, 0)``.
s : str
The text to convert to a path.
size : float, optional
Font size in points. Defaults to the size specified via the font
properties *prop*.
prop : `matplotlib.font_manager.FontProperties`, optional
Font property. If not provided, will use a default
``FontProperties`` with parameters from the
:ref:`rcParams <matplotlib-rcparams>`.
_interpolation_steps : integer, optional
(Currently ignored)
usetex : bool, optional
Whether to use tex rendering. Defaults to ``False``.
Examples
--------
The following creates a path from the string "ABC" with Helvetica
font face; and another path from the latex fraction 1/2::
from matplotlib.textpath import TextPath
from matplotlib.font_manager import FontProperties
fp = FontProperties(family="Helvetica", style="italic")
path1 = TextPath((12,12), "ABC", size=12, prop=fp)
path2 = TextPath((0,0), r"$\frac{1}{2}$", size=12, usetex=True)
Also see :doc:`/gallery/text_labels_and_annotations/demo_text_path`.
"""
# Circular import.
from matplotlib.text import Text
if args or kwargs:
cbook.warn_deprecated(
"3.1", message="Additional arguments to TextPath used to be "
"ignored, but will trigger a TypeError %(removal)s.")
if prop is None:
prop = FontProperties()
if size is None:
size = prop.get_size_in_points()
self._xy = xy
self.set_size(size)
self._cached_vertices = None
s, ismath = Text(usetex=usetex)._preprocess_math(s)
self._vertices, self._codes = text_to_path.get_text_path(
prop, s, ismath=ismath)
self._should_simplify = False
self._simplify_threshold = rcParams['path.simplify_threshold']
self._interpolation_steps = _interpolation_steps
def set_size(self, size):
"""Set the text size."""
self._size = size
self._invalid = True
def get_size(self):
"""Get the text size."""
return self._size
@property
def vertices(self):
"""
Return the cached path after updating it if necessary.
"""
self._revalidate_path()
return self._cached_vertices
@property
def codes(self):
"""
Return the codes
"""
return self._codes
def _revalidate_path(self):
"""
Update the path if necessary.
The path for the text is initially create with the font size of
`~.FONT_SCALE`, and this path is rescaled to other size when necessary.
"""
if self._invalid or self._cached_vertices is None:
tr = Affine2D().scale(
self._size / text_to_path.FONT_SCALE,
self._size / text_to_path.FONT_SCALE).translate(*self._xy)
self._cached_vertices = tr.transform(self._vertices)
self._invalid = False
@cbook.deprecated("3.1")
def is_math_text(self, s):
"""
Returns True if the given string *s* contains any mathtext.
"""
# copied from Text.is_math_text -JJL
# Did we find an even number of non-escaped dollar signs?
# If so, treat is as math text.
dollar_count = s.count(r'$') - s.count(r'\$')
even_dollars = (dollar_count > 0 and dollar_count % 2 == 0)
if rcParams['text.usetex']:
return s, 'TeX'
if even_dollars:
return s, True
else:
return s.replace(r'\$', '$'), False
@cbook.deprecated("3.1", alternative="TextPath")
def text_get_vertices_codes(self, prop, s, usetex):
"""
Convert string *s* to a (vertices, codes) pair using font property
*prop*.
"""
# Mostly copied from backend_svg.py.
if usetex:
return text_to_path.get_text_path(prop, s, usetex=True)
else:
clean_line, ismath = self.is_math_text(s)
return text_to_path.get_text_path(prop, clean_line, ismath=ismath)
|
c92d69fa8b3019c8ada86a7768eed3c67d2ad78e238e30485c715847ebe50980
|
"""
This module provides routines to adjust subplot params so that subplots are
nicely fit in the figure. In doing so, only axis labels, tick labels, axes
titles and offsetboxes that are anchored to axes are currently considered.
Internally, it assumes that the margins (left_margin, etc.) which are
differences between ax.get_tightbbox and ax.bbox are independent of axes
position. This may fail if Axes.adjustable is datalim. Also, This will fail
for some cases (for example, left or right margin is affected by xlabel).
"""
from matplotlib import cbook, rcParams
from matplotlib.font_manager import FontProperties
from matplotlib.transforms import TransformedBbox, Bbox
def _get_left(tight_bbox, axes_bbox):
return axes_bbox.xmin - tight_bbox.xmin
def _get_right(tight_bbox, axes_bbox):
return tight_bbox.xmax - axes_bbox.xmax
def _get_bottom(tight_bbox, axes_bbox):
return axes_bbox.ymin - tight_bbox.ymin
def _get_top(tight_bbox, axes_bbox):
return tight_bbox.ymax - axes_bbox.ymax
def auto_adjust_subplotpars(
fig, renderer, nrows_ncols, num1num2_list, subplot_list,
ax_bbox_list=None, pad=1.08, h_pad=None, w_pad=None, rect=None):
"""
Return a dict of subplot parameters to adjust spacing between subplots
or ``None`` if resulting axes would have zero height or width.
Note that this function ignores geometry information of subplot
itself, but uses what is given by the *nrows_ncols* and *num1num2_list*
parameters. Also, the results could be incorrect if some subplots have
``adjustable=datalim``.
Parameters
----------
nrows_ncols : Tuple[int, int]
Number of rows and number of columns of the grid.
num1num2_list : List[int]
List of numbers specifying the area occupied by the subplot
subplot_list : list of subplots
List of subplots that will be used to calculate optimal subplot_params.
pad : float
Padding between the figure edge and the edges of subplots, as a
fraction of the font size.
h_pad, w_pad : float
Padding (height/width) between edges of adjacent subplots, as a
fraction of the font size. Defaults to *pad*.
rect : Tuple[float, float, float, float]
[left, bottom, right, top] in normalized (0, 1) figure coordinates.
"""
rows, cols = nrows_ncols
font_size_inches = (
FontProperties(size=rcParams["font.size"]).get_size_in_points() / 72)
pad_inches = pad * font_size_inches
if h_pad is not None:
vpad_inches = h_pad * font_size_inches
else:
vpad_inches = pad_inches
if w_pad is not None:
hpad_inches = w_pad * font_size_inches
else:
hpad_inches = pad_inches
if len(num1num2_list) != len(subplot_list) or len(subplot_list) == 0:
raise ValueError
if rect is None:
margin_left = margin_bottom = margin_right = margin_top = None
else:
margin_left, margin_bottom, _right, _top = rect
if _right:
margin_right = 1 - _right
else:
margin_right = None
if _top:
margin_top = 1 - _top
else:
margin_top = None
vspaces = [[] for i in range((rows + 1) * cols)]
hspaces = [[] for i in range(rows * (cols + 1))]
union = Bbox.union
if ax_bbox_list is None:
ax_bbox_list = []
for subplots in subplot_list:
ax_bbox = union([ax.get_position(original=True)
for ax in subplots])
ax_bbox_list.append(ax_bbox)
for subplots, ax_bbox, (num1, num2) in zip(subplot_list,
ax_bbox_list,
num1num2_list):
if all(not ax.get_visible() for ax in subplots):
continue
tight_bbox_raw = union([ax.get_tightbbox(renderer) for ax in subplots
if ax.get_visible()])
tight_bbox = TransformedBbox(tight_bbox_raw,
fig.transFigure.inverted())
row1, col1 = divmod(num1, cols)
if num2 is None:
# left
hspaces[row1 * (cols + 1) + col1].append(
_get_left(tight_bbox, ax_bbox))
# right
hspaces[row1 * (cols + 1) + (col1 + 1)].append(
_get_right(tight_bbox, ax_bbox))
# top
vspaces[row1 * cols + col1].append(
_get_top(tight_bbox, ax_bbox))
# bottom
vspaces[(row1 + 1) * cols + col1].append(
_get_bottom(tight_bbox, ax_bbox))
else:
row2, col2 = divmod(num2, cols)
for row_i in range(row1, row2 + 1):
# left
hspaces[row_i * (cols + 1) + col1].append(
_get_left(tight_bbox, ax_bbox))
# right
hspaces[row_i * (cols + 1) + (col2 + 1)].append(
_get_right(tight_bbox, ax_bbox))
for col_i in range(col1, col2 + 1):
# top
vspaces[row1 * cols + col_i].append(
_get_top(tight_bbox, ax_bbox))
# bottom
vspaces[(row2 + 1) * cols + col_i].append(
_get_bottom(tight_bbox, ax_bbox))
fig_width_inch, fig_height_inch = fig.get_size_inches()
# margins can be negative for axes with aspect applied. And we
# append + [0] to make minimum margins 0
if not margin_left:
margin_left = max([sum(s) for s in hspaces[::cols + 1]] + [0])
margin_left += pad_inches / fig_width_inch
if not margin_right:
margin_right = max([sum(s) for s in hspaces[cols::cols + 1]] + [0])
margin_right += pad_inches / fig_width_inch
if not margin_top:
margin_top = max([sum(s) for s in vspaces[:cols]] + [0])
margin_top += pad_inches / fig_height_inch
if not margin_bottom:
margin_bottom = max([sum(s) for s in vspaces[-cols:]] + [0])
margin_bottom += pad_inches / fig_height_inch
if margin_left + margin_right >= 1:
cbook._warn_external('Tight layout not applied. The left and right '
'margins cannot be made large enough to '
'accommodate all axes decorations. ')
return None
if margin_bottom + margin_top >= 1:
cbook._warn_external('Tight layout not applied. The bottom and top '
'margins cannot be made large enough to '
'accommodate all axes decorations. ')
return None
kwargs = dict(left=margin_left,
right=1 - margin_right,
bottom=margin_bottom,
top=1 - margin_top)
if cols > 1:
hspace = (
max(sum(s)
for i in range(rows)
for s in hspaces[i * (cols + 1) + 1:(i + 1) * (cols + 1) - 1])
+ hpad_inches / fig_width_inch)
# axes widths:
h_axes = (1 - margin_right - margin_left - hspace * (cols - 1)) / cols
if h_axes < 0:
cbook._warn_external('Tight layout not applied. tight_layout '
'cannot make axes width small enough to '
'accommodate all axes decorations')
return None
else:
kwargs["wspace"] = hspace / h_axes
if rows > 1:
vspace = (max(sum(s) for s in vspaces[cols:-cols])
+ vpad_inches / fig_height_inch)
v_axes = (1 - margin_top - margin_bottom - vspace * (rows - 1)) / rows
if v_axes < 0:
cbook._warn_external('Tight layout not applied. tight_layout '
'cannot make axes height small enough to '
'accommodate all axes decorations')
return None
else:
kwargs["hspace"] = vspace / v_axes
return kwargs
def get_renderer(fig):
if fig._cachedRenderer:
renderer = fig._cachedRenderer
else:
canvas = fig.canvas
if canvas and hasattr(canvas, "get_renderer"):
renderer = canvas.get_renderer()
else:
# not sure if this can happen
cbook._warn_external("tight_layout : falling back to Agg renderer")
from matplotlib.backends.backend_agg import FigureCanvasAgg
canvas = FigureCanvasAgg(fig)
renderer = canvas.get_renderer()
return renderer
def get_subplotspec_list(axes_list, grid_spec=None):
"""Return a list of subplotspec from the given list of axes.
For an instance of axes that does not support subplotspec, None is inserted
in the list.
If grid_spec is given, None is inserted for those not from the given
grid_spec.
"""
subplotspec_list = []
for ax in axes_list:
axes_or_locator = ax.get_axes_locator()
if axes_or_locator is None:
axes_or_locator = ax
if hasattr(axes_or_locator, "get_subplotspec"):
subplotspec = axes_or_locator.get_subplotspec()
subplotspec = subplotspec.get_topmost_subplotspec()
gs = subplotspec.get_gridspec()
if grid_spec is not None:
if gs != grid_spec:
subplotspec = None
elif gs.locally_modified_subplot_params():
subplotspec = None
else:
subplotspec = None
subplotspec_list.append(subplotspec)
return subplotspec_list
def get_tight_layout_figure(fig, axes_list, subplotspec_list, renderer,
pad=1.08, h_pad=None, w_pad=None, rect=None):
"""
Return subplot parameters for tight-layouted-figure with specified padding.
Parameters
----------
fig : Figure
axes_list : list of Axes
subplotspec_list : list of `.SubplotSpec`
The subplotspecs of each axes.
renderer : renderer
pad : float
Padding between the figure edge and the edges of subplots, as a
fraction of the font size.
h_pad, w_pad : float
Padding (height/width) between edges of adjacent subplots. Defaults to
*pad_inches*.
rect : Tuple[float, float, float, float], optional
(left, bottom, right, top) rectangle in normalized figure coordinates
that the whole subplots area (including labels) will fit into.
Defaults to using the entire figure.
Returns
-------
subplotspec or None
subplotspec kwargs to be passed to `.Figure.subplots_adjust` or
None if tight_layout could not be accomplished.
"""
subplot_list = []
nrows_list = []
ncols_list = []
ax_bbox_list = []
subplot_dict = {} # Multiple axes can share same subplot_interface (e.g.,
# axes_grid1); thus we need to join them together.
subplotspec_list2 = []
for ax, subplotspec in zip(axes_list, subplotspec_list):
if subplotspec is None:
continue
subplots = subplot_dict.setdefault(subplotspec, [])
if not subplots:
myrows, mycols, _, _ = subplotspec.get_geometry()
nrows_list.append(myrows)
ncols_list.append(mycols)
subplotspec_list2.append(subplotspec)
subplot_list.append(subplots)
ax_bbox_list.append(subplotspec.get_position(fig))
subplots.append(ax)
if len(nrows_list) == 0 or len(ncols_list) == 0:
return {}
max_nrows = max(nrows_list)
max_ncols = max(ncols_list)
num1num2_list = []
for subplotspec in subplotspec_list2:
rows, cols, num1, num2 = subplotspec.get_geometry()
div_row, mod_row = divmod(max_nrows, rows)
div_col, mod_col = divmod(max_ncols, cols)
if mod_row != 0:
cbook._warn_external('tight_layout not applied: number of rows '
'in subplot specifications must be '
'multiples of one another.')
return {}
if mod_col != 0:
cbook._warn_external('tight_layout not applied: number of '
'columns in subplot specifications must be '
'multiples of one another.')
return {}
rowNum1, colNum1 = divmod(num1, cols)
if num2 is None:
rowNum2, colNum2 = rowNum1, colNum1
else:
rowNum2, colNum2 = divmod(num2, cols)
num1num2_list.append((rowNum1 * div_row * max_ncols +
colNum1 * div_col,
((rowNum2 + 1) * div_row - 1) * max_ncols +
(colNum2 + 1) * div_col - 1))
kwargs = auto_adjust_subplotpars(fig, renderer,
nrows_ncols=(max_nrows, max_ncols),
num1num2_list=num1num2_list,
subplot_list=subplot_list,
ax_bbox_list=ax_bbox_list,
pad=pad, h_pad=h_pad, w_pad=w_pad)
# kwargs can be none if tight_layout fails...
if rect is not None and kwargs is not None:
# if rect is given, the whole subplots area (including
# labels) will fit into the rect instead of the
# figure. Note that the rect argument of
# *auto_adjust_subplotpars* specify the area that will be
# covered by the total area of axes.bbox. Thus we call
# auto_adjust_subplotpars twice, where the second run
# with adjusted rect parameters.
left, bottom, right, top = rect
if left is not None:
left += kwargs["left"]
if bottom is not None:
bottom += kwargs["bottom"]
if right is not None:
right -= (1 - kwargs["right"])
if top is not None:
top -= (1 - kwargs["top"])
kwargs = auto_adjust_subplotpars(fig, renderer,
nrows_ncols=(max_nrows, max_ncols),
num1num2_list=num1num2_list,
subplot_list=subplot_list,
ax_bbox_list=ax_bbox_list,
pad=pad, h_pad=h_pad, w_pad=w_pad,
rect=(left, bottom, right, top))
return kwargs
|
30ba75febc2c4d4a2eacb28256c68762aee431b17b3903c0f616f967faa760b9
|
"""
Streamline plotting for 2D vector fields.
"""
import numpy as np
import matplotlib
import matplotlib.cm as cm
import matplotlib.colors as mcolors
import matplotlib.collections as mcollections
import matplotlib.lines as mlines
import matplotlib.patches as patches
__all__ = ['streamplot']
def streamplot(axes, x, y, u, v, density=1, linewidth=None, color=None,
cmap=None, norm=None, arrowsize=1, arrowstyle='-|>',
minlength=0.1, transform=None, zorder=None, start_points=None,
maxlength=4.0, integration_direction='both'):
"""
Draw streamlines of a vector flow.
Parameters
----------
x, y : 1d arrays
An evenly spaced grid.
u, v : 2d arrays
*x* and *y*-velocities. Number of rows should match length of *y*, and
the number of columns should match *x*.
density : float or 2-tuple
Controls the closeness of streamlines. When ``density = 1``, the domain
is divided into a 30x30 grid---*density* linearly scales this grid.
Each cell in the grid can have, at most, one traversing streamline.
For different densities in each direction, use [density_x, density_y].
linewidth : numeric or 2d array
Vary linewidth when given a 2d array with the same shape as velocities.
color : matplotlib color code, or 2d array
Streamline color. When given an array with the same shape as
velocities, *color* values are converted to colors using *cmap*.
cmap : `~matplotlib.colors.Colormap`
Colormap used to plot streamlines and arrows. Only necessary when using
an array input for *color*.
norm : `~matplotlib.colors.Normalize`
Normalize object used to scale luminance data to 0, 1. If ``None``,
stretch (min, max) to (0, 1). Only necessary when *color* is an array.
arrowsize : float
Factor scale arrow size.
arrowstyle : str
Arrow style specification.
See `~matplotlib.patches.FancyArrowPatch`.
minlength : float
Minimum length of streamline in axes coordinates.
start_points : Nx2 array
Coordinates of starting points for the streamlines.
In data coordinates, the same as the *x* and *y* arrays.
zorder : int
Any number.
maxlength : float
Maximum length of streamline in axes coordinates.
integration_direction : ['forward' | 'backward' | 'both']
Integrate the streamline in forward, backward or both directions.
default is ``'both'``.
Returns
-------
stream_container : StreamplotSet
Container object with attributes
- lines: `matplotlib.collections.LineCollection` of streamlines
- arrows: collection of `matplotlib.patches.FancyArrowPatch`
objects representing arrows half-way along stream
lines.
This container will probably change in the future to allow changes
to the colormap, alpha, etc. for both lines and arrows, but these
changes should be backward compatible.
"""
grid = Grid(x, y)
mask = StreamMask(density)
dmap = DomainMap(grid, mask)
if zorder is None:
zorder = mlines.Line2D.zorder
# default to data coordinates
if transform is None:
transform = axes.transData
if color is None:
color = axes._get_lines.get_next_color()
if linewidth is None:
linewidth = matplotlib.rcParams['lines.linewidth']
line_kw = {}
arrow_kw = dict(arrowstyle=arrowstyle, mutation_scale=10 * arrowsize)
if integration_direction not in ['both', 'forward', 'backward']:
errstr = ("Integration direction '%s' not recognised. "
"Expected 'both', 'forward' or 'backward'." %
integration_direction)
raise ValueError(errstr)
if integration_direction == 'both':
maxlength /= 2.
use_multicolor_lines = isinstance(color, np.ndarray)
if use_multicolor_lines:
if color.shape != grid.shape:
raise ValueError(
"If 'color' is given, must have the shape of 'Grid(x,y)'")
line_colors = []
color = np.ma.masked_invalid(color)
else:
line_kw['color'] = color
arrow_kw['color'] = color
if isinstance(linewidth, np.ndarray):
if linewidth.shape != grid.shape:
raise ValueError(
"If 'linewidth' is given, must have the shape of 'Grid(x,y)'")
line_kw['linewidth'] = []
else:
line_kw['linewidth'] = linewidth
arrow_kw['linewidth'] = linewidth
line_kw['zorder'] = zorder
arrow_kw['zorder'] = zorder
## Sanity checks.
if u.shape != grid.shape or v.shape != grid.shape:
raise ValueError("'u' and 'v' must be of shape 'Grid(x,y)'")
u = np.ma.masked_invalid(u)
v = np.ma.masked_invalid(v)
integrate = get_integrator(u, v, dmap, minlength, maxlength,
integration_direction)
trajectories = []
if start_points is None:
for xm, ym in _gen_starting_points(mask.shape):
if mask[ym, xm] == 0:
xg, yg = dmap.mask2grid(xm, ym)
t = integrate(xg, yg)
if t is not None:
trajectories.append(t)
else:
sp2 = np.asanyarray(start_points, dtype=float).copy()
# Check if start_points are outside the data boundaries
for xs, ys in sp2:
if not (grid.x_origin <= xs <= grid.x_origin + grid.width
and grid.y_origin <= ys <= grid.y_origin + grid.height):
raise ValueError("Starting point ({}, {}) outside of data "
"boundaries".format(xs, ys))
# Convert start_points from data to array coords
# Shift the seed points from the bottom left of the data so that
# data2grid works properly.
sp2[:, 0] -= grid.x_origin
sp2[:, 1] -= grid.y_origin
for xs, ys in sp2:
xg, yg = dmap.data2grid(xs, ys)
t = integrate(xg, yg)
if t is not None:
trajectories.append(t)
if use_multicolor_lines:
if norm is None:
norm = mcolors.Normalize(color.min(), color.max())
if cmap is None:
cmap = cm.get_cmap(matplotlib.rcParams['image.cmap'])
else:
cmap = cm.get_cmap(cmap)
streamlines = []
arrows = []
for t in trajectories:
tgx = np.array(t[0])
tgy = np.array(t[1])
# Rescale from grid-coordinates to data-coordinates.
tx, ty = dmap.grid2data(*np.array(t))
tx += grid.x_origin
ty += grid.y_origin
points = np.transpose([tx, ty]).reshape(-1, 1, 2)
streamlines.extend(np.hstack([points[:-1], points[1:]]))
# Add arrows half way along each trajectory.
s = np.cumsum(np.hypot(np.diff(tx), np.diff(ty)))
n = np.searchsorted(s, s[-1] / 2.)
arrow_tail = (tx[n], ty[n])
arrow_head = (np.mean(tx[n:n + 2]), np.mean(ty[n:n + 2]))
if isinstance(linewidth, np.ndarray):
line_widths = interpgrid(linewidth, tgx, tgy)[:-1]
line_kw['linewidth'].extend(line_widths)
arrow_kw['linewidth'] = line_widths[n]
if use_multicolor_lines:
color_values = interpgrid(color, tgx, tgy)[:-1]
line_colors.append(color_values)
arrow_kw['color'] = cmap(norm(color_values[n]))
p = patches.FancyArrowPatch(
arrow_tail, arrow_head, transform=transform, **arrow_kw)
axes.add_patch(p)
arrows.append(p)
lc = mcollections.LineCollection(
streamlines, transform=transform, **line_kw)
lc.sticky_edges.x[:] = [grid.x_origin, grid.x_origin + grid.width]
lc.sticky_edges.y[:] = [grid.y_origin, grid.y_origin + grid.height]
if use_multicolor_lines:
lc.set_array(np.ma.hstack(line_colors))
lc.set_cmap(cmap)
lc.set_norm(norm)
axes.add_collection(lc)
axes.autoscale_view()
ac = matplotlib.collections.PatchCollection(arrows)
stream_container = StreamplotSet(lc, ac)
return stream_container
class StreamplotSet(object):
def __init__(self, lines, arrows, **kwargs):
self.lines = lines
self.arrows = arrows
# Coordinate definitions
# ========================
class DomainMap(object):
"""Map representing different coordinate systems.
Coordinate definitions:
* axes-coordinates goes from 0 to 1 in the domain.
* data-coordinates are specified by the input x-y coordinates.
* grid-coordinates goes from 0 to N and 0 to M for an N x M grid,
where N and M match the shape of the input data.
* mask-coordinates goes from 0 to N and 0 to M for an N x M mask,
where N and M are user-specified to control the density of streamlines.
This class also has methods for adding trajectories to the StreamMask.
Before adding a trajectory, run `start_trajectory` to keep track of regions
crossed by a given trajectory. Later, if you decide the trajectory is bad
(e.g., if the trajectory is very short) just call `undo_trajectory`.
"""
def __init__(self, grid, mask):
self.grid = grid
self.mask = mask
# Constants for conversion between grid- and mask-coordinates
self.x_grid2mask = (mask.nx - 1) / grid.nx
self.y_grid2mask = (mask.ny - 1) / grid.ny
self.x_mask2grid = 1. / self.x_grid2mask
self.y_mask2grid = 1. / self.y_grid2mask
self.x_data2grid = 1. / grid.dx
self.y_data2grid = 1. / grid.dy
def grid2mask(self, xi, yi):
"""Return nearest space in mask-coords from given grid-coords."""
return (int(xi * self.x_grid2mask + 0.5),
int(yi * self.y_grid2mask + 0.5))
def mask2grid(self, xm, ym):
return xm * self.x_mask2grid, ym * self.y_mask2grid
def data2grid(self, xd, yd):
return xd * self.x_data2grid, yd * self.y_data2grid
def grid2data(self, xg, yg):
return xg / self.x_data2grid, yg / self.y_data2grid
def start_trajectory(self, xg, yg):
xm, ym = self.grid2mask(xg, yg)
self.mask._start_trajectory(xm, ym)
def reset_start_point(self, xg, yg):
xm, ym = self.grid2mask(xg, yg)
self.mask._current_xy = (xm, ym)
def update_trajectory(self, xg, yg):
if not self.grid.within_grid(xg, yg):
raise InvalidIndexError
xm, ym = self.grid2mask(xg, yg)
self.mask._update_trajectory(xm, ym)
def undo_trajectory(self):
self.mask._undo_trajectory()
class Grid(object):
"""Grid of data."""
def __init__(self, x, y):
if x.ndim == 1:
pass
elif x.ndim == 2:
x_row = x[0, :]
if not np.allclose(x_row, x):
raise ValueError("The rows of 'x' must be equal")
x = x_row
else:
raise ValueError("'x' can have at maximum 2 dimensions")
if y.ndim == 1:
pass
elif y.ndim == 2:
y_col = y[:, 0]
if not np.allclose(y_col, y.T):
raise ValueError("The columns of 'y' must be equal")
y = y_col
else:
raise ValueError("'y' can have at maximum 2 dimensions")
self.nx = len(x)
self.ny = len(y)
self.dx = x[1] - x[0]
self.dy = y[1] - y[0]
self.x_origin = x[0]
self.y_origin = y[0]
self.width = x[-1] - x[0]
self.height = y[-1] - y[0]
if not np.allclose(np.diff(x), self.width / (self.nx - 1)):
raise ValueError("'x' values must be equally spaced")
if not np.allclose(np.diff(y), self.height / (self.ny - 1)):
raise ValueError("'y' values must be equally spaced")
@property
def shape(self):
return self.ny, self.nx
def within_grid(self, xi, yi):
"""Return True if point is a valid index of grid."""
# Note that xi/yi can be floats; so, for example, we can't simply check
# `xi < self.nx` since `xi` can be `self.nx - 1 < xi < self.nx`
return xi >= 0 and xi <= self.nx - 1 and yi >= 0 and yi <= self.ny - 1
class StreamMask(object):
"""Mask to keep track of discrete regions crossed by streamlines.
The resolution of this grid determines the approximate spacing between
trajectories. Streamlines are only allowed to pass through zeroed cells:
When a streamline enters a cell, that cell is set to 1, and no new
streamlines are allowed to enter.
"""
def __init__(self, density):
try:
self.nx, self.ny = (30 * np.broadcast_to(density, 2)).astype(int)
except ValueError:
raise ValueError("'density' must be a scalar or be of length 2")
if self.nx < 0 or self.ny < 0:
raise ValueError("'density' must be positive")
self._mask = np.zeros((self.ny, self.nx))
self.shape = self._mask.shape
self._current_xy = None
def __getitem__(self, *args):
return self._mask.__getitem__(*args)
def _start_trajectory(self, xm, ym):
"""Start recording streamline trajectory"""
self._traj = []
self._update_trajectory(xm, ym)
def _undo_trajectory(self):
"""Remove current trajectory from mask"""
for t in self._traj:
self._mask.__setitem__(t, 0)
def _update_trajectory(self, xm, ym):
"""Update current trajectory position in mask.
If the new position has already been filled, raise `InvalidIndexError`.
"""
if self._current_xy != (xm, ym):
if self[ym, xm] == 0:
self._traj.append((ym, xm))
self._mask[ym, xm] = 1
self._current_xy = (xm, ym)
else:
raise InvalidIndexError
class InvalidIndexError(Exception):
pass
class TerminateTrajectory(Exception):
pass
# Integrator definitions
#========================
def get_integrator(u, v, dmap, minlength, maxlength, integration_direction):
# rescale velocity onto grid-coordinates for integrations.
u, v = dmap.data2grid(u, v)
# speed (path length) will be in axes-coordinates
u_ax = u / dmap.grid.nx
v_ax = v / dmap.grid.ny
speed = np.ma.sqrt(u_ax ** 2 + v_ax ** 2)
def forward_time(xi, yi):
ds_dt = interpgrid(speed, xi, yi)
if ds_dt == 0:
raise TerminateTrajectory()
dt_ds = 1. / ds_dt
ui = interpgrid(u, xi, yi)
vi = interpgrid(v, xi, yi)
return ui * dt_ds, vi * dt_ds
def backward_time(xi, yi):
dxi, dyi = forward_time(xi, yi)
return -dxi, -dyi
def integrate(x0, y0):
"""Return x, y grid-coordinates of trajectory based on starting point.
Integrate both forward and backward in time from starting point in
grid coordinates.
Integration is terminated when a trajectory reaches a domain boundary
or when it crosses into an already occupied cell in the StreamMask. The
resulting trajectory is None if it is shorter than `minlength`.
"""
stotal, x_traj, y_traj = 0., [], []
try:
dmap.start_trajectory(x0, y0)
except InvalidIndexError:
return None
if integration_direction in ['both', 'backward']:
s, xt, yt = _integrate_rk12(x0, y0, dmap, backward_time, maxlength)
stotal += s
x_traj += xt[::-1]
y_traj += yt[::-1]
if integration_direction in ['both', 'forward']:
dmap.reset_start_point(x0, y0)
s, xt, yt = _integrate_rk12(x0, y0, dmap, forward_time, maxlength)
if len(x_traj) > 0:
xt = xt[1:]
yt = yt[1:]
stotal += s
x_traj += xt
y_traj += yt
if stotal > minlength:
return x_traj, y_traj
else: # reject short trajectories
dmap.undo_trajectory()
return None
return integrate
def _integrate_rk12(x0, y0, dmap, f, maxlength):
"""2nd-order Runge-Kutta algorithm with adaptive step size.
This method is also referred to as the improved Euler's method, or Heun's
method. This method is favored over higher-order methods because:
1. To get decent looking trajectories and to sample every mask cell
on the trajectory we need a small timestep, so a lower order
solver doesn't hurt us unless the data is *very* high resolution.
In fact, for cases where the user inputs
data smaller or of similar grid size to the mask grid, the higher
order corrections are negligible because of the very fast linear
interpolation used in `interpgrid`.
2. For high resolution input data (i.e. beyond the mask
resolution), we must reduce the timestep. Therefore, an adaptive
timestep is more suited to the problem as this would be very hard
to judge automatically otherwise.
This integrator is about 1.5 - 2x as fast as both the RK4 and RK45
solvers in most setups on my machine. I would recommend removing the
other two to keep things simple.
"""
# This error is below that needed to match the RK4 integrator. It
# is set for visual reasons -- too low and corners start
# appearing ugly and jagged. Can be tuned.
maxerror = 0.003
# This limit is important (for all integrators) to avoid the
# trajectory skipping some mask cells. We could relax this
# condition if we use the code which is commented out below to
# increment the location gradually. However, due to the efficient
# nature of the interpolation, this doesn't boost speed by much
# for quite a bit of complexity.
maxds = min(1. / dmap.mask.nx, 1. / dmap.mask.ny, 0.1)
ds = maxds
stotal = 0
xi = x0
yi = y0
xf_traj = []
yf_traj = []
while dmap.grid.within_grid(xi, yi):
xf_traj.append(xi)
yf_traj.append(yi)
try:
k1x, k1y = f(xi, yi)
k2x, k2y = f(xi + ds * k1x,
yi + ds * k1y)
except IndexError:
# Out of the domain on one of the intermediate integration steps.
# Take an Euler step to the boundary to improve neatness.
ds, xf_traj, yf_traj = _euler_step(xf_traj, yf_traj, dmap, f)
stotal += ds
break
except TerminateTrajectory:
break
dx1 = ds * k1x
dy1 = ds * k1y
dx2 = ds * 0.5 * (k1x + k2x)
dy2 = ds * 0.5 * (k1y + k2y)
nx, ny = dmap.grid.shape
# Error is normalized to the axes coordinates
error = np.hypot((dx2 - dx1) / nx, (dy2 - dy1) / ny)
# Only save step if within error tolerance
if error < maxerror:
xi += dx2
yi += dy2
try:
dmap.update_trajectory(xi, yi)
except InvalidIndexError:
break
if stotal + ds > maxlength:
break
stotal += ds
# recalculate stepsize based on step error
if error == 0:
ds = maxds
else:
ds = min(maxds, 0.85 * ds * (maxerror / error) ** 0.5)
return stotal, xf_traj, yf_traj
def _euler_step(xf_traj, yf_traj, dmap, f):
"""Simple Euler integration step that extends streamline to boundary."""
ny, nx = dmap.grid.shape
xi = xf_traj[-1]
yi = yf_traj[-1]
cx, cy = f(xi, yi)
if cx == 0:
dsx = np.inf
elif cx < 0:
dsx = xi / -cx
else:
dsx = (nx - 1 - xi) / cx
if cy == 0:
dsy = np.inf
elif cy < 0:
dsy = yi / -cy
else:
dsy = (ny - 1 - yi) / cy
ds = min(dsx, dsy)
xf_traj.append(xi + cx * ds)
yf_traj.append(yi + cy * ds)
return ds, xf_traj, yf_traj
# Utility functions
# ========================
def interpgrid(a, xi, yi):
"""Fast 2D, linear interpolation on an integer grid"""
Ny, Nx = np.shape(a)
if isinstance(xi, np.ndarray):
x = xi.astype(int)
y = yi.astype(int)
# Check that xn, yn don't exceed max index
xn = np.clip(x + 1, 0, Nx - 1)
yn = np.clip(y + 1, 0, Ny - 1)
else:
x = int(xi)
y = int(yi)
# conditional is faster than clipping for integers
if x == (Nx - 1):
xn = x
else:
xn = x + 1
if y == (Ny - 1):
yn = y
else:
yn = y + 1
a00 = a[y, x]
a01 = a[y, xn]
a10 = a[yn, x]
a11 = a[yn, xn]
xt = xi - x
yt = yi - y
a0 = a00 * (1 - xt) + a01 * xt
a1 = a10 * (1 - xt) + a11 * xt
ai = a0 * (1 - yt) + a1 * yt
if not isinstance(xi, np.ndarray):
if np.ma.is_masked(ai):
raise TerminateTrajectory
return ai
def _gen_starting_points(shape):
"""Yield starting points for streamlines.
Trying points on the boundary first gives higher quality streamlines.
This algorithm starts with a point on the mask corner and spirals inward.
This algorithm is inefficient, but fast compared to rest of streamplot.
"""
ny, nx = shape
xfirst = 0
yfirst = 1
xlast = nx - 1
ylast = ny - 1
x, y = 0, 0
direction = 'right'
for i in range(nx * ny):
yield x, y
if direction == 'right':
x += 1
if x >= xlast:
xlast -= 1
direction = 'up'
elif direction == 'up':
y += 1
if y >= ylast:
ylast -= 1
direction = 'left'
elif direction == 'left':
x -= 1
if x <= xfirst:
xfirst += 1
direction = 'down'
elif direction == 'down':
y -= 1
if y <= yfirst:
yfirst += 1
direction = 'right'
|
5d587a8e071064a5a783539702433a80adce9e26d118ec75c7adb9c5941b28f6
|
"""
This module defines default legend handlers.
It is strongly encouraged to have read the :doc:`legend guide
</tutorials/intermediate/legend_guide>` before this documentation.
Legend handlers are expected to be a callable object with a following
signature. ::
legend_handler(legend, orig_handle, fontsize, handlebox)
Where *legend* is the legend itself, *orig_handle* is the original
plot, *fontsize* is the fontsize in pixels, and *handlebox* is a
OffsetBox instance. Within the call, you should create relevant
artists (using relevant properties from the *legend* and/or
*orig_handle*) and add them into the handlebox. The artists needs to
be scaled according to the fontsize (note that the size is in pixel,
i.e., this is dpi-scaled value).
This module includes definition of several legend handler classes
derived from the base class (HandlerBase) with the following method::
def legend_artist(self, legend, orig_handle, fontsize, handlebox)
"""
from itertools import cycle
import numpy as np
from matplotlib.lines import Line2D
from matplotlib.patches import Rectangle
import matplotlib.collections as mcoll
import matplotlib.colors as mcolors
def update_from_first_child(tgt, src):
first_child = next(iter(src.get_children()), None)
if first_child is not None:
tgt.update_from(first_child)
class HandlerBase(object):
"""
A Base class for default legend handlers.
The derived classes are meant to override *create_artists* method, which
has a following signature.::
def create_artists(self, legend, orig_handle,
xdescent, ydescent, width, height, fontsize,
trans):
The overridden method needs to create artists of the given
transform that fits in the given dimension (xdescent, ydescent,
width, height) that are scaled by fontsize if necessary.
"""
def __init__(self, xpad=0., ypad=0., update_func=None):
self._xpad, self._ypad = xpad, ypad
self._update_prop_func = update_func
def _update_prop(self, legend_handle, orig_handle):
if self._update_prop_func is None:
self._default_update_prop(legend_handle, orig_handle)
else:
self._update_prop_func(legend_handle, orig_handle)
def _default_update_prop(self, legend_handle, orig_handle):
legend_handle.update_from(orig_handle)
def update_prop(self, legend_handle, orig_handle, legend):
self._update_prop(legend_handle, orig_handle)
legend._set_artist_props(legend_handle)
legend_handle.set_clip_box(None)
legend_handle.set_clip_path(None)
def adjust_drawing_area(self, legend, orig_handle,
xdescent, ydescent, width, height, fontsize,
):
xdescent = xdescent - self._xpad * fontsize
ydescent = ydescent - self._ypad * fontsize
width = width - self._xpad * fontsize
height = height - self._ypad * fontsize
return xdescent, ydescent, width, height
def legend_artist(self, legend, orig_handle,
fontsize, handlebox):
"""
Return the artist that this HandlerBase generates for the given
original artist/handle.
Parameters
----------
legend : :class:`matplotlib.legend.Legend` instance
The legend for which these legend artists are being created.
orig_handle : :class:`matplotlib.artist.Artist` or similar
The object for which these legend artists are being created.
fontsize : float or int
The fontsize in pixels. The artists being created should
be scaled according to the given fontsize.
handlebox : :class:`matplotlib.offsetbox.OffsetBox` instance
The box which has been created to hold this legend entry's
artists. Artists created in the `legend_artist` method must
be added to this handlebox inside this method.
"""
xdescent, ydescent, width, height = self.adjust_drawing_area(
legend, orig_handle,
handlebox.xdescent, handlebox.ydescent,
handlebox.width, handlebox.height,
fontsize)
artists = self.create_artists(legend, orig_handle,
xdescent, ydescent, width, height,
fontsize, handlebox.get_transform())
# create_artists will return a list of artists.
for a in artists:
handlebox.add_artist(a)
# we only return the first artist
return artists[0]
def create_artists(self, legend, orig_handle,
xdescent, ydescent, width, height, fontsize,
trans):
raise NotImplementedError('Derived must override')
class HandlerNpoints(HandlerBase):
"""
A legend handler that shows *numpoints* points in the legend entry.
"""
def __init__(self, marker_pad=0.3, numpoints=None, **kw):
"""
Parameters
----------
marker_pad : float
Padding between points in legend entry.
numpoints : int
Number of points to show in legend entry.
Notes
-----
Any other keyword arguments are given to `HandlerBase`.
"""
HandlerBase.__init__(self, **kw)
self._numpoints = numpoints
self._marker_pad = marker_pad
def get_numpoints(self, legend):
if self._numpoints is None:
return legend.numpoints
else:
return self._numpoints
def get_xdata(self, legend, xdescent, ydescent, width, height, fontsize):
numpoints = self.get_numpoints(legend)
if numpoints > 1:
# we put some pad here to compensate the size of the marker
pad = self._marker_pad * fontsize
xdata = np.linspace(-xdescent + pad,
-xdescent + width - pad,
numpoints)
xdata_marker = xdata
else:
xdata = np.linspace(-xdescent, -xdescent + width, 2)
xdata_marker = [-xdescent + 0.5 * width]
return xdata, xdata_marker
class HandlerNpointsYoffsets(HandlerNpoints):
"""
A legend handler that shows *numpoints* in the legend, and allows them to
be individually offest in the y-direction.
"""
def __init__(self, numpoints=None, yoffsets=None, **kw):
"""
Parameters
----------
numpoints : int
Number of points to show in legend entry.
yoffsets : array of floats
Length *numpoints* list of y offsets for each point in
legend entry.
Notes
-----
Any other keyword arguments are given to `HandlerNpoints`.
"""
HandlerNpoints.__init__(self, numpoints=numpoints, **kw)
self._yoffsets = yoffsets
def get_ydata(self, legend, xdescent, ydescent, width, height, fontsize):
if self._yoffsets is None:
ydata = height * legend._scatteryoffsets
else:
ydata = height * np.asarray(self._yoffsets)
return ydata
class HandlerLine2D(HandlerNpoints):
"""
Handler for `.Line2D` instances.
"""
def __init__(self, marker_pad=0.3, numpoints=None, **kw):
"""
Parameters
----------
marker_pad : float
Padding between points in legend entry.
numpoints : int
Number of points to show in legend entry.
Notes
-----
Any other keyword arguments are given to `HandlerNpoints`.
"""
HandlerNpoints.__init__(self, marker_pad=marker_pad,
numpoints=numpoints, **kw)
def create_artists(self, legend, orig_handle,
xdescent, ydescent, width, height, fontsize,
trans):
xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent,
width, height, fontsize)
ydata = np.full_like(xdata, ((height - ydescent) / 2))
legline = Line2D(xdata, ydata)
self.update_prop(legline, orig_handle, legend)
legline.set_drawstyle('default')
legline.set_marker("")
legline_marker = Line2D(xdata_marker, ydata[:len(xdata_marker)])
self.update_prop(legline_marker, orig_handle, legend)
legline_marker.set_linestyle('None')
if legend.markerscale != 1:
newsz = legline_marker.get_markersize() * legend.markerscale
legline_marker.set_markersize(newsz)
# we don't want to add this to the return list because
# the texts and handles are assumed to be in one-to-one
# correspondence.
legline._legmarker = legline_marker
legline.set_transform(trans)
legline_marker.set_transform(trans)
return [legline, legline_marker]
class HandlerPatch(HandlerBase):
"""
Handler for `.Patch` instances.
"""
def __init__(self, patch_func=None, **kw):
"""
Parameters
----------
patch_func : callable, optional
The function that creates the legend key artist.
*patch_func* should have the signature::
def patch_func(legend=legend, orig_handle=orig_handle,
xdescent=xdescent, ydescent=ydescent,
width=width, height=height, fontsize=fontsize)
Subsequently the created artist will have its ``update_prop``
method called and the appropriate transform will be applied.
Notes
-----
Any other keyword arguments are given to `HandlerBase`.
"""
HandlerBase.__init__(self, **kw)
self._patch_func = patch_func
def _create_patch(self, legend, orig_handle,
xdescent, ydescent, width, height, fontsize):
if self._patch_func is None:
p = Rectangle(xy=(-xdescent, -ydescent),
width=width, height=height)
else:
p = self._patch_func(legend=legend, orig_handle=orig_handle,
xdescent=xdescent, ydescent=ydescent,
width=width, height=height, fontsize=fontsize)
return p
def create_artists(self, legend, orig_handle,
xdescent, ydescent, width, height, fontsize, trans):
p = self._create_patch(legend, orig_handle,
xdescent, ydescent, width, height, fontsize)
self.update_prop(p, orig_handle, legend)
p.set_transform(trans)
return [p]
class HandlerLineCollection(HandlerLine2D):
"""
Handler for `.LineCollection` instances.
"""
def get_numpoints(self, legend):
if self._numpoints is None:
return legend.scatterpoints
else:
return self._numpoints
def _default_update_prop(self, legend_handle, orig_handle):
lw = orig_handle.get_linewidths()[0]
dashes = orig_handle._us_linestyles[0]
color = orig_handle.get_colors()[0]
legend_handle.set_color(color)
legend_handle.set_linestyle(dashes)
legend_handle.set_linewidth(lw)
def create_artists(self, legend, orig_handle,
xdescent, ydescent, width, height, fontsize, trans):
xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent,
width, height, fontsize)
ydata = ((height - ydescent) / 2.) * np.ones(xdata.shape, float)
legline = Line2D(xdata, ydata)
self.update_prop(legline, orig_handle, legend)
legline.set_transform(trans)
return [legline]
class HandlerRegularPolyCollection(HandlerNpointsYoffsets):
"""
Handler for `.RegularPolyCollections`.
"""
def __init__(self, yoffsets=None, sizes=None, **kw):
HandlerNpointsYoffsets.__init__(self, yoffsets=yoffsets, **kw)
self._sizes = sizes
def get_numpoints(self, legend):
if self._numpoints is None:
return legend.scatterpoints
else:
return self._numpoints
def get_sizes(self, legend, orig_handle,
xdescent, ydescent, width, height, fontsize):
if self._sizes is None:
handle_sizes = orig_handle.get_sizes()
if not len(handle_sizes):
handle_sizes = [1]
size_max = max(handle_sizes) * legend.markerscale ** 2
size_min = min(handle_sizes) * legend.markerscale ** 2
numpoints = self.get_numpoints(legend)
if numpoints < 4:
sizes = [.5 * (size_max + size_min), size_max,
size_min][:numpoints]
else:
rng = (size_max - size_min)
sizes = rng * np.linspace(0, 1, numpoints) + size_min
else:
sizes = self._sizes
return sizes
def update_prop(self, legend_handle, orig_handle, legend):
self._update_prop(legend_handle, orig_handle)
legend_handle.set_figure(legend.figure)
# legend._set_artist_props(legend_handle)
legend_handle.set_clip_box(None)
legend_handle.set_clip_path(None)
def create_collection(self, orig_handle, sizes, offsets, transOffset):
p = type(orig_handle)(orig_handle.get_numsides(),
rotation=orig_handle.get_rotation(),
sizes=sizes,
offsets=offsets,
transOffset=transOffset,
)
return p
def create_artists(self, legend, orig_handle,
xdescent, ydescent, width, height, fontsize,
trans):
xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent,
width, height, fontsize)
ydata = self.get_ydata(legend, xdescent, ydescent,
width, height, fontsize)
sizes = self.get_sizes(legend, orig_handle, xdescent, ydescent,
width, height, fontsize)
p = self.create_collection(orig_handle, sizes,
offsets=list(zip(xdata_marker, ydata)),
transOffset=trans)
self.update_prop(p, orig_handle, legend)
p._transOffset = trans
return [p]
class HandlerPathCollection(HandlerRegularPolyCollection):
"""
Handler for `.PathCollections`, which are used by `~.Axes.scatter`.
"""
def create_collection(self, orig_handle, sizes, offsets, transOffset):
p = type(orig_handle)([orig_handle.get_paths()[0]],
sizes=sizes,
offsets=offsets,
transOffset=transOffset,
)
return p
class HandlerCircleCollection(HandlerRegularPolyCollection):
"""
Handler for `.CircleCollections`.
"""
def create_collection(self, orig_handle, sizes, offsets, transOffset):
p = type(orig_handle)(sizes,
offsets=offsets,
transOffset=transOffset,
)
return p
class HandlerErrorbar(HandlerLine2D):
"""
Handler for Errorbars.
"""
def __init__(self, xerr_size=0.5, yerr_size=None,
marker_pad=0.3, numpoints=None, **kw):
self._xerr_size = xerr_size
self._yerr_size = yerr_size
HandlerLine2D.__init__(self, marker_pad=marker_pad,
numpoints=numpoints, **kw)
def get_err_size(self, legend, xdescent, ydescent,
width, height, fontsize):
xerr_size = self._xerr_size * fontsize
if self._yerr_size is None:
yerr_size = xerr_size
else:
yerr_size = self._yerr_size * fontsize
return xerr_size, yerr_size
def create_artists(self, legend, orig_handle,
xdescent, ydescent, width, height, fontsize,
trans):
plotlines, caplines, barlinecols = orig_handle
xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent,
width, height, fontsize)
ydata = ((height - ydescent) / 2.) * np.ones(xdata.shape, float)
legline = Line2D(xdata, ydata)
xdata_marker = np.asarray(xdata_marker)
ydata_marker = np.asarray(ydata[:len(xdata_marker)])
xerr_size, yerr_size = self.get_err_size(legend, xdescent, ydescent,
width, height, fontsize)
legline_marker = Line2D(xdata_marker, ydata_marker)
# when plotlines are None (only errorbars are drawn), we just
# make legline invisible.
if plotlines is None:
legline.set_visible(False)
legline_marker.set_visible(False)
else:
self.update_prop(legline, plotlines, legend)
legline.set_drawstyle('default')
legline.set_marker('None')
self.update_prop(legline_marker, plotlines, legend)
legline_marker.set_linestyle('None')
if legend.markerscale != 1:
newsz = legline_marker.get_markersize() * legend.markerscale
legline_marker.set_markersize(newsz)
handle_barlinecols = []
handle_caplines = []
if orig_handle.has_xerr:
verts = [((x - xerr_size, y), (x + xerr_size, y))
for x, y in zip(xdata_marker, ydata_marker)]
coll = mcoll.LineCollection(verts)
self.update_prop(coll, barlinecols[0], legend)
handle_barlinecols.append(coll)
if caplines:
capline_left = Line2D(xdata_marker - xerr_size, ydata_marker)
capline_right = Line2D(xdata_marker + xerr_size, ydata_marker)
self.update_prop(capline_left, caplines[0], legend)
self.update_prop(capline_right, caplines[0], legend)
capline_left.set_marker("|")
capline_right.set_marker("|")
handle_caplines.append(capline_left)
handle_caplines.append(capline_right)
if orig_handle.has_yerr:
verts = [((x, y - yerr_size), (x, y + yerr_size))
for x, y in zip(xdata_marker, ydata_marker)]
coll = mcoll.LineCollection(verts)
self.update_prop(coll, barlinecols[0], legend)
handle_barlinecols.append(coll)
if caplines:
capline_left = Line2D(xdata_marker, ydata_marker - yerr_size)
capline_right = Line2D(xdata_marker, ydata_marker + yerr_size)
self.update_prop(capline_left, caplines[0], legend)
self.update_prop(capline_right, caplines[0], legend)
capline_left.set_marker("_")
capline_right.set_marker("_")
handle_caplines.append(capline_left)
handle_caplines.append(capline_right)
artists = []
artists.extend(handle_barlinecols)
artists.extend(handle_caplines)
artists.append(legline)
artists.append(legline_marker)
for artist in artists:
artist.set_transform(trans)
return artists
class HandlerStem(HandlerNpointsYoffsets):
"""
Handler for plots produced by `~.Axes.stem`.
"""
def __init__(self, marker_pad=0.3, numpoints=None,
bottom=None, yoffsets=None, **kw):
"""
Parameters
----------
marker_pad : float
Padding between points in legend entry. Default is 0.3.
numpoints : int, optional
Number of points to show in legend entry.
bottom : float, optional
yoffsets : array of floats, optional
Length *numpoints* list of y offsets for each point in
legend entry.
Notes
-----
Any other keyword arguments are given to `HandlerNpointsYoffsets`.
"""
HandlerNpointsYoffsets.__init__(self, marker_pad=marker_pad,
numpoints=numpoints,
yoffsets=yoffsets,
**kw)
self._bottom = bottom
def get_ydata(self, legend, xdescent, ydescent, width, height, fontsize):
if self._yoffsets is None:
ydata = height * (0.5 * legend._scatteryoffsets + 0.5)
else:
ydata = height * np.asarray(self._yoffsets)
return ydata
def create_artists(self, legend, orig_handle,
xdescent, ydescent, width, height, fontsize,
trans):
markerline, stemlines, baseline = orig_handle
# Check to see if the stemcontainer is storing lines as a list or a
# LineCollection. Eventually using a list will be removed, and this
# logic can also be removed.
using_linecoll = isinstance(stemlines, mcoll.LineCollection)
xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent,
width, height, fontsize)
ydata = self.get_ydata(legend, xdescent, ydescent,
width, height, fontsize)
if self._bottom is None:
bottom = 0.
else:
bottom = self._bottom
leg_markerline = Line2D(xdata_marker, ydata[:len(xdata_marker)])
self.update_prop(leg_markerline, markerline, legend)
leg_stemlines = [Line2D([x, x], [bottom, y])
for x, y in zip(xdata_marker, ydata)]
if using_linecoll:
# change the function used by update_prop() from the default
# to one that handles LineCollection
orig_update_func = self._update_prop_func
self._update_prop_func = self._copy_collection_props
for line in leg_stemlines:
self.update_prop(line, stemlines, legend)
else:
for lm, m in zip(leg_stemlines, stemlines):
self.update_prop(lm, m, legend)
if using_linecoll:
self._update_prop_func = orig_update_func
leg_baseline = Line2D([np.min(xdata), np.max(xdata)],
[bottom, bottom])
self.update_prop(leg_baseline, baseline, legend)
artists = leg_stemlines
artists.append(leg_baseline)
artists.append(leg_markerline)
for artist in artists:
artist.set_transform(trans)
return artists
def _copy_collection_props(self, legend_handle, orig_handle):
"""
Method to copy properties from a LineCollection (orig_handle) to a
Line2D (legend_handle).
"""
legend_handle.set_color(orig_handle.get_color()[0])
legend_handle.set_linestyle(orig_handle.get_linestyle()[0])
class HandlerTuple(HandlerBase):
"""
Handler for Tuple.
Additional kwargs are passed through to `HandlerBase`.
Parameters
----------
ndivide : int, optional
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.
"""
def __init__(self, ndivide=1, pad=None, **kwargs):
self._ndivide = ndivide
self._pad = pad
HandlerBase.__init__(self, **kwargs)
def create_artists(self, legend, orig_handle,
xdescent, ydescent, width, height, fontsize,
trans):
handler_map = legend.get_legend_handler_map()
if self._ndivide is None:
ndivide = len(orig_handle)
else:
ndivide = self._ndivide
if self._pad is None:
pad = legend.borderpad * fontsize
else:
pad = self._pad * fontsize
if ndivide > 1:
width = (width - pad * (ndivide - 1)) / ndivide
xds_cycle = cycle(xdescent - (width + pad) * np.arange(ndivide))
a_list = []
for handle1 in orig_handle:
handler = legend.get_legend_handler(handler_map, handle1)
_a_list = handler.create_artists(
legend, handle1,
next(xds_cycle), ydescent, width, height, fontsize, trans)
a_list.extend(_a_list)
return a_list
class HandlerPolyCollection(HandlerBase):
"""
Handler for `.PolyCollection` used in `~.Axes.fill_between` and
`~.Axes.stackplot`.
"""
def _update_prop(self, legend_handle, orig_handle):
def first_color(colors):
if colors is None:
return None
colors = mcolors.to_rgba_array(colors)
if len(colors):
return colors[0]
else:
return "none"
def get_first(prop_array):
if len(prop_array):
return prop_array[0]
else:
return None
edgecolor = getattr(orig_handle, '_original_edgecolor',
orig_handle.get_edgecolor())
legend_handle.set_edgecolor(first_color(edgecolor))
facecolor = getattr(orig_handle, '_original_facecolor',
orig_handle.get_facecolor())
legend_handle.set_facecolor(first_color(facecolor))
legend_handle.set_fill(orig_handle.get_fill())
legend_handle.set_hatch(orig_handle.get_hatch())
legend_handle.set_linewidth(get_first(orig_handle.get_linewidths()))
legend_handle.set_linestyle(get_first(orig_handle.get_linestyles()))
legend_handle.set_transform(get_first(orig_handle.get_transforms()))
legend_handle.set_figure(orig_handle.get_figure())
legend_handle.set_alpha(orig_handle.get_alpha())
def create_artists(self, legend, orig_handle,
xdescent, ydescent, width, height, fontsize, trans):
p = Rectangle(xy=(-xdescent, -ydescent),
width=width, height=height)
self.update_prop(p, orig_handle, legend)
p.set_transform(trans)
return [p]
|
70b722b34b0b1f7d07cd23fa96308f26e35d10489cd5ad9d8314e334d286a632
|
"""
This provides several classes used for blocking interaction with figure
windows:
`BlockingInput`
Creates a callable object to retrieve events in a blocking way for
interactive sessions. Base class of the other classes listed here.
`BlockingKeyMouseInput`
Creates a callable object to retrieve key or mouse clicks in a blocking
way for interactive sessions. Used by `waitforbuttonpress`.
`BlockingMouseInput`
Creates a callable object to retrieve mouse clicks in a blocking way for
interactive sessions. Used by `ginput`.
`BlockingContourLabeler`
Creates a callable object to retrieve mouse clicks in a blocking way that
will then be used to place labels on a `ContourSet`. Used by `clabel`.
"""
import logging
from numbers import Integral
import matplotlib.lines as mlines
_log = logging.getLogger(__name__)
class BlockingInput(object):
"""Callable for retrieving events in a blocking way."""
def __init__(self, fig, eventslist=()):
self.fig = fig
self.eventslist = eventslist
def on_event(self, event):
"""
Event handler; will be passed to the current figure to retrieve events.
"""
# Add a new event to list - using a separate function is overkill for
# the base class, but this is consistent with subclasses.
self.add_event(event)
_log.info("Event %i", len(self.events))
# This will extract info from events.
self.post_event()
# Check if we have enough events already.
if len(self.events) >= self.n > 0:
self.fig.canvas.stop_event_loop()
def post_event(self):
"""For baseclass, do nothing but collect events."""
def cleanup(self):
"""Disconnect all callbacks."""
for cb in self.callbacks:
self.fig.canvas.mpl_disconnect(cb)
self.callbacks = []
def add_event(self, event):
"""For base class, this just appends an event to events."""
self.events.append(event)
def pop_event(self, index=-1):
"""
Remove an event from the event list -- by default, the last.
Note that this does not check that there are events, much like the
normal pop method. If no events exist, this will throw an exception.
"""
self.events.pop(index)
pop = pop_event
def __call__(self, n=1, timeout=30):
"""Blocking call to retrieve *n* events."""
if not isinstance(n, Integral):
raise ValueError("Requires an integer argument")
self.n = n
self.events = []
if hasattr(self.fig.canvas, "manager"):
# Ensure that the figure is shown, if we are managing it.
self.fig.show()
# Connect the events to the on_event function call.
self.callbacks = [self.fig.canvas.mpl_connect(name, self.on_event)
for name in self.eventslist]
try:
# Start event loop.
self.fig.canvas.start_event_loop(timeout=timeout)
finally: # Run even on exception like ctrl-c.
# Disconnect the callbacks.
self.cleanup()
# Return the events in this case.
return self.events
class BlockingMouseInput(BlockingInput):
"""
Callable for retrieving mouse clicks in a blocking way.
This class will also retrieve keypresses and map them to mouse clicks:
delete and backspace are like mouse button 3, enter is like mouse button 2
and all others are like mouse button 1.
"""
button_add = 1
button_pop = 3
button_stop = 2
def __init__(self, fig, mouse_add=1, mouse_pop=3, mouse_stop=2):
BlockingInput.__init__(self, fig=fig,
eventslist=('button_press_event',
'key_press_event'))
self.button_add = mouse_add
self.button_pop = mouse_pop
self.button_stop = mouse_stop
def post_event(self):
"""Process an event."""
if len(self.events) == 0:
_log.warning("No events yet")
elif self.events[-1].name == 'key_press_event':
self.key_event()
else:
self.mouse_event()
def mouse_event(self):
"""Process a mouse click event."""
event = self.events[-1]
button = event.button
if button == self.button_pop:
self.mouse_event_pop(event)
elif button == self.button_stop:
self.mouse_event_stop(event)
elif button == self.button_add:
self.mouse_event_add(event)
def key_event(self):
"""
Process a key press event, mapping keys to appropriate mouse clicks.
"""
event = self.events[-1]
if event.key is None:
# At least in OSX gtk backend some keys return None.
return
key = event.key.lower()
if key in ['backspace', 'delete']:
self.mouse_event_pop(event)
elif key in ['escape', 'enter']:
self.mouse_event_stop(event)
else:
self.mouse_event_add(event)
def mouse_event_add(self, event):
"""
Process an button-1 event (add a click if inside axes).
Parameters
----------
event : `~.backend_bases.MouseEvent`
"""
if event.inaxes:
self.add_click(event)
else: # If not a valid click, remove from event list.
BlockingInput.pop(self)
def mouse_event_stop(self, event):
"""
Process an button-2 event (end blocking input).
Parameters
----------
event : `~.backend_bases.MouseEvent`
"""
# Remove last event just for cleanliness.
BlockingInput.pop(self)
# This will exit even if not in infinite mode. This is consistent with
# MATLAB and sometimes quite useful, but will require the user to test
# how many points were actually returned before using data.
self.fig.canvas.stop_event_loop()
def mouse_event_pop(self, event):
"""
Process an button-3 event (remove the last click).
Parameters
----------
event : `~.backend_bases.MouseEvent`
"""
# Remove this last event.
BlockingInput.pop(self)
# Now remove any existing clicks if possible.
if self.events:
self.pop(event)
def add_click(self, event):
"""
Add the coordinates of an event to the list of clicks.
Parameters
----------
event : `~.backend_bases.MouseEvent`
"""
self.clicks.append((event.xdata, event.ydata))
_log.info("input %i: %f, %f",
len(self.clicks), event.xdata, event.ydata)
# If desired, plot up click.
if self.show_clicks:
line = mlines.Line2D([event.xdata], [event.ydata],
marker='+', color='r')
event.inaxes.add_line(line)
self.marks.append(line)
self.fig.canvas.draw()
def pop_click(self, event, index=-1):
"""
Remove a click (by default, the last) from the list of clicks.
Parameters
----------
event : `~.backend_bases.MouseEvent`
"""
self.clicks.pop(index)
if self.show_clicks:
self.marks.pop(index).remove()
self.fig.canvas.draw()
def pop(self, event, index=-1):
"""
Removes a click and the associated event from the list of clicks.
Defaults to the last click.
"""
self.pop_click(event, index)
BlockingInput.pop(self, index)
def cleanup(self, event=None):
"""
Parameters
----------
event : `~.backend_bases.MouseEvent`, optional
Not used
"""
# Clean the figure.
if self.show_clicks:
for mark in self.marks:
mark.remove()
self.marks = []
self.fig.canvas.draw()
# Call base class to remove callbacks.
BlockingInput.cleanup(self)
def __call__(self, n=1, timeout=30, show_clicks=True):
"""
Blocking call to retrieve *n* coordinate pairs through mouse clicks.
"""
self.show_clicks = show_clicks
self.clicks = []
self.marks = []
BlockingInput.__call__(self, n=n, timeout=timeout)
return self.clicks
class BlockingContourLabeler(BlockingMouseInput):
"""
Callable for retrieving mouse clicks and key presses in a blocking way.
Used to place contour labels.
"""
def __init__(self, cs):
self.cs = cs
BlockingMouseInput.__init__(self, fig=cs.ax.figure)
def add_click(self, event):
self.button1(event)
def pop_click(self, event, index=-1):
self.button3(event)
def button1(self, event):
"""
Process an button-1 event (add a label to a contour).
Parameters
----------
event : `~.backend_bases.MouseEvent`
"""
# Shorthand
if event.inaxes == self.cs.ax:
self.cs.add_label_near(event.x, event.y, self.inline,
inline_spacing=self.inline_spacing,
transform=False)
self.fig.canvas.draw()
else: # Remove event if not valid
BlockingInput.pop(self)
def button3(self, event):
"""
Process an button-3 event (remove a label if not in inline mode).
Unfortunately, if one is doing inline labels, then there is currently
no way to fix the broken contour - once humpty-dumpty is broken, he
can't be put back together. In inline mode, this does nothing.
Parameters
----------
event : `~.backend_bases.MouseEvent`
"""
if self.inline:
pass
else:
self.cs.pop_label()
self.cs.ax.figure.canvas.draw()
def __call__(self, inline, inline_spacing=5, n=-1, timeout=-1):
self.inline = inline
self.inline_spacing = inline_spacing
BlockingMouseInput.__call__(self, n=n, timeout=timeout,
show_clicks=False)
class BlockingKeyMouseInput(BlockingInput):
"""
Callable for retrieving mouse clicks and key presses in a blocking way.
"""
def __init__(self, fig):
BlockingInput.__init__(self, fig=fig, eventslist=(
'button_press_event', 'key_press_event'))
def post_event(self):
"""Determine if it is a key event."""
if self.events:
self.keyormouse = self.events[-1].name == 'key_press_event'
else:
_log.warning("No events yet.")
def __call__(self, timeout=30):
"""
Blocking call to retrieve a single mouse click or key press.
Returns ``True`` if key press, ``False`` if mouse click, or ``None`` if
timed out.
"""
self.keyormouse = None
BlockingInput.__call__(self, n=1, timeout=timeout)
return self.keyormouse
|
bb906eb35bca3df607c4fd84456f307d5fb94586892bd4a9217d063d1d559fb7
|
"""
These are classes to support contour plotting and labelling for the Axes class.
"""
from numbers import Integral
import numpy as np
from numpy import ma
import matplotlib as mpl
import matplotlib.path as mpath
import matplotlib.ticker as ticker
import matplotlib.cm as cm
import matplotlib.colors as mcolors
import matplotlib.collections as mcoll
import matplotlib.font_manager as font_manager
import matplotlib.text as text
import matplotlib.cbook as cbook
import matplotlib.mathtext as mathtext
import matplotlib.patches as mpatches
import matplotlib.texmanager as texmanager
import matplotlib.transforms as mtransforms
# Import needed for adding manual selection capability to clabel
from matplotlib.blocking_input import BlockingContourLabeler
# We can't use a single line collection for contour because a line
# collection can have only a single line style, and we want to be able to have
# dashed negative contours, for example, and solid positive contours.
# We could use a single polygon collection for filled contours, but it
# seems better to keep line and filled contours similar, with one collection
# per level.
class ClabelText(text.Text):
"""
Unlike the ordinary text, the get_rotation returns an updated
angle in the pixel coordinate assuming that the input rotation is
an angle in data coordinate (or whatever transform set).
"""
def get_rotation(self):
angle = text.Text.get_rotation(self)
trans = self.get_transform()
x, y = self.get_position()
new_angles = trans.transform_angles(np.array([angle]),
np.array([[x, y]]))
return new_angles[0]
class ContourLabeler(object):
"""Mixin to provide labelling capability to `.ContourSet`."""
def clabel(self, *args,
fontsize=None, inline=True, inline_spacing=5, fmt='%1.3f',
colors=None, use_clabeltext=False, manual=False,
rightside_up=True):
"""
Label a contour plot.
Call signature::
clabel(cs, [levels,] **kwargs)
Adds labels to line contours in *cs*, where *cs* is a
:class:`~matplotlib.contour.ContourSet` object returned by
``contour()``.
Parameters
----------
cs : `.ContourSet`
The ContourSet to label.
levels : array-like, optional
A list of level values, that should be labeled. The list must be
a subset of ``cs.levels``. If not given, all levels are labeled.
fontsize : string or float, optional
Size in points or relative size e.g., 'smaller', 'x-large'.
See `.Text.set_size` for accepted string values.
colors : color-spec, optional
The label colors:
- If *None*, the color of each label matches the color of
the corresponding contour.
- If one string color, e.g., *colors* = 'r' or *colors* =
'red', all labels will be plotted in this color.
- If a tuple of matplotlib color args (string, float, rgb, etc),
different labels will be plotted in different colors in the order
specified.
inline : bool, optional
If ``True`` the underlying contour is removed where the label is
placed. Default is ``True``.
inline_spacing : float, optional
Space in pixels to leave on each side of label when
placing inline. Defaults to 5.
This spacing will be exact for labels at locations where the
contour is straight, less so for labels on curved contours.
fmt : string or dict, optional
A format string for the label. Default is '%1.3f'
Alternatively, this can be a dictionary matching contour
levels with arbitrary strings to use for each contour level
(i.e., fmt[level]=string), or it can be any callable, such
as a :class:`~matplotlib.ticker.Formatter` instance, that
returns a string when called with a numeric contour level.
manual : bool or iterable, optional
If ``True``, contour labels will be placed manually using
mouse clicks. Click the first button near a contour to
add a label, click the second button (or potentially both
mouse buttons at once) to finish adding labels. The third
button can be used to remove the last label added, but
only if labels are not inline. Alternatively, the keyboard
can be used to select label locations (enter to end label
placement, delete or backspace act like the third mouse button,
and any other key will select a label location).
*manual* can also be an iterable object of x,y tuples.
Contour labels will be created as if mouse is clicked at each
x,y positions.
rightside_up : bool, optional
If ``True``, label rotations will always be plus
or minus 90 degrees from level. Default is ``True``.
use_clabeltext : bool, optional
If ``True``, `.ClabelText` class (instead of `.Text`) is used to
create labels. `ClabelText` recalculates rotation angles
of texts during the drawing time, therefore this can be used if
aspect of the axes changes. Default is ``False``.
Returns
-------
labels
A list of `.Text` instances for the labels.
"""
"""
NOTES on how this all works:
clabel basically takes the input arguments and uses them to
add a list of "label specific" attributes to the ContourSet
object. These attributes are all of the form label* and names
should be fairly self explanatory.
Once these attributes are set, clabel passes control to the
labels method (case of automatic label placement) or
`BlockingContourLabeler` (case of manual label placement).
"""
self.labelFmt = fmt
self._use_clabeltext = use_clabeltext
# Detect if manual selection is desired and remove from argument list.
self.labelManual = manual
self.rightside_up = rightside_up
if len(args) == 0:
levels = self.levels
indices = list(range(len(self.cvalues)))
elif len(args) == 1:
levlabs = list(args[0])
indices, levels = [], []
for i, lev in enumerate(self.levels):
if lev in levlabs:
indices.append(i)
levels.append(lev)
if len(levels) < len(levlabs):
raise ValueError("Specified levels {} don't match available "
"levels {}".format(levlabs, self.levels))
else:
raise TypeError("Illegal arguments to clabel, see help(clabel)")
self.labelLevelList = levels
self.labelIndiceList = indices
self.labelFontProps = font_manager.FontProperties()
self.labelFontProps.set_size(fontsize)
font_size_pts = self.labelFontProps.get_size_in_points()
self.labelFontSizeList = [font_size_pts] * len(levels)
if colors is None:
self.labelMappable = self
self.labelCValueList = np.take(self.cvalues, self.labelIndiceList)
else:
cmap = mcolors.ListedColormap(colors, N=len(self.labelLevelList))
self.labelCValueList = list(range(len(self.labelLevelList)))
self.labelMappable = cm.ScalarMappable(cmap=cmap,
norm=mcolors.NoNorm())
self.labelXYs = []
if np.iterable(self.labelManual):
for x, y in self.labelManual:
self.add_label_near(x, y, inline,
inline_spacing)
elif self.labelManual:
print('Select label locations manually using first mouse button.')
print('End manual selection with second mouse button.')
if not inline:
print('Remove last label by clicking third mouse button.')
blocking_contour_labeler = BlockingContourLabeler(self)
blocking_contour_labeler(inline, inline_spacing)
else:
self.labels(inline, inline_spacing)
self.labelTextsList = cbook.silent_list('text.Text', self.labelTexts)
return self.labelTextsList
cl = cbook.deprecated("3.0", alternative="labelTexts")(property(
lambda self: self.labelTexts))
cl_xy = cbook.deprecated("3.0", alternative="labelXYs")(property(
lambda self: self.labelXYs))
cl_cvalues = cbook.deprecated("3.0", alternative="labelCValues")(property(
lambda self: self.labelCValues))
def print_label(self, linecontour, labelwidth):
"Return *False* if contours are too short for a label."
return (len(linecontour) > 10 * labelwidth
or (np.ptp(linecontour, axis=0) > 1.2 * labelwidth).any())
def too_close(self, x, y, lw):
"Return *True* if a label is already near this location."
thresh = (1.2 * lw) ** 2
return any((x - loc[0]) ** 2 + (y - loc[1]) ** 2 < thresh
for loc in self.labelXYs)
def get_label_coords(self, distances, XX, YY, ysize, lw):
"""
Return x, y, and the index of a label location.
Labels are plotted at a location with the smallest
deviation of the contour from a straight line
unless there is another label nearby, in which case
the next best place on the contour is picked up.
If all such candidates are rejected, the beginning
of the contour is chosen.
"""
hysize = int(ysize / 2)
adist = np.argsort(distances)
for ind in adist:
x, y = XX[ind][hysize], YY[ind][hysize]
if self.too_close(x, y, lw):
continue
return x, y, ind
ind = adist[0]
x, y = XX[ind][hysize], YY[ind][hysize]
return x, y, ind
def get_label_width(self, lev, fmt, fsize):
"""
Return the width of the label in points.
"""
if not isinstance(lev, str):
lev = self.get_text(lev, fmt)
lev, ismath = text.Text()._preprocess_math(lev)
if ismath == 'TeX':
if not hasattr(self, '_TeX_manager'):
self._TeX_manager = texmanager.TexManager()
lw, _, _ = self._TeX_manager.get_text_width_height_descent(lev,
fsize)
elif ismath:
if not hasattr(self, '_mathtext_parser'):
self._mathtext_parser = mathtext.MathTextParser('bitmap')
img, _ = self._mathtext_parser.parse(lev, dpi=72,
prop=self.labelFontProps)
lw = img.get_width() # at dpi=72, the units are PostScript points
else:
# width is much less than "font size"
lw = (len(lev)) * fsize * 0.6
return lw
def set_label_props(self, label, text, color):
"""Set the label properties - color, fontsize, text."""
label.set_text(text)
label.set_color(color)
label.set_fontproperties(self.labelFontProps)
label.set_clip_box(self.ax.bbox)
def get_text(self, lev, fmt):
"""Get the text of the label."""
if isinstance(lev, str):
return lev
else:
if isinstance(fmt, dict):
return fmt.get(lev, '%1.3f')
elif callable(fmt):
return fmt(lev)
else:
return fmt % lev
def locate_label(self, linecontour, labelwidth):
"""
Find good place to draw a label (relatively flat part of the contour).
"""
# Number of contour points
nsize = len(linecontour)
if labelwidth > 1:
xsize = int(np.ceil(nsize / labelwidth))
else:
xsize = 1
if xsize == 1:
ysize = nsize
else:
ysize = int(labelwidth)
XX = np.resize(linecontour[:, 0], (xsize, ysize))
YY = np.resize(linecontour[:, 1], (xsize, ysize))
# I might have fouled up the following:
yfirst = YY[:, :1]
ylast = YY[:, -1:]
xfirst = XX[:, :1]
xlast = XX[:, -1:]
s = (yfirst - YY) * (xlast - xfirst) - (xfirst - XX) * (ylast - yfirst)
L = np.hypot(xlast - xfirst, ylast - yfirst)
# Ignore warning that divide by zero throws, as this is a valid option
with np.errstate(divide='ignore', invalid='ignore'):
dist = np.sum(np.abs(s) / L, axis=-1)
x, y, ind = self.get_label_coords(dist, XX, YY, ysize, labelwidth)
# There must be a more efficient way...
lc = [tuple(l) for l in linecontour]
dind = lc.index((x, y))
return x, y, dind
def calc_label_rot_and_inline(self, slc, ind, lw, lc=None, spacing=5):
"""
This function calculates the appropriate label rotation given
the linecontour coordinates in screen units, the index of the
label location and the label width.
It will also break contour and calculate inlining if *lc* is
not empty (lc defaults to the empty list if None). *spacing*
is the space around the label in pixels to leave empty.
Do both of these tasks at once to avoid calculating path lengths
multiple times, which is relatively costly.
The method used here involves calculating the path length
along the contour in pixel coordinates and then looking
approximately label width / 2 away from central point to
determine rotation and then to break contour if desired.
"""
if lc is None:
lc = []
# Half the label width
hlw = lw / 2.0
# Check if closed and, if so, rotate contour so label is at edge
closed = _is_closed_polygon(slc)
if closed:
slc = np.r_[slc[ind:-1], slc[:ind + 1]]
if len(lc): # Rotate lc also if not empty
lc = np.r_[lc[ind:-1], lc[:ind + 1]]
ind = 0
# Calculate path lengths
pl = np.zeros(slc.shape[0], dtype=float)
dx = np.diff(slc, axis=0)
pl[1:] = np.cumsum(np.hypot(dx[:, 0], dx[:, 1]))
pl = pl - pl[ind]
# Use linear interpolation to get points around label
xi = np.array([-hlw, hlw])
if closed: # Look at end also for closed contours
dp = np.array([pl[-1], 0])
else:
dp = np.zeros_like(xi)
# Get angle of vector between the two ends of the label - must be
# calculated in pixel space for text rotation to work correctly.
(dx,), (dy,) = (np.diff(np.interp(dp + xi, pl, slc_col))
for slc_col in slc.T)
rotation = np.rad2deg(np.arctan2(dy, dx))
if self.rightside_up:
# Fix angle so text is never upside-down
rotation = (rotation + 90) % 180 - 90
# Break contour if desired
nlc = []
if len(lc):
# Expand range by spacing
xi = dp + xi + np.array([-spacing, spacing])
# Get (integer) indices near points of interest; use -1 as marker
# for out of bounds.
I = np.interp(xi, pl, np.arange(len(pl)), left=-1, right=-1)
I = [np.floor(I[0]).astype(int), np.ceil(I[1]).astype(int)]
if I[0] != -1:
xy1 = [np.interp(xi[0], pl, lc_col) for lc_col in lc.T]
if I[1] != -1:
xy2 = [np.interp(xi[1], pl, lc_col) for lc_col in lc.T]
# Actually break contours
if closed:
# This will remove contour if shorter than label
if all(i != -1 for i in I):
nlc.append(np.row_stack([xy2, lc[I[1]:I[0]+1], xy1]))
else:
# These will remove pieces of contour if they have length zero
if I[0] != -1:
nlc.append(np.row_stack([lc[:I[0]+1], xy1]))
if I[1] != -1:
nlc.append(np.row_stack([xy2, lc[I[1]:]]))
# The current implementation removes contours completely
# covered by labels. Uncomment line below to keep
# original contour if this is the preferred behavior.
# if not len(nlc): nlc = [ lc ]
return rotation, nlc
def _get_label_text(self, x, y, rotation):
dx, dy = self.ax.transData.inverted().transform_point((x, y))
t = text.Text(dx, dy, rotation=rotation,
horizontalalignment='center',
verticalalignment='center')
return t
def _get_label_clabeltext(self, x, y, rotation):
# x, y, rotation is given in pixel coordinate. Convert them to
# the data coordinate and create a label using ClabelText
# class. This way, the rotation of the clabel is along the
# contour line always.
transDataInv = self.ax.transData.inverted()
dx, dy = transDataInv.transform_point((x, y))
drotation = transDataInv.transform_angles(np.array([rotation]),
np.array([[x, y]]))
t = ClabelText(dx, dy, rotation=drotation[0],
horizontalalignment='center',
verticalalignment='center')
return t
def _add_label(self, t, x, y, lev, cvalue):
color = self.labelMappable.to_rgba(cvalue, alpha=self.alpha)
_text = self.get_text(lev, self.labelFmt)
self.set_label_props(t, _text, color)
self.labelTexts.append(t)
self.labelCValues.append(cvalue)
self.labelXYs.append((x, y))
# Add label to plot here - useful for manual mode label selection
self.ax.add_artist(t)
def add_label(self, x, y, rotation, lev, cvalue):
"""
Add contour label using :class:`~matplotlib.text.Text` class.
"""
t = self._get_label_text(x, y, rotation)
self._add_label(t, x, y, lev, cvalue)
def add_label_clabeltext(self, x, y, rotation, lev, cvalue):
"""
Add contour label using :class:`ClabelText` class.
"""
# x, y, rotation is given in pixel coordinate. Convert them to
# the data coordinate and create a label using ClabelText
# class. This way, the rotation of the clabel is along the
# contour line always.
t = self._get_label_clabeltext(x, y, rotation)
self._add_label(t, x, y, lev, cvalue)
def add_label_near(self, x, y, inline=True, inline_spacing=5,
transform=None):
"""
Add a label near the point (x, y). If transform is None
(default), (x, y) is in data coordinates; if transform is
False, (x, y) is in display coordinates; otherwise, the
specified transform will be used to translate (x, y) into
display coordinates.
Parameters
----------
x, y : float
The approximate location of the label.
inline : bool, optional, default: True
If *True* remove the segment of the contour beneath the label.
inline_spacing : int, optional, default: 5
Space in pixels to leave on each side of label when placing
inline. This spacing will be exact for labels at locations where
the contour is straight, less so for labels on curved contours.
"""
if transform is None:
transform = self.ax.transData
if transform:
x, y = transform.transform_point((x, y))
# find the nearest contour _in screen units_
conmin, segmin, imin, xmin, ymin = self.find_nearest_contour(
x, y, self.labelIndiceList)[:5]
# The calc_label_rot_and_inline routine requires that (xmin,ymin)
# be a vertex in the path. So, if it isn't, add a vertex here
# grab the paths from the collections
paths = self.collections[conmin].get_paths()
# grab the correct segment
active_path = paths[segmin]
# grab its vertices
lc = active_path.vertices
# sort out where the new vertex should be added data-units
xcmin = self.ax.transData.inverted().transform_point([xmin, ymin])
# if there isn't a vertex close enough
if not np.allclose(xcmin, lc[imin]):
# insert new data into the vertex list
lc = np.r_[lc[:imin], np.array(xcmin)[None, :], lc[imin:]]
# replace the path with the new one
paths[segmin] = mpath.Path(lc)
# Get index of nearest level in subset of levels used for labeling
lmin = self.labelIndiceList.index(conmin)
# Coordinates of contour
paths = self.collections[conmin].get_paths()
lc = paths[segmin].vertices
# In pixel/screen space
slc = self.ax.transData.transform(lc)
# Get label width for rotating labels and breaking contours
lw = self.get_label_width(self.labelLevelList[lmin],
self.labelFmt, self.labelFontSizeList[lmin])
# lw is in points.
lw *= self.ax.figure.dpi / 72.0 # scale to screen coordinates
# now lw in pixels
# Figure out label rotation.
if inline:
lcarg = lc
else:
lcarg = None
rotation, nlc = self.calc_label_rot_and_inline(
slc, imin, lw, lcarg,
inline_spacing)
self.add_label(xmin, ymin, rotation, self.labelLevelList[lmin],
self.labelCValueList[lmin])
if inline:
# Remove old, not looping over paths so we can do this up front
paths.pop(segmin)
# Add paths if not empty or single point
for n in nlc:
if len(n) > 1:
paths.append(mpath.Path(n))
def pop_label(self, index=-1):
"""Defaults to removing last label, but any index can be supplied"""
self.labelCValues.pop(index)
t = self.labelTexts.pop(index)
t.remove()
def labels(self, inline, inline_spacing):
if self._use_clabeltext:
add_label = self.add_label_clabeltext
else:
add_label = self.add_label
for icon, lev, fsize, cvalue in zip(
self.labelIndiceList, self.labelLevelList,
self.labelFontSizeList, self.labelCValueList):
con = self.collections[icon]
trans = con.get_transform()
lw = self.get_label_width(lev, self.labelFmt, fsize)
lw *= self.ax.figure.dpi / 72.0 # scale to screen coordinates
additions = []
paths = con.get_paths()
for segNum, linepath in enumerate(paths):
lc = linepath.vertices # Line contour
slc0 = trans.transform(lc) # Line contour in screen coords
# For closed polygons, add extra point to avoid division by
# zero in print_label and locate_label. Other than these
# functions, this is not necessary and should probably be
# eventually removed.
if _is_closed_polygon(lc):
slc = np.r_[slc0, slc0[1:2, :]]
else:
slc = slc0
# Check if long enough for a label
if self.print_label(slc, lw):
x, y, ind = self.locate_label(slc, lw)
if inline:
lcarg = lc
else:
lcarg = None
rotation, new = self.calc_label_rot_and_inline(
slc0, ind, lw, lcarg,
inline_spacing)
# Actually add the label
add_label(x, y, rotation, lev, cvalue)
# If inline, add new contours
if inline:
for n in new:
# Add path if not empty or single point
if len(n) > 1:
additions.append(mpath.Path(n))
else: # If not adding label, keep old path
additions.append(linepath)
# After looping over all segments on a contour, remove old
# paths and add new ones if inlining
if inline:
del paths[:]
paths.extend(additions)
def _find_closest_point_on_leg(p1, p2, p0):
"""Find the closest point to p0 on line segment connecting p1 and p2."""
# handle degenerate case
if np.all(p2 == p1):
d = np.sum((p0 - p1)**2)
return d, p1
d21 = p2 - p1
d01 = p0 - p1
# project on to line segment to find closest point
proj = np.dot(d01, d21) / np.dot(d21, d21)
if proj < 0:
proj = 0
if proj > 1:
proj = 1
pc = p1 + proj * d21
# find squared distance
d = np.sum((pc-p0)**2)
return d, pc
def _is_closed_polygon(X):
"""
Return whether first and last object in a sequence are the same. These are
presumably coordinates on a polygonal curve, in which case this function
tests if that curve is closed.
"""
return np.all(X[0] == X[-1])
def _find_closest_point_on_path(lc, point):
"""
Parameters
----------
lc : coordinates of vertices
point : coordinates of test point
"""
# find index of closest vertex for this segment
ds = np.sum((lc - point[None, :])**2, 1)
imin = np.argmin(ds)
dmin = np.inf
xcmin = None
legmin = (None, None)
closed = _is_closed_polygon(lc)
# build list of legs before and after this vertex
legs = []
if imin > 0 or closed:
legs.append(((imin-1) % len(lc), imin))
if imin < len(lc) - 1 or closed:
legs.append((imin, (imin+1) % len(lc)))
for leg in legs:
d, xc = _find_closest_point_on_leg(lc[leg[0]], lc[leg[1]], point)
if d < dmin:
dmin = d
xcmin = xc
legmin = leg
return (dmin, xcmin, legmin)
class ContourSet(cm.ScalarMappable, ContourLabeler):
"""
Store a set of contour lines or filled regions.
User-callable method: `~.axes.Axes.clabel`
Parameters
----------
ax : `~.axes.Axes`
levels : [level0, level1, ..., leveln]
A list of floating point numbers indicating the contour
levels.
allsegs : [level0segs, level1segs, ...]
List of all the polygon segments for all the *levels*.
For contour lines ``len(allsegs) == len(levels)``, and for
filled contour regions ``len(allsegs) = len(levels)-1``. The lists
should look like::
level0segs = [polygon0, polygon1, ...]
polygon0 = array_like [[x0,y0], [x1,y1], ...]
allkinds : ``None`` or [level0kinds, level1kinds, ...]
Optional list of all the polygon vertex kinds (code types), as
described and used in Path. This is used to allow multiply-
connected paths such as holes within filled polygons.
If not ``None``, ``len(allkinds) == len(allsegs)``. The lists
should look like::
level0kinds = [polygon0kinds, ...]
polygon0kinds = [vertexcode0, vertexcode1, ...]
If *allkinds* is not ``None``, usually all polygons for a
particular contour level are grouped together so that
``level0segs = [polygon0]`` and ``level0kinds = [polygon0kinds]``.
**kwargs
Keyword arguments are as described in the docstring of
`~.axes.Axes.contour`.
Attributes
----------
ax
The axes object in which the contours are drawn.
collections
A silent_list of LineCollections or PolyCollections.
levels
Contour levels.
layers
Same as levels for line contours; half-way between
levels for filled contours. See :meth:`_process_colors`.
"""
def __init__(self, ax, *args,
levels=None, filled=False, linewidths=None, linestyles=None,
alpha=None, origin=None, extent=None,
cmap=None, colors=None, norm=None, vmin=None, vmax=None,
extend='neither', antialiased=None,
**kwargs):
"""
Draw contour lines or filled regions, depending on
whether keyword arg *filled* is ``False`` (default) or ``True``.
Call signature::
ContourSet(ax, levels, allsegs, [allkinds], **kwargs)
Parameters
----------
ax : `~.axes.Axes`
The `~.axes.Axes` object to draw on.
levels : [level0, level1, ..., leveln]
A list of floating point numbers indicating the contour
levels.
allsegs : [level0segs, level1segs, ...]
List of all the polygon segments for all the *levels*.
For contour lines ``len(allsegs) == len(levels)``, and for
filled contour regions ``len(allsegs) = len(levels)-1``. The lists
should look like::
level0segs = [polygon0, polygon1, ...]
polygon0 = array_like [[x0,y0], [x1,y1], ...]
allkinds : [level0kinds, level1kinds, ...], optional
Optional list of all the polygon vertex kinds (code types), as
described and used in Path. This is used to allow multiply-
connected paths such as holes within filled polygons.
If not ``None``, ``len(allkinds) == len(allsegs)``. The lists
should look like::
level0kinds = [polygon0kinds, ...]
polygon0kinds = [vertexcode0, vertexcode1, ...]
If *allkinds* is not ``None``, usually all polygons for a
particular contour level are grouped together so that
``level0segs = [polygon0]`` and ``level0kinds = [polygon0kinds]``.
**kwargs
Keyword arguments are as described in the docstring of
`~axes.Axes.contour`.
"""
self.ax = ax
self.levels = levels
self.filled = filled
self.linewidths = linewidths
self.linestyles = linestyles
self.hatches = kwargs.pop('hatches', [None])
self.alpha = alpha
self.origin = origin
self.extent = extent
self.colors = colors
self.extend = extend
self.antialiased = antialiased
if self.antialiased is None and self.filled:
self.antialiased = False # eliminate artifacts; we are not
# stroking the boundaries.
# The default for line contours will be taken from the
# LineCollection default, which uses :rc:`lines.antialiased`.
self.nchunk = kwargs.pop('nchunk', 0)
self.locator = kwargs.pop('locator', None)
if (isinstance(norm, mcolors.LogNorm)
or isinstance(self.locator, ticker.LogLocator)):
self.logscale = True
if norm is None:
norm = mcolors.LogNorm()
else:
self.logscale = False
cbook._check_in_list([None, 'lower', 'upper', 'image'], origin=origin)
if self.extent is not None and len(self.extent) != 4:
raise ValueError("If given, *extent* must be '[ *None* |"
" (x0,x1,y0,y1) ]'")
if self.colors is not None and cmap is not None:
raise ValueError('Either colors or cmap must be None')
if self.origin == 'image':
self.origin = mpl.rcParams['image.origin']
self._transform = kwargs.pop('transform', None)
kwargs = self._process_args(*args, **kwargs)
self._process_levels()
if self.colors is not None:
ncolors = len(self.levels)
if self.filled:
ncolors -= 1
i0 = 0
# Handle the case where colors are given for the extended
# parts of the contour.
extend_min = self.extend in ['min', 'both']
extend_max = self.extend in ['max', 'both']
use_set_under_over = False
# if we are extending the lower end, and we've been given enough
# colors then skip the first color in the resulting cmap. For the
# extend_max case we don't need to worry about passing more colors
# than ncolors as ListedColormap will clip.
total_levels = ncolors + int(extend_min) + int(extend_max)
if len(self.colors) == total_levels and (extend_min or extend_max):
use_set_under_over = True
if extend_min:
i0 = 1
cmap = mcolors.ListedColormap(self.colors[i0:None], N=ncolors)
if use_set_under_over:
if extend_min:
cmap.set_under(self.colors[0])
if extend_max:
cmap.set_over(self.colors[-1])
if self.filled:
self.collections = cbook.silent_list('mcoll.PathCollection')
else:
self.collections = cbook.silent_list('mcoll.LineCollection')
# label lists must be initialized here
self.labelTexts = []
self.labelCValues = []
kw = {'cmap': cmap}
if norm is not None:
kw['norm'] = norm
# sets self.cmap, norm if needed;
cm.ScalarMappable.__init__(self, **kw)
if vmin is not None:
self.norm.vmin = vmin
if vmax is not None:
self.norm.vmax = vmax
self._process_colors()
self.allsegs, self.allkinds = self._get_allsegs_and_allkinds()
if self.filled:
if self.linewidths is not None:
cbook._warn_external('linewidths is ignored by contourf')
# Lower and upper contour levels.
lowers, uppers = self._get_lowers_and_uppers()
# Ensure allkinds can be zipped below.
if self.allkinds is None:
self.allkinds = [None] * len(self.allsegs)
# Default zorder taken from Collection
zorder = kwargs.pop('zorder', 1)
for level, level_upper, segs, kinds in \
zip(lowers, uppers, self.allsegs, self.allkinds):
paths = self._make_paths(segs, kinds)
col = mcoll.PathCollection(
paths,
antialiaseds=(self.antialiased,),
edgecolors='none',
alpha=self.alpha,
transform=self.get_transform(),
zorder=zorder)
self.ax.add_collection(col, autolim=False)
self.collections.append(col)
else:
tlinewidths = self._process_linewidths()
self.tlinewidths = tlinewidths
tlinestyles = self._process_linestyles()
aa = self.antialiased
if aa is not None:
aa = (self.antialiased,)
# Default zorder taken from LineCollection
zorder = kwargs.pop('zorder', 2)
for level, width, lstyle, segs in \
zip(self.levels, tlinewidths, tlinestyles, self.allsegs):
col = mcoll.LineCollection(
segs,
antialiaseds=aa,
linewidths=width,
linestyles=[lstyle],
alpha=self.alpha,
transform=self.get_transform(),
zorder=zorder)
col.set_label('_nolegend_')
self.ax.add_collection(col, autolim=False)
self.collections.append(col)
for col in self.collections:
col.sticky_edges.x[:] = [self._mins[0], self._maxs[0]]
col.sticky_edges.y[:] = [self._mins[1], self._maxs[1]]
self.ax.update_datalim([self._mins, self._maxs])
self.ax.autoscale_view(tight=True)
self.changed() # set the colors
if kwargs:
s = ", ".join(map(repr, kwargs))
cbook._warn_external('The following kwargs were not used by '
'contour: ' + s)
def get_transform(self):
"""
Return the :class:`~matplotlib.transforms.Transform`
instance used by this ContourSet.
"""
if self._transform is None:
self._transform = self.ax.transData
elif (not isinstance(self._transform, mtransforms.Transform)
and hasattr(self._transform, '_as_mpl_transform')):
self._transform = self._transform._as_mpl_transform(self.ax)
return self._transform
def __getstate__(self):
state = self.__dict__.copy()
# the C object _contour_generator cannot currently be pickled. This
# isn't a big issue as it is not actually used once the contour has
# been calculated.
state['_contour_generator'] = None
return state
def legend_elements(self, variable_name='x', str_format=str):
"""
Return a list of artists and labels suitable for passing through
to :func:`plt.legend` which represent this ContourSet.
The labels have the form "0 < x <= 1" stating the data ranges which
the artists represent.
Parameters
----------
variable_name : str
The string used inside the inequality used on the labels.
str_format : function: float -> str
Function used to format the numbers in the labels.
Returns
-------
artists : List[`.Artist`]
A list of the artists.
labels : List[str]
A list of the labels.
"""
artists = []
labels = []
if self.filled:
lowers, uppers = self._get_lowers_and_uppers()
n_levels = len(self.collections)
for i, (collection, lower, upper) in enumerate(
zip(self.collections, lowers, uppers)):
patch = mpatches.Rectangle(
(0, 0), 1, 1,
facecolor=collection.get_facecolor()[0],
hatch=collection.get_hatch(),
alpha=collection.get_alpha())
artists.append(patch)
lower = str_format(lower)
upper = str_format(upper)
if i == 0 and self.extend in ('min', 'both'):
labels.append(r'$%s \leq %s$' % (variable_name,
lower))
elif i == n_levels - 1 and self.extend in ('max', 'both'):
labels.append(r'$%s > %s$' % (variable_name,
upper))
else:
labels.append(r'$%s < %s \leq %s$' % (lower,
variable_name,
upper))
else:
for collection, level in zip(self.collections, self.levels):
patch = mcoll.LineCollection(None)
patch.update_from(collection)
artists.append(patch)
# format the level for insertion into the labels
level = str_format(level)
labels.append(r'$%s = %s$' % (variable_name, level))
return artists, labels
def _process_args(self, *args, **kwargs):
"""
Process *args* and *kwargs*; override in derived classes.
Must set self.levels, self.zmin and self.zmax, and update axes
limits.
"""
self.levels = args[0]
self.allsegs = args[1]
self.allkinds = len(args) > 2 and args[2] or None
self.zmax = np.max(self.levels)
self.zmin = np.min(self.levels)
# Check lengths of levels and allsegs.
if self.filled:
if len(self.allsegs) != len(self.levels) - 1:
raise ValueError('must be one less number of segments as '
'levels')
else:
if len(self.allsegs) != len(self.levels):
raise ValueError('must be same number of segments as levels')
# Check length of allkinds.
if (self.allkinds is not None and
len(self.allkinds) != len(self.allsegs)):
raise ValueError('allkinds has different length to allsegs')
# Determine x,y bounds and update axes data limits.
flatseglist = [s for seg in self.allsegs for s in seg]
points = np.concatenate(flatseglist, axis=0)
self._mins = points.min(axis=0)
self._maxs = points.max(axis=0)
return kwargs
def _get_allsegs_and_allkinds(self):
"""
Override in derived classes to create and return allsegs and allkinds.
allkinds can be None.
"""
return self.allsegs, self.allkinds
def _get_lowers_and_uppers(self):
"""
Return (lowers,uppers) for filled contours.
"""
lowers = self._levels[:-1]
if self.zmin == lowers[0]:
# Include minimum values in lowest interval
lowers = lowers.copy() # so we don't change self._levels
if self.logscale:
lowers[0] = 0.99 * self.zmin
else:
lowers[0] -= 1
uppers = self._levels[1:]
return (lowers, uppers)
def _make_paths(self, segs, kinds):
if kinds is not None:
return [mpath.Path(seg, codes=kind)
for seg, kind in zip(segs, kinds)]
else:
return [mpath.Path(seg) for seg in segs]
def changed(self):
tcolors = [(tuple(rgba),)
for rgba in self.to_rgba(self.cvalues, alpha=self.alpha)]
self.tcolors = tcolors
hatches = self.hatches * len(tcolors)
for color, hatch, collection in zip(tcolors, hatches,
self.collections):
if self.filled:
collection.set_facecolor(color)
# update the collection's hatch (may be None)
collection.set_hatch(hatch)
else:
collection.set_color(color)
for label, cv in zip(self.labelTexts, self.labelCValues):
label.set_alpha(self.alpha)
label.set_color(self.labelMappable.to_rgba(cv))
# add label colors
cm.ScalarMappable.changed(self)
def _autolev(self, N):
"""
Select contour levels to span the data.
The target number of levels, *N*, is used only when the
scale is not log and default locator is used.
We need two more levels for filled contours than for
line contours, because for the latter we need to specify
the lower and upper boundary of each range. For example,
a single contour boundary, say at z = 0, requires only
one contour line, but two filled regions, and therefore
three levels to provide boundaries for both regions.
"""
if self.locator is None:
if self.logscale:
self.locator = ticker.LogLocator()
else:
self.locator = ticker.MaxNLocator(N + 1, min_n_ticks=1)
lev = self.locator.tick_values(self.zmin, self.zmax)
try:
if self.locator._symmetric:
return lev
except AttributeError:
pass
# Trim excess levels the locator may have supplied.
under = np.nonzero(lev < self.zmin)[0]
i0 = under[-1] if len(under) else 0
over = np.nonzero(lev > self.zmax)[0]
i1 = over[0] + 1 if len(over) else len(lev)
if self.extend in ('min', 'both'):
i0 += 1
if self.extend in ('max', 'both'):
i1 -= 1
if i1 - i0 < 3:
i0, i1 = 0, len(lev)
return lev[i0:i1]
def _contour_level_args(self, z, args):
"""
Determine the contour levels and store in self.levels.
"""
if self.levels is None:
if len(args) == 0:
levels_arg = 7 # Default, hard-wired.
else:
levels_arg = args[0]
else:
levels_arg = self.levels
if isinstance(levels_arg, Integral):
self.levels = self._autolev(levels_arg)
else:
self.levels = np.asarray(levels_arg).astype(np.float64)
if not self.filled:
inside = (self.levels > self.zmin) & (self.levels < self.zmax)
levels_in = self.levels[inside]
if len(levels_in) == 0:
self.levels = [self.zmin]
cbook._warn_external(
"No contour levels were found within the data range.")
if self.filled and len(self.levels) < 2:
raise ValueError("Filled contours require at least 2 levels.")
if len(self.levels) > 1 and np.min(np.diff(self.levels)) <= 0.0:
raise ValueError("Contour levels must be increasing")
def _process_levels(self):
"""
Assign values to :attr:`layers` based on :attr:`levels`,
adding extended layers as needed if contours are filled.
For line contours, layers simply coincide with levels;
a line is a thin layer. No extended levels are needed
with line contours.
"""
# Make a private _levels to include extended regions; we
# want to leave the original levels attribute unchanged.
# (Colorbar needs this even for line contours.)
self._levels = list(self.levels)
if self.logscale:
lower, upper = 1e-250, 1e250
else:
lower, upper = -1e250, 1e250
if self.extend in ('both', 'min'):
self._levels.insert(0, lower)
if self.extend in ('both', 'max'):
self._levels.append(upper)
self._levels = np.asarray(self._levels)
if not self.filled:
self.layers = self.levels
return
# Layer values are mid-way between levels in screen space.
if self.logscale:
# Avoid overflow by taking sqrt before multiplying.
self.layers = (np.sqrt(self._levels[:-1])
* np.sqrt(self._levels[1:]))
else:
self.layers = 0.5 * (self._levels[:-1] + self._levels[1:])
def _process_colors(self):
"""
Color argument processing for contouring.
Note that we base the color mapping on the contour levels
and layers, not on the actual range of the Z values. This
means we don't have to worry about bad values in Z, and we
always have the full dynamic range available for the selected
levels.
The color is based on the midpoint of the layer, except for
extended end layers. By default, the norm vmin and vmax
are the extreme values of the non-extended levels. Hence,
the layer color extremes are not the extreme values of
the colormap itself, but approach those values as the number
of levels increases. An advantage of this scheme is that
line contours, when added to filled contours, take on
colors that are consistent with those of the filled regions;
for example, a contour line on the boundary between two
regions will have a color intermediate between those
of the regions.
"""
self.monochrome = self.cmap.monochrome
if self.colors is not None:
# Generate integers for direct indexing.
i0, i1 = 0, len(self.levels)
if self.filled:
i1 -= 1
# Out of range indices for over and under:
if self.extend in ('both', 'min'):
i0 -= 1
if self.extend in ('both', 'max'):
i1 += 1
self.cvalues = list(range(i0, i1))
self.set_norm(mcolors.NoNorm())
else:
self.cvalues = self.layers
self.set_array(self.levels)
self.autoscale_None()
if self.extend in ('both', 'max', 'min'):
self.norm.clip = False
# self.tcolors are set by the "changed" method
def _process_linewidths(self):
linewidths = self.linewidths
Nlev = len(self.levels)
if linewidths is None:
tlinewidths = [(mpl.rcParams['lines.linewidth'],)] * Nlev
else:
if not np.iterable(linewidths):
linewidths = [linewidths] * Nlev
else:
linewidths = list(linewidths)
if len(linewidths) < Nlev:
nreps = int(np.ceil(Nlev / len(linewidths)))
linewidths = linewidths * nreps
if len(linewidths) > Nlev:
linewidths = linewidths[:Nlev]
tlinewidths = [(w,) for w in linewidths]
return tlinewidths
def _process_linestyles(self):
linestyles = self.linestyles
Nlev = len(self.levels)
if linestyles is None:
tlinestyles = ['solid'] * Nlev
if self.monochrome:
neg_ls = mpl.rcParams['contour.negative_linestyle']
eps = - (self.zmax - self.zmin) * 1e-15
for i, lev in enumerate(self.levels):
if lev < eps:
tlinestyles[i] = neg_ls
else:
if isinstance(linestyles, str):
tlinestyles = [linestyles] * Nlev
elif np.iterable(linestyles):
tlinestyles = list(linestyles)
if len(tlinestyles) < Nlev:
nreps = int(np.ceil(Nlev / len(linestyles)))
tlinestyles = tlinestyles * nreps
if len(tlinestyles) > Nlev:
tlinestyles = tlinestyles[:Nlev]
else:
raise ValueError("Unrecognized type for linestyles kwarg")
return tlinestyles
def get_alpha(self):
"""returns alpha to be applied to all ContourSet artists"""
return self.alpha
def set_alpha(self, alpha):
"""
Set the alpha blending value for all ContourSet artists.
*alpha* must be between 0 (transparent) and 1 (opaque).
"""
self.alpha = alpha
self.changed()
def find_nearest_contour(self, x, y, indices=None, pixel=True):
"""
Finds contour that is closest to a point. Defaults to
measuring distance in pixels (screen space - useful for manual
contour labeling), but this can be controlled via a keyword
argument.
Returns a tuple containing the contour, segment, index of
segment, x & y of segment point and distance to minimum point.
Optional keyword arguments:
*indices*:
Indexes of contour levels to consider when looking for
nearest point. Defaults to using all levels.
*pixel*:
If *True*, measure distance in pixel space, if not, measure
distance in axes space. Defaults to *True*.
"""
# This function uses a method that is probably quite
# inefficient based on converting each contour segment to
# pixel coordinates and then comparing the given point to
# those coordinates for each contour. This will probably be
# quite slow for complex contours, but for normal use it works
# sufficiently well that the time is not noticeable.
# Nonetheless, improvements could probably be made.
if indices is None:
indices = list(range(len(self.levels)))
dmin = np.inf
conmin = None
segmin = None
xmin = None
ymin = None
point = np.array([x, y])
for icon in indices:
con = self.collections[icon]
trans = con.get_transform()
paths = con.get_paths()
for segNum, linepath in enumerate(paths):
lc = linepath.vertices
# transfer all data points to screen coordinates if desired
if pixel:
lc = trans.transform(lc)
d, xc, leg = _find_closest_point_on_path(lc, point)
if d < dmin:
dmin = d
conmin = icon
segmin = segNum
imin = leg[1]
xmin = xc[0]
ymin = xc[1]
return (conmin, segmin, imin, xmin, ymin, dmin)
class QuadContourSet(ContourSet):
"""
Create and store a set of contour lines or filled regions.
User-callable method: `~axes.Axes.clabel`
Attributes
----------
ax
The axes object in which the contours are drawn.
collections
A silent_list of LineCollections or PolyCollections.
levels
Contour levels.
layers
Same as levels for line contours; half-way between
levels for filled contours. See :meth:`_process_colors` method.
"""
def _process_args(self, *args, **kwargs):
"""
Process args and kwargs.
"""
if isinstance(args[0], QuadContourSet):
if self.levels is None:
self.levels = args[0].levels
self.zmin = args[0].zmin
self.zmax = args[0].zmax
self._corner_mask = args[0]._corner_mask
contour_generator = args[0]._contour_generator
self._mins = args[0]._mins
self._maxs = args[0]._maxs
else:
import matplotlib._contour as _contour
self._corner_mask = kwargs.pop('corner_mask', None)
if self._corner_mask is None:
self._corner_mask = mpl.rcParams['contour.corner_mask']
x, y, z = self._contour_args(args, kwargs)
_mask = ma.getmask(z)
if _mask is ma.nomask or not _mask.any():
_mask = None
contour_generator = _contour.QuadContourGenerator(
x, y, z.filled(), _mask, self._corner_mask, self.nchunk)
t = self.get_transform()
# if the transform is not trans data, and some part of it
# contains transData, transform the xs and ys to data coordinates
if (t != self.ax.transData and
any(t.contains_branch_seperately(self.ax.transData))):
trans_to_data = t - self.ax.transData
pts = (np.vstack([x.flat, y.flat]).T)
transformed_pts = trans_to_data.transform(pts)
x = transformed_pts[..., 0]
y = transformed_pts[..., 1]
self._mins = [ma.min(x), ma.min(y)]
self._maxs = [ma.max(x), ma.max(y)]
self._contour_generator = contour_generator
return kwargs
def _get_allsegs_and_allkinds(self):
"""Compute ``allsegs`` and ``allkinds`` using C extension."""
allsegs = []
if self.filled:
lowers, uppers = self._get_lowers_and_uppers()
allkinds = []
for level, level_upper in zip(lowers, uppers):
vertices, kinds = \
self._contour_generator.create_filled_contour(
level, level_upper)
allsegs.append(vertices)
allkinds.append(kinds)
else:
allkinds = None
for level in self.levels:
vertices = self._contour_generator.create_contour(level)
allsegs.append(vertices)
return allsegs, allkinds
def _contour_args(self, args, kwargs):
if self.filled:
fn = 'contourf'
else:
fn = 'contour'
Nargs = len(args)
if Nargs <= 2:
z = ma.asarray(args[0], dtype=np.float64)
x, y = self._initialize_x_y(z)
args = args[1:]
elif Nargs <= 4:
x, y, z = self._check_xyz(args[:3], kwargs)
args = args[3:]
else:
raise TypeError("Too many arguments to %s; see help(%s)" %
(fn, fn))
z = ma.masked_invalid(z, copy=False)
self.zmax = float(z.max())
self.zmin = float(z.min())
if self.logscale and self.zmin <= 0:
z = ma.masked_where(z <= 0, z)
cbook._warn_external('Log scale: values of z <= 0 have been '
'masked')
self.zmin = float(z.min())
self._contour_level_args(z, args)
return (x, y, z)
def _check_xyz(self, args, kwargs):
"""
For functions like contour, check that the dimensions
of the input arrays match; if x and y are 1D, convert
them to 2D using meshgrid.
Possible change: I think we should make and use an ArgumentError
Exception class (here and elsewhere).
"""
x, y = args[:2]
kwargs = self.ax._process_unit_info(xdata=x, ydata=y, kwargs=kwargs)
x = self.ax.convert_xunits(x)
y = self.ax.convert_yunits(y)
x = np.asarray(x, dtype=np.float64)
y = np.asarray(y, dtype=np.float64)
z = ma.asarray(args[2], dtype=np.float64)
if z.ndim != 2:
raise TypeError("Input z must be a 2D array.")
elif z.shape[0] < 2 or z.shape[1] < 2:
raise TypeError("Input z must be at least a 2x2 array.")
else:
Ny, Nx = z.shape
if x.ndim != y.ndim:
raise TypeError("Number of dimensions of x and y should match.")
if x.ndim == 1:
nx, = x.shape
ny, = y.shape
if nx != Nx:
raise TypeError("Length of x must be number of columns in z.")
if ny != Ny:
raise TypeError("Length of y must be number of rows in z.")
x, y = np.meshgrid(x, y)
elif x.ndim == 2:
if x.shape != z.shape:
raise TypeError("Shape of x does not match that of z: found "
"{0} instead of {1}.".format(x.shape, z.shape))
if y.shape != z.shape:
raise TypeError("Shape of y does not match that of z: found "
"{0} instead of {1}.".format(y.shape, z.shape))
else:
raise TypeError("Inputs x and y must be 1D or 2D.")
return x, y, z
def _initialize_x_y(self, z):
"""
Return X, Y arrays such that contour(Z) will match imshow(Z)
if origin is not None.
The center of pixel Z[i,j] depends on origin:
if origin is None, x = j, y = i;
if origin is 'lower', x = j + 0.5, y = i + 0.5;
if origin is 'upper', x = j + 0.5, y = Nrows - i - 0.5
If extent is not None, x and y will be scaled to match,
as in imshow.
If origin is None and extent is not None, then extent
will give the minimum and maximum values of x and y.
"""
if z.ndim != 2:
raise TypeError("Input must be a 2D array.")
elif z.shape[0] < 2 or z.shape[1] < 2:
raise TypeError("Input z must be at least a 2x2 array.")
else:
Ny, Nx = z.shape
if self.origin is None: # Not for image-matching.
if self.extent is None:
return np.meshgrid(np.arange(Nx), np.arange(Ny))
else:
x0, x1, y0, y1 = self.extent
x = np.linspace(x0, x1, Nx)
y = np.linspace(y0, y1, Ny)
return np.meshgrid(x, y)
# Match image behavior:
if self.extent is None:
x0, x1, y0, y1 = (0, Nx, 0, Ny)
else:
x0, x1, y0, y1 = self.extent
dx = (x1 - x0) / Nx
dy = (y1 - y0) / Ny
x = x0 + (np.arange(Nx) + 0.5) * dx
y = y0 + (np.arange(Ny) + 0.5) * dy
if self.origin == 'upper':
y = y[::-1]
return np.meshgrid(x, y)
_contour_doc = """
Plot contours.
Call signature::
contour([X, Y,] Z, [levels], **kwargs)
`.contour` and `.contourf` draw contour lines and filled contours,
respectively. Except as noted, function signatures and return values
are the same for both versions.
Parameters
----------
X, Y : array-like, optional
The coordinates of the values in *Z*.
*X* and *Y* must both be 2-D with the same shape as *Z* (e.g.
created via `numpy.meshgrid`), or they must both be 1-D such
that ``len(X) == M`` is the number of columns in *Z* and
``len(Y) == N`` is the number of rows in *Z*.
If not given, they are assumed to be integer indices, i.e.
``X = range(M)``, ``Y = range(N)``.
Z : array-like(N, M)
The height values over which the contour is drawn.
levels : int or array-like, optional
Determines the number and positions of the contour lines / regions.
If an int *n*, use *n* data intervals; i.e. draw *n+1* contour
lines. The level heights are automatically chosen.
If array-like, draw contour lines at the specified levels.
The values must be in increasing order.
Returns
-------
c : `~.contour.QuadContourSet`
Other Parameters
----------------
corner_mask : bool, optional
Enable/disable corner masking, which only has an effect if *Z* is
a masked array. If ``False``, any quad touching a masked point is
masked out. If ``True``, only the triangular corners of quads
nearest those points are always masked out, other triangular
corners comprising three unmasked points are contoured as usual.
Defaults to :rc:`contour.corner_mask`, which defaults to ``True``.
colors : color string or sequence of colors, optional
The colors of the levels, i.e. the lines for `.contour` and the
areas for `.contourf`.
The sequence is cycled for the levels in ascending order. If the
sequence is shorter than the number of levels, it's repeated.
As a shortcut, single color strings may be used in place of
one-element lists, i.e. ``'red'`` instead of ``['red']`` to color
all levels with the same color. This shortcut does only work for
color strings, not for other ways of specifying colors.
By default (value *None*), the colormap specified by *cmap*
will be used.
alpha : float, optional
The alpha blending value, between 0 (transparent) and 1 (opaque).
cmap : str or `.Colormap`, optional
A `.Colormap` instance or registered colormap name. The colormap
maps the level values to colors.
Defaults to :rc:`image.cmap`.
If given, *colors* take precedence over *cmap*.
norm : `~matplotlib.colors.Normalize`, optional
If a colormap is used, the `.Normalize` instance scales the level
values to the canonical colormap range [0, 1] for mapping to
colors. If not given, the default linear scaling is used.
vmin, vmax : float, optional
If not *None*, either or both of these values will be supplied to
the `.Normalize` instance, overriding the default color scaling
based on *levels*.
origin : {*None*, 'upper', 'lower', 'image'}, optional
Determines the orientation and exact position of *Z* by specifying
the position of ``Z[0, 0]``. This is only relevant, if *X*, *Y*
are not given.
- *None*: ``Z[0, 0]`` is at X=0, Y=0 in the lower left corner.
- 'lower': ``Z[0, 0]`` is at X=0.5, Y=0.5 in the lower left corner.
- 'upper': ``Z[0, 0]`` is at X=N+0.5, Y=0.5 in the upper left
corner.
- 'image': Use the value from :rc:`image.origin`.
extent : (x0, x1, y0, y1), optional
If *origin* is not *None*, then *extent* is interpreted as in
`.imshow`: it gives the outer pixel boundaries. In this case, the
position of Z[0,0] is the center of the pixel, not a corner. If
*origin* is *None*, then (*x0*, *y0*) is the position of Z[0,0],
and (*x1*, *y1*) is the position of Z[-1,-1].
This argument is ignored if *X* and *Y* are specified in the call
to contour.
locator : ticker.Locator subclass, optional
The locator is used to determine the contour levels if they
are not given explicitly via *levels*.
Defaults to `~.ticker.MaxNLocator`.
extend : {'neither', 'both', 'min', 'max'}, optional, default: \
'neither'
Determines the ``contourf``-coloring of values that are outside the
*levels* range.
If 'neither', values outside the *levels* range are not colored.
If 'min', 'max' or 'both', color the values below, above or below
and above the *levels* range.
Values below ``min(levels)`` and above ``max(levels)`` are mapped
to the under/over values of the `.Colormap`. Note, that most
colormaps do not have dedicated colors for these by default, so
that the over and under values are the edge values of the colormap.
You may want to set these values explicitly using
`.Colormap.set_under` and `.Colormap.set_over`.
.. note::
An exising `.QuadContourSet` does not get notified if
properties of its colormap are changed. Therefore, an explicit
call `.QuadContourSet.changed()` is needed after modifying the
colormap. The explicit call can be left out, if a colorbar is
assigned to the `.QuadContourSet` because it internally calls
`.QuadContourSet.changed()`.
Example::
x = np.arange(1, 10)
y = x.reshape(-1, 1)
h = x * y
cs = plt.contourf(h, levels=[10, 30, 50],
colors=['#808080', '#A0A0A0', '#C0C0C0'], extend='both')
cs.cmap.set_over('red')
cs.cmap.set_under('blue')
cs.changed()
xunits, yunits : registered units, optional
Override axis units by specifying an instance of a
:class:`matplotlib.units.ConversionInterface`.
antialiased : bool, optional
Enable antialiasing, overriding the defaults. For
filled contours, the default is *True*. For line contours,
it is taken from :rc:`lines.antialiased`.
Nchunk : int >= 0, optional
If 0, no subdivision of the domain. Specify a positive integer to
divide the domain into subdomains of *nchunk* by *nchunk* quads.
Chunking reduces the maximum length of polygons generated by the
contouring algorithm which reduces the rendering workload passed
on to the backend and also requires slightly less RAM. It can
however introduce rendering artifacts at chunk boundaries depending
on the backend, the *antialiased* flag and value of *alpha*.
linewidths : float or sequence of float, optional
*Only applies to* `.contour`.
The line width of the contour lines.
If a number, all levels will be plotted with this linewidth.
If a sequence, the levels in ascending order will be plotted with
the linewidths in the order specified.
Defaults to :rc:`lines.linewidth`.
linestyles : {*None*, 'solid', 'dashed', 'dashdot', 'dotted'}, optional
*Only applies to* `.contour`.
If *linestyles* is *None*, the default is 'solid' unless the lines
are monochrome. In that case, negative contours will take their
linestyle from :rc:`contour.negative_linestyle` setting.
*linestyles* can also be an iterable of the above strings
specifying a set of linestyles to be used. If this
iterable is shorter than the number of contour levels
it will be repeated as necessary.
hatches : List[str], optional
*Only applies to* `.contourf`.
A list of cross hatch patterns to use on the filled areas.
If None, no hatching will be added to the contour.
Hatching is supported in the PostScript, PDF, SVG and Agg
backends only.
Notes
-----
1. `.contourf` differs from the MATLAB version in that it does not draw
the polygon edges. To draw edges, add line contours with calls to
`.contour`.
2. `.contourf` fills intervals that are closed at the top; that is, for
boundaries *z1* and *z2*, the filled region is::
z1 < Z <= z2
except for the lowest interval, which is closed on both sides (i.e.
it includes the lowest value).
"""
|
a2dfea37d0f8d8314cc0f73ca879d5403ff2fd137436151a48b2f6078edf62af
|
"""
This is a python interface to Adobe Font Metrics Files. Although a
number of other python implementations exist, and may be more complete
than this, it was decided not to go with them because they were
either:
1) copyrighted or used a non-BSD compatible license
2) had too many dependencies and a free standing lib was needed
3) Did more than needed and it was easier to write afresh rather than
figure out how to get just what was needed.
It is pretty easy to use, and requires only built-in python libs:
>>> from matplotlib import rcParams
>>> import os.path
>>> afm_fname = os.path.join(rcParams['datapath'],
... 'fonts', 'afm', 'ptmr8a.afm')
>>>
>>> from matplotlib.afm import AFM
>>> with open(afm_fname, 'rb') as fh:
... afm = AFM(fh)
>>> afm.string_width_height('What the heck?')
(6220.0, 694)
>>> afm.get_fontname()
'Times-Roman'
>>> afm.get_kern_dist('A', 'f')
0
>>> afm.get_kern_dist('A', 'y')
-92.0
>>> afm.get_bbox_char('!')
[130, -9, 238, 676]
As in the Adobe Font Metrics File Format Specification, all dimensions
are given in units of 1/1000 of the scale factor (point size) of the font
being used.
"""
from collections import namedtuple
import logging
import re
from ._mathtext_data import uni2type1
from matplotlib.cbook import deprecated
_log = logging.getLogger(__name__)
def _to_int(x):
# Some AFM files have floats where we are expecting ints -- there is
# probably a better way to handle this (support floats, round rather
# than truncate). But I don't know what the best approach is now and
# this change to _to_int should at least prevent mpl from crashing on
# these JDH (2009-11-06)
return int(float(x))
def _to_float(x):
# Some AFM files use "," instead of "." as decimal separator -- this
# shouldn't be ambiguous (unless someone is wicked enough to use "," as
# thousands separator...).
if isinstance(x, bytes):
# Encoding doesn't really matter -- if we have codepoints >127 the call
# to float() will error anyways.
x = x.decode('latin-1')
return float(x.replace(',', '.'))
def _to_str(x):
return x.decode('utf8')
def _to_list_of_ints(s):
s = s.replace(b',', b' ')
return [_to_int(val) for val in s.split()]
def _to_list_of_floats(s):
return [_to_float(val) for val in s.split()]
def _to_bool(s):
if s.lower().strip() in (b'false', b'0', b'no'):
return False
else:
return True
def _sanity_check(fh):
"""
Check if the file looks like AFM; if it doesn't, raise `RuntimeError`.
"""
# Remember the file position in case the caller wants to
# do something else with the file.
pos = fh.tell()
try:
line = next(fh)
finally:
fh.seek(pos, 0)
# AFM spec, Section 4: The StartFontMetrics keyword [followed by a
# version number] must be the first line in the file, and the
# EndFontMetrics keyword must be the last non-empty line in the
# file. We just check the first line.
if not line.startswith(b'StartFontMetrics'):
raise RuntimeError('Not an AFM file')
def _parse_header(fh):
"""
Reads the font metrics header (up to the char metrics) and returns
a dictionary mapping *key* to *val*. *val* will be converted to the
appropriate python type as necessary; e.g.:
* 'False'->False
* '0'->0
* '-168 -218 1000 898'-> [-168, -218, 1000, 898]
Dictionary keys are
StartFontMetrics, FontName, FullName, FamilyName, Weight,
ItalicAngle, IsFixedPitch, FontBBox, UnderlinePosition,
UnderlineThickness, Version, Notice, EncodingScheme, CapHeight,
XHeight, Ascender, Descender, StartCharMetrics
"""
header_converters = {
b'StartFontMetrics': _to_float,
b'FontName': _to_str,
b'FullName': _to_str,
b'FamilyName': _to_str,
b'Weight': _to_str,
b'ItalicAngle': _to_float,
b'IsFixedPitch': _to_bool,
b'FontBBox': _to_list_of_ints,
b'UnderlinePosition': _to_float,
b'UnderlineThickness': _to_float,
b'Version': _to_str,
# Some AFM files have non-ASCII characters (which are not allowed by
# the spec). Given that there is actually no public API to even access
# this field, just return it as straight bytes.
b'Notice': lambda x: x,
b'EncodingScheme': _to_str,
b'CapHeight': _to_float, # Is the second version a mistake, or
b'Capheight': _to_float, # do some AFM files contain 'Capheight'? -JKS
b'XHeight': _to_float,
b'Ascender': _to_float,
b'Descender': _to_float,
b'StdHW': _to_float,
b'StdVW': _to_float,
b'StartCharMetrics': _to_int,
b'CharacterSet': _to_str,
b'Characters': _to_int,
}
d = {}
for line in fh:
line = line.rstrip()
if line.startswith(b'Comment'):
continue
lst = line.split(b' ', 1)
key = lst[0]
if len(lst) == 2:
val = lst[1]
else:
val = b''
try:
converter = header_converters[key]
except KeyError:
_log.error('Found an unknown keyword in AFM header (was %r)' % key)
continue
try:
d[key] = converter(val)
except ValueError:
_log.error('Value error parsing header in AFM: %s, %s', key, val)
continue
if key == b'StartCharMetrics':
return d
raise RuntimeError('Bad parse')
CharMetrics = namedtuple('CharMetrics', 'width, name, bbox')
CharMetrics.__doc__ = """
Represents the character metrics of a single character.
Notes
-----
The fields do currently only describe a subset of character metrics
information defined in the AFM standard.
"""
CharMetrics.width.__doc__ = """The character width (WX)."""
CharMetrics.name.__doc__ = """The character name (N)."""
CharMetrics.bbox.__doc__ = """
The bbox of the character (B) as a tuple (*llx*, *lly*, *urx*, *ury*)."""
def _parse_char_metrics(fh):
"""
Parse the given filehandle for character metrics information and return
the information as dicts.
It is assumed that the file cursor is on the line behind
'StartCharMetrics'.
Returns
-------
ascii_d : dict
A mapping "ASCII num of the character" to `.CharMetrics`.
name_d : dict
A mapping "character name" to `.CharMetrics`.
Notes
-----
This function is incomplete per the standard, but thus far parses
all the sample afm files tried.
"""
required_keys = {'C', 'WX', 'N', 'B'}
ascii_d = {}
name_d = {}
for line in fh:
# We are defensively letting values be utf8. The spec requires
# ascii, but there are non-compliant fonts in circulation
line = _to_str(line.rstrip()) # Convert from byte-literal
if line.startswith('EndCharMetrics'):
return ascii_d, name_d
# Split the metric line into a dictionary, keyed by metric identifiers
vals = dict(s.strip().split(' ', 1) for s in line.split(';') if s)
# There may be other metrics present, but only these are needed
if not required_keys.issubset(vals):
raise RuntimeError('Bad char metrics line: %s' % line)
num = _to_int(vals['C'])
wx = _to_float(vals['WX'])
name = vals['N']
bbox = _to_list_of_floats(vals['B'])
bbox = list(map(int, bbox))
metrics = CharMetrics(wx, name, bbox)
# Workaround: If the character name is 'Euro', give it the
# corresponding character code, according to WinAnsiEncoding (see PDF
# Reference).
if name == 'Euro':
num = 128
if num != -1:
ascii_d[num] = metrics
name_d[name] = metrics
raise RuntimeError('Bad parse')
def _parse_kern_pairs(fh):
"""
Return a kern pairs dictionary; keys are (*char1*, *char2*) tuples and
values are the kern pair value. For example, a kern pairs line like
``KPX A y -50``
will be represented as::
d[ ('A', 'y') ] = -50
"""
line = next(fh)
if not line.startswith(b'StartKernPairs'):
raise RuntimeError('Bad start of kern pairs data: %s' % line)
d = {}
for line in fh:
line = line.rstrip()
if not line:
continue
if line.startswith(b'EndKernPairs'):
next(fh) # EndKernData
return d
vals = line.split()
if len(vals) != 4 or vals[0] != b'KPX':
raise RuntimeError('Bad kern pairs line: %s' % line)
c1, c2, val = _to_str(vals[1]), _to_str(vals[2]), _to_float(vals[3])
d[(c1, c2)] = val
raise RuntimeError('Bad kern pairs parse')
CompositePart = namedtuple('CompositePart', 'name, dx, dy')
CompositePart.__doc__ = """
Represents the information on a composite element of a composite char."""
CompositePart.name.__doc__ = """Name of the part, e.g. 'acute'."""
CompositePart.dx.__doc__ = """x-displacement of the part from the origin."""
CompositePart.dy.__doc__ = """y-displacement of the part from the origin."""
def _parse_composites(fh):
"""
Parse the given filehandle for composites information return them as a
dict.
It is assumed that the file cursor is on the line behind 'StartComposites'.
Returns
-------
composites : dict
A dict mapping composite character names to a parts list. The parts
list is a list of `.CompositePart` entries describing the parts of
the composite.
Example
-------
A composite definition line::
CC Aacute 2 ; PCC A 0 0 ; PCC acute 160 170 ;
will be represented as::
composites['Aacute'] = [CompositePart(name='A', dx=0, dy=0),
CompositePart(name='acute', dx=160, dy=170)]
"""
composites = {}
for line in fh:
line = line.rstrip()
if not line:
continue
if line.startswith(b'EndComposites'):
return composites
vals = line.split(b';')
cc = vals[0].split()
name, numParts = cc[1], _to_int(cc[2])
pccParts = []
for s in vals[1:-1]:
pcc = s.split()
part = CompositePart(pcc[1], _to_float(pcc[2]), _to_float(pcc[3]))
pccParts.append(part)
composites[name] = pccParts
raise RuntimeError('Bad composites parse')
def _parse_optional(fh):
"""
Parse the optional fields for kern pair data and composites.
Returns
-------
kern_data : dict
A dict containing kerning information. May be empty.
See `._parse_kern_pairs`.
composites : dict
A dict containing composite information. May be empty.
See `._parse_composites`.
"""
optional = {
b'StartKernData': _parse_kern_pairs,
b'StartComposites': _parse_composites,
}
d = {b'StartKernData': {},
b'StartComposites': {}}
for line in fh:
line = line.rstrip()
if not line:
continue
key = line.split()[0]
if key in optional:
d[key] = optional[key](fh)
return d[b'StartKernData'], d[b'StartComposites']
@deprecated("3.0", alternative="the AFM class")
def parse_afm(fh):
return _parse_afm(fh)
def _parse_afm(fh):
"""
Parse the Adobe Font Metrics file in file handle *fh*.
Returns
-------
header : dict
A header dict. See :func:`_parse_header`.
cmetrics_by_ascii : dict
From :func:`_parse_char_metrics`.
cmetrics_by_name : dict
From :func:`_parse_char_metrics`.
kernpairs : dict
From :func:`_parse_kern_pairs`.
composites : dict
From :func:`_parse_composites`
"""
_sanity_check(fh)
header = _parse_header(fh)
cmetrics_by_ascii, cmetrics_by_name = _parse_char_metrics(fh)
kernpairs, composites = _parse_optional(fh)
return header, cmetrics_by_ascii, cmetrics_by_name, kernpairs, composites
class AFM(object):
def __init__(self, fh):
"""Parse the AFM file in file object *fh*."""
(self._header,
self._metrics,
self._metrics_by_name,
self._kern,
self._composite) = _parse_afm(fh)
def get_bbox_char(self, c, isord=False):
if not isord:
c = ord(c)
return self._metrics[c].bbox
def string_width_height(self, s):
"""
Return the string width (including kerning) and string height
as a (*w*, *h*) tuple.
"""
if not len(s):
return 0, 0
total_width = 0
namelast = None
miny = 1e9
maxy = 0
for c in s:
if c == '\n':
continue
wx, name, bbox = self._metrics[ord(c)]
total_width += wx + self._kern.get((namelast, name), 0)
l, b, w, h = bbox
miny = min(miny, b)
maxy = max(maxy, b + h)
namelast = name
return total_width, maxy - miny
def get_str_bbox_and_descent(self, s):
"""Return the string bounding box and the maximal descent."""
if not len(s):
return 0, 0, 0, 0, 0
total_width = 0
namelast = None
miny = 1e9
maxy = 0
left = 0
if not isinstance(s, str):
s = _to_str(s)
for c in s:
if c == '\n':
continue
name = uni2type1.get(ord(c), 'question')
try:
wx, _, bbox = self._metrics_by_name[name]
except KeyError:
name = 'question'
wx, _, bbox = self._metrics_by_name[name]
total_width += wx + self._kern.get((namelast, name), 0)
l, b, w, h = bbox
left = min(left, l)
miny = min(miny, b)
maxy = max(maxy, b + h)
namelast = name
return left, miny, total_width, maxy - miny, -miny
def get_str_bbox(self, s):
"""Return the string bounding box."""
return self.get_str_bbox_and_descent(s)[:4]
def get_name_char(self, c, isord=False):
"""Get the name of the character, i.e., ';' is 'semicolon'."""
if not isord:
c = ord(c)
return self._metrics[c].name
def get_width_char(self, c, isord=False):
"""
Get the width of the character from the character metric WX field.
"""
if not isord:
c = ord(c)
return self._metrics[c].width
def get_width_from_char_name(self, name):
"""Get the width of the character from a type1 character name."""
return self._metrics_by_name[name].width
def get_height_char(self, c, isord=False):
"""Get the bounding box (ink) height of character *c* (space is 0)."""
if not isord:
c = ord(c)
return self._metrics[c].bbox[-1]
def get_kern_dist(self, c1, c2):
"""
Return the kerning pair distance (possibly 0) for chars *c1* and *c2*.
"""
name1, name2 = self.get_name_char(c1), self.get_name_char(c2)
return self.get_kern_dist_from_name(name1, name2)
def get_kern_dist_from_name(self, name1, name2):
"""
Return the kerning pair distance (possibly 0) for chars
*name1* and *name2*.
"""
return self._kern.get((name1, name2), 0)
def get_fontname(self):
"""Return the font name, e.g., 'Times-Roman'."""
return self._header[b'FontName']
def get_fullname(self):
"""Return the font full name, e.g., 'Times-Roman'."""
name = self._header.get(b'FullName')
if name is None: # use FontName as a substitute
name = self._header[b'FontName']
return name
def get_familyname(self):
"""Return the font family name, e.g., 'Times'."""
name = self._header.get(b'FamilyName')
if name is not None:
return name
# FamilyName not specified so we'll make a guess
name = self.get_fullname()
extras = (r'(?i)([ -](regular|plain|italic|oblique|bold|semibold|'
r'light|ultralight|extra|condensed))+$')
return re.sub(extras, '', name)
@property
def family_name(self):
"""The font family name, e.g., 'Times'."""
return self.get_familyname()
def get_weight(self):
"""Return the font weight, e.g., 'Bold' or 'Roman'."""
return self._header[b'Weight']
def get_angle(self):
"""Return the fontangle as float."""
return self._header[b'ItalicAngle']
def get_capheight(self):
"""Return the cap height as float."""
return self._header[b'CapHeight']
def get_xheight(self):
"""Return the xheight as float."""
return self._header[b'XHeight']
def get_underline_thickness(self):
"""Return the underline thickness as float."""
return self._header[b'UnderlineThickness']
def get_horizontal_stem_width(self):
"""
Return the standard horizontal stem width as float, or *None* if
not specified in AFM file.
"""
return self._header.get(b'StdHW', None)
def get_vertical_stem_width(self):
"""
Return the standard vertical stem width as float, or *None* if
not specified in AFM file.
"""
return self._header.get(b'StdVW', None)
|
c151a2efe995e6c9f574605786d8ee0fd48b8addb837873c943251c9553070f0
|
"""
A module providing some utility functions regarding bezier path manipulation.
"""
import numpy as np
import matplotlib.cbook as cbook
from matplotlib.path import Path
class NonIntersectingPathException(ValueError):
pass
# some functions
def get_intersection(cx1, cy1, cos_t1, sin_t1,
cx2, cy2, cos_t2, sin_t2):
"""
Return the intersection between the line through (*cx1*, *cy1*) at angle
*t1* and the line through (*cx2, cy2) at angle *t2*.
"""
# line1 => sin_t1 * (x - cx1) - cos_t1 * (y - cy1) = 0.
# line1 => sin_t1 * x + cos_t1 * y = sin_t1*cx1 - cos_t1*cy1
line1_rhs = sin_t1 * cx1 - cos_t1 * cy1
line2_rhs = sin_t2 * cx2 - cos_t2 * cy2
# rhs matrix
a, b = sin_t1, -cos_t1
c, d = sin_t2, -cos_t2
ad_bc = a * d - b * c
if np.abs(ad_bc) < 1.0e-12:
raise ValueError("Given lines do not intersect. Please verify that "
"the angles are not equal or differ by 180 degrees.")
# rhs_inverse
a_, b_ = d, -b
c_, d_ = -c, a
a_, b_, c_, d_ = [k / ad_bc for k in [a_, b_, c_, d_]]
x = a_ * line1_rhs + b_ * line2_rhs
y = c_ * line1_rhs + d_ * line2_rhs
return x, y
def get_normal_points(cx, cy, cos_t, sin_t, length):
"""
For a line passing through (*cx*, *cy*) and having a angle *t*, return
locations of the two points located along its perpendicular line at the
distance of *length*.
"""
if length == 0.:
return cx, cy, cx, cy
cos_t1, sin_t1 = sin_t, -cos_t
cos_t2, sin_t2 = -sin_t, cos_t
x1, y1 = length * cos_t1 + cx, length * sin_t1 + cy
x2, y2 = length * cos_t2 + cx, length * sin_t2 + cy
return x1, y1, x2, y2
# BEZIER routines
# subdividing bezier curve
# http://www.cs.mtu.edu/~shene/COURSES/cs3621/NOTES/spline/Bezier/bezier-sub.html
def _de_casteljau1(beta, t):
next_beta = beta[:-1] * (1 - t) + beta[1:] * t
return next_beta
def split_de_casteljau(beta, t):
"""
Split a bezier segment defined by its control points *beta* into two
separate segments divided at *t* and return their control points.
"""
beta = np.asarray(beta)
beta_list = [beta]
while True:
beta = _de_casteljau1(beta, t)
beta_list.append(beta)
if len(beta) == 1:
break
left_beta = [beta[0] for beta in beta_list]
right_beta = [beta[-1] for beta in reversed(beta_list)]
return left_beta, right_beta
@cbook._rename_parameter("3.1", "tolerence", "tolerance")
def find_bezier_t_intersecting_with_closedpath(
bezier_point_at_t, inside_closedpath, t0=0., t1=1., tolerance=0.01):
""" Find a parameter t0 and t1 of the given bezier path which
bounds the intersecting points with a provided closed
path(*inside_closedpath*). Search starts from *t0* and *t1* and it
uses a simple bisecting algorithm therefore one of the end point
must be inside the path while the other doesn't. The search stop
when |t0-t1| gets smaller than the given tolerance.
value for
- bezier_point_at_t : a function which returns x, y coordinates at *t*
- inside_closedpath : return True if the point is inside the path
"""
# inside_closedpath : function
start = bezier_point_at_t(t0)
end = bezier_point_at_t(t1)
start_inside = inside_closedpath(start)
end_inside = inside_closedpath(end)
if start_inside == end_inside and start != end:
raise NonIntersectingPathException(
"Both points are on the same side of the closed path")
while True:
# return if the distance is smaller than the tolerance
if np.hypot(start[0] - end[0], start[1] - end[1]) < tolerance:
return t0, t1
# calculate the middle point
middle_t = 0.5 * (t0 + t1)
middle = bezier_point_at_t(middle_t)
middle_inside = inside_closedpath(middle)
if start_inside ^ middle_inside:
t1 = middle_t
end = middle
end_inside = middle_inside
else:
t0 = middle_t
start = middle
start_inside = middle_inside
class BezierSegment(object):
"""
A simple class of a 2-dimensional bezier segment
"""
# Higher order bezier lines can be supported by simplying adding
# corresponding values.
_binom_coeff = {1: np.array([1., 1.]),
2: np.array([1., 2., 1.]),
3: np.array([1., 3., 3., 1.])}
def __init__(self, control_points):
"""
*control_points* : location of contol points. It needs have a
shape of n * 2, where n is the order of the bezier line. 1<=
n <= 3 is supported.
"""
_o = len(control_points)
self._orders = np.arange(_o)
_coeff = BezierSegment._binom_coeff[_o - 1]
xx, yy = np.asarray(control_points).T
self._px = xx * _coeff
self._py = yy * _coeff
def point_at_t(self, t):
"evaluate a point at t"
tt = ((1 - t) ** self._orders)[::-1] * t ** self._orders
_x = np.dot(tt, self._px)
_y = np.dot(tt, self._py)
return _x, _y
@cbook._rename_parameter("3.1", "tolerence", "tolerance")
def split_bezier_intersecting_with_closedpath(
bezier, inside_closedpath, tolerance=0.01):
"""
bezier : control points of the bezier segment
inside_closedpath : a function which returns true if the point is inside
the path
"""
bz = BezierSegment(bezier)
bezier_point_at_t = bz.point_at_t
t0, t1 = find_bezier_t_intersecting_with_closedpath(
bezier_point_at_t, inside_closedpath, tolerance=tolerance)
_left, _right = split_de_casteljau(bezier, (t0 + t1) / 2.)
return _left, _right
@cbook.deprecated("3.1")
@cbook._rename_parameter("3.1", "tolerence", "tolerance")
def find_r_to_boundary_of_closedpath(
inside_closedpath, xy, cos_t, sin_t, rmin=0., rmax=1., tolerance=0.01):
"""
Find a radius r (centered at *xy*) between *rmin* and *rmax* at
which it intersect with the path.
inside_closedpath : function
cx, cy : center
cos_t, sin_t : cosine and sine for the angle
rmin, rmax :
"""
cx, cy = xy
def _f(r):
return cos_t * r + cx, sin_t * r + cy
find_bezier_t_intersecting_with_closedpath(
_f, inside_closedpath, t0=rmin, t1=rmax, tolerance=tolerance)
# matplotlib specific
@cbook._rename_parameter("3.1", "tolerence", "tolerance")
def split_path_inout(path, inside, tolerance=0.01, reorder_inout=False):
""" divide a path into two segment at the point where inside(x, y)
becomes False.
"""
path_iter = path.iter_segments()
ctl_points, command = next(path_iter)
begin_inside = inside(ctl_points[-2:]) # true if begin point is inside
ctl_points_old = ctl_points
concat = np.concatenate
iold = 0
i = 1
for ctl_points, command in path_iter:
iold = i
i += len(ctl_points) // 2
if inside(ctl_points[-2:]) != begin_inside:
bezier_path = concat([ctl_points_old[-2:], ctl_points])
break
ctl_points_old = ctl_points
else:
raise ValueError("The path does not intersect with the patch")
bp = bezier_path.reshape((-1, 2))
left, right = split_bezier_intersecting_with_closedpath(
bp, inside, tolerance)
if len(left) == 2:
codes_left = [Path.LINETO]
codes_right = [Path.MOVETO, Path.LINETO]
elif len(left) == 3:
codes_left = [Path.CURVE3, Path.CURVE3]
codes_right = [Path.MOVETO, Path.CURVE3, Path.CURVE3]
elif len(left) == 4:
codes_left = [Path.CURVE4, Path.CURVE4, Path.CURVE4]
codes_right = [Path.MOVETO, Path.CURVE4, Path.CURVE4, Path.CURVE4]
else:
raise AssertionError("This should never be reached")
verts_left = left[1:]
verts_right = right[:]
if path.codes is None:
path_in = Path(concat([path.vertices[:i], verts_left]))
path_out = Path(concat([verts_right, path.vertices[i:]]))
else:
path_in = Path(concat([path.vertices[:iold], verts_left]),
concat([path.codes[:iold], codes_left]))
path_out = Path(concat([verts_right, path.vertices[i:]]),
concat([codes_right, path.codes[i:]]))
if reorder_inout and not begin_inside:
path_in, path_out = path_out, path_in
return path_in, path_out
def inside_circle(cx, cy, r):
r2 = r ** 2
def _f(xy):
x, y = xy
return (x - cx) ** 2 + (y - cy) ** 2 < r2
return _f
# quadratic bezier lines
def get_cos_sin(x0, y0, x1, y1):
dx, dy = x1 - x0, y1 - y0
d = (dx * dx + dy * dy) ** .5
# Account for divide by zero
if d == 0:
return 0.0, 0.0
return dx / d, dy / d
@cbook._rename_parameter("3.1", "tolerence", "tolerance")
def check_if_parallel(dx1, dy1, dx2, dy2, tolerance=1.e-5):
""" returns
* 1 if two lines are parallel in same direction
* -1 if two lines are parallel in opposite direction
* 0 otherwise
"""
theta1 = np.arctan2(dx1, dy1)
theta2 = np.arctan2(dx2, dy2)
dtheta = np.abs(theta1 - theta2)
if dtheta < tolerance:
return 1
elif np.abs(dtheta - np.pi) < tolerance:
return -1
else:
return False
def get_parallels(bezier2, width):
"""
Given the quadratic bezier control points *bezier2*, returns
control points of quadratic bezier lines roughly parallel to given
one separated by *width*.
"""
# The parallel bezier lines are constructed by following ways.
# c1 and c2 are control points representing the begin and end of the
# bezier line.
# cm is the middle point
c1x, c1y = bezier2[0]
cmx, cmy = bezier2[1]
c2x, c2y = bezier2[2]
parallel_test = check_if_parallel(c1x - cmx, c1y - cmy,
cmx - c2x, cmy - c2y)
if parallel_test == -1:
cbook._warn_external(
"Lines do not intersect. A straight line is used instead.")
cos_t1, sin_t1 = get_cos_sin(c1x, c1y, c2x, c2y)
cos_t2, sin_t2 = cos_t1, sin_t1
else:
# t1 and t2 is the angle between c1 and cm, cm, c2. They are
# also a angle of the tangential line of the path at c1 and c2
cos_t1, sin_t1 = get_cos_sin(c1x, c1y, cmx, cmy)
cos_t2, sin_t2 = get_cos_sin(cmx, cmy, c2x, c2y)
# find c1_left, c1_right which are located along the lines
# through c1 and perpendicular to the tangential lines of the
# bezier path at a distance of width. Same thing for c2_left and
# c2_right with respect to c2.
c1x_left, c1y_left, c1x_right, c1y_right = (
get_normal_points(c1x, c1y, cos_t1, sin_t1, width)
)
c2x_left, c2y_left, c2x_right, c2y_right = (
get_normal_points(c2x, c2y, cos_t2, sin_t2, width)
)
# find cm_left which is the intersecting point of a line through
# c1_left with angle t1 and a line through c2_left with angle
# t2. Same with cm_right.
if parallel_test != 0:
# a special case for a straight line, i.e., angle between two
# lines are smaller than some (arbitrary) value.
cmx_left, cmy_left = (
0.5 * (c1x_left + c2x_left), 0.5 * (c1y_left + c2y_left)
)
cmx_right, cmy_right = (
0.5 * (c1x_right + c2x_right), 0.5 * (c1y_right + c2y_right)
)
else:
cmx_left, cmy_left = get_intersection(c1x_left, c1y_left, cos_t1,
sin_t1, c2x_left, c2y_left,
cos_t2, sin_t2)
cmx_right, cmy_right = get_intersection(c1x_right, c1y_right, cos_t1,
sin_t1, c2x_right, c2y_right,
cos_t2, sin_t2)
# the parallel bezier lines are created with control points of
# [c1_left, cm_left, c2_left] and [c1_right, cm_right, c2_right]
path_left = [(c1x_left, c1y_left),
(cmx_left, cmy_left),
(c2x_left, c2y_left)]
path_right = [(c1x_right, c1y_right),
(cmx_right, cmy_right),
(c2x_right, c2y_right)]
return path_left, path_right
def find_control_points(c1x, c1y, mmx, mmy, c2x, c2y):
"""
Find control points of the Bezier curve passing through (*c1x*, *c1y*),
(*mmx*, *mmy*), and (*c2x*, *c2y*), at parametric values 0, 0.5, and 1.
"""
cmx = .5 * (4 * mmx - (c1x + c2x))
cmy = .5 * (4 * mmy - (c1y + c2y))
return [(c1x, c1y), (cmx, cmy), (c2x, c2y)]
def make_wedged_bezier2(bezier2, width, w1=1., wm=0.5, w2=0.):
"""
Being similar to get_parallels, returns control points of two quadratic
bezier lines having a width roughly parallel to given one separated by
*width*.
"""
# c1, cm, c2
c1x, c1y = bezier2[0]
cmx, cmy = bezier2[1]
c3x, c3y = bezier2[2]
# t1 and t2 is the angle between c1 and cm, cm, c3.
# They are also a angle of the tangential line of the path at c1 and c3
cos_t1, sin_t1 = get_cos_sin(c1x, c1y, cmx, cmy)
cos_t2, sin_t2 = get_cos_sin(cmx, cmy, c3x, c3y)
# find c1_left, c1_right which are located along the lines
# through c1 and perpendicular to the tangential lines of the
# bezier path at a distance of width. Same thing for c3_left and
# c3_right with respect to c3.
c1x_left, c1y_left, c1x_right, c1y_right = (
get_normal_points(c1x, c1y, cos_t1, sin_t1, width * w1)
)
c3x_left, c3y_left, c3x_right, c3y_right = (
get_normal_points(c3x, c3y, cos_t2, sin_t2, width * w2)
)
# find c12, c23 and c123 which are middle points of c1-cm, cm-c3 and
# c12-c23
c12x, c12y = (c1x + cmx) * .5, (c1y + cmy) * .5
c23x, c23y = (cmx + c3x) * .5, (cmy + c3y) * .5
c123x, c123y = (c12x + c23x) * .5, (c12y + c23y) * .5
# tangential angle of c123 (angle between c12 and c23)
cos_t123, sin_t123 = get_cos_sin(c12x, c12y, c23x, c23y)
c123x_left, c123y_left, c123x_right, c123y_right = (
get_normal_points(c123x, c123y, cos_t123, sin_t123, width * wm)
)
path_left = find_control_points(c1x_left, c1y_left,
c123x_left, c123y_left,
c3x_left, c3y_left)
path_right = find_control_points(c1x_right, c1y_right,
c123x_right, c123y_right,
c3x_right, c3y_right)
return path_left, path_right
def make_path_regular(p):
"""
If the :attr:`codes` attribute of `Path` *p* is None, return a copy of *p*
with the :attr:`codes` set to (MOVETO, LINETO, LINETO, ..., LINETO);
otherwise return *p* itself.
"""
c = p.codes
if c is None:
c = np.full(len(p.vertices), Path.LINETO, dtype=Path.code_type)
c[0] = Path.MOVETO
return Path(p.vertices, c)
else:
return p
def concatenate_paths(paths):
"""Concatenate a list of paths into a single path."""
vertices = np.concatenate([p.vertices for p in paths])
codes = np.concatenate([make_path_regular(p).codes for p in paths])
return Path(vertices, codes)
|
a453439025dd44716268195e225449c40cac957773133cfcbcabb51e99ce4e2b
|
"""
The legend module defines the Legend class, which is responsible for
drawing legends associated with axes and/or figures.
.. important::
It is unlikely that you would ever create a Legend instance
manually. Most users would normally create a legend via the
:meth:`~matplotlib.axes.Axes.legend` function. For more details on legends
there is also a :doc:`legend guide </tutorials/intermediate/legend_guide>`.
The Legend class can be considered as a container of legend handles and
legend texts. Creation of corresponding legend handles from the plot elements
in the axes or figures (e.g., lines, patches, etc.) are specified by the
handler map, which defines the mapping between the plot elements and the
legend handlers to be used (the default legend handlers are defined in the
:mod:`~matplotlib.legend_handler` module). Note that not all kinds of
artist are supported by the legend yet by default but it is possible to
extend the legend handler's capabilities to support arbitrary objects. See
the :doc:`legend guide </tutorials/intermediate/legend_guide>` for more
information.
"""
import logging
import numpy as np
from matplotlib import cbook
from matplotlib import rcParams
from matplotlib import cbook, docstring
from matplotlib.artist import Artist, allow_rasterization
from matplotlib.cbook import silent_list, is_hashable, warn_deprecated
from matplotlib.font_manager import FontProperties
from matplotlib.lines import Line2D
from matplotlib.patches import Patch, Rectangle, Shadow, FancyBboxPatch
from matplotlib.collections import (LineCollection, RegularPolyCollection,
CircleCollection, PathCollection,
PolyCollection)
from matplotlib.transforms import Bbox, BboxBase, TransformedBbox
from matplotlib.transforms import BboxTransformTo, BboxTransformFrom
from matplotlib.offsetbox import HPacker, VPacker, TextArea, DrawingArea
from matplotlib.offsetbox import DraggableOffsetBox
from matplotlib.container import ErrorbarContainer, BarContainer, StemContainer
from . import legend_handler
class DraggableLegend(DraggableOffsetBox):
def __init__(self, legend, use_blit=False, update="loc"):
"""
Wrapper around a `.Legend` to support mouse dragging.
Parameters
----------
legend : `.Legend`
The `.Legend` instance to wrap.
use_blit : bool, optional
Use blitting for faster image composition. For details see
:ref:`func-animation`.
update : {'loc', 'bbox'}, optional
If "loc", update the *loc* parameter of the legend upon finalizing.
If "bbox", update the *bbox_to_anchor* parameter.
"""
self.legend = legend
if update in ["loc", "bbox"]:
self._update = update
else:
raise ValueError("update parameter '%s' is not supported." %
update)
DraggableOffsetBox.__init__(self, legend, legend._legend_box,
use_blit=use_blit)
def artist_picker(self, legend, evt):
return self.legend.contains(evt)
def finalize_offset(self):
loc_in_canvas = self.get_loc_in_canvas()
if self._update == "loc":
self._update_loc(loc_in_canvas)
elif self._update == "bbox":
self._update_bbox_to_anchor(loc_in_canvas)
else:
raise RuntimeError("update parameter '%s' is not supported." %
self.update)
def _update_loc(self, loc_in_canvas):
bbox = self.legend.get_bbox_to_anchor()
# if bbox has zero width or height, the transformation is
# ill-defined. Fall back to the defaul bbox_to_anchor.
if bbox.width == 0 or bbox.height == 0:
self.legend.set_bbox_to_anchor(None)
bbox = self.legend.get_bbox_to_anchor()
_bbox_transform = BboxTransformFrom(bbox)
self.legend._loc = tuple(
_bbox_transform.transform_point(loc_in_canvas)
)
def _update_bbox_to_anchor(self, loc_in_canvas):
tr = self.legend.axes.transAxes
loc_in_bbox = tr.transform_point(loc_in_canvas)
self.legend.set_bbox_to_anchor(loc_in_bbox)
_legend_kw_doc = '''
loc : str or pair of floats, default: :rc:`legend.loc` ('best' for axes, \
'upper right' for figures)
The location of the legend.
The strings
``'upper left', 'upper right', 'lower left', 'lower right'``
place the legend at the corresponding corner of the axes/figure.
The strings
``'upper center', 'lower center', 'center left', 'center right'``
place the legend at the center of the corresponding edge of the
axes/figure.
The string ``'center'`` places the legend at the center of the axes/figure.
The string ``'best'`` places the legend at the location, among the nine
locations defined so far, with the minimum overlap with other drawn
artists. This option can be quite slow for plots with large amounts of
data; your plotting speed may benefit from providing a specific location.
The location can also be a 2-tuple giving the coordinates of the lower-left
corner of the legend in axes coordinates (in which case *bbox_to_anchor*
will be ignored).
For back-compatibility, ``'center right'`` (but no other location) can also
be spelled ``'right'``, and each "string" locations can also be given as a
numeric value:
=============== =============
Location String Location Code
=============== =============
'best' 0
'upper right' 1
'upper left' 2
'lower left' 3
'lower right' 4
'right' 5
'center left' 6
'center right' 7
'lower center' 8
'upper center' 9
'center' 10
=============== =============
bbox_to_anchor : `.BboxBase`, 2-tuple, or 4-tuple of floats
Box that is used to position the legend in conjunction with *loc*.
Defaults to `axes.bbox` (if called as a method to `.Axes.legend`) or
`figure.bbox` (if `.Figure.legend`). This argument allows arbitrary
placement of the legend.
Bbox coordinates are interpreted in the coordinate system given by
`bbox_transform`, with the default transform
Axes or Figure coordinates, depending on which ``legend`` is called.
If a 4-tuple or `.BboxBase` is given, then it specifies the bbox
``(x, y, width, height)`` that the legend is placed in.
To put the legend in the best location in the bottom right
quadrant of the axes (or figure)::
loc='best', bbox_to_anchor=(0.5, 0., 0.5, 0.5)
A 2-tuple ``(x, y)`` places the corner of the legend specified by *loc* at
x, y. For example, to put the legend's upper right-hand corner in the
center of the axes (or figure) the following keywords can be used::
loc='upper right', bbox_to_anchor=(0.5, 0.5)
ncol : integer
The number of columns that the legend has. Default is 1.
prop : None or :class:`matplotlib.font_manager.FontProperties` or dict
The font properties of the legend. If None (default), the current
:data:`matplotlib.rcParams` will be used.
fontsize : int or float or {'xx-small', 'x-small', 'small', 'medium', \
'large', 'x-large', 'xx-large'}
Controls the font size of the legend. If the value is numeric the
size will be the absolute font size in points. String values are
relative to the current default font size. This argument is only
used if `prop` is not specified.
numpoints : None or int
The number of marker points in the legend when creating a legend
entry for a `.Line2D` (line).
Default is ``None``, which will take the value from
:rc:`legend.numpoints`.
scatterpoints : None or int
The number of marker points in the legend when creating
a legend entry for a `.PathCollection` (scatter plot).
Default is ``None``, which will take the value from
:rc:`legend.scatterpoints`.
scatteryoffsets : iterable of floats
The vertical offset (relative to the font size) for the markers
created for a scatter plot legend entry. 0.0 is at the base the
legend text, and 1.0 is at the top. To draw all markers at the
same height, set to ``[0.5]``. Default is ``[0.375, 0.5, 0.3125]``.
markerscale : None or int or float
The relative size of legend markers compared with the originally
drawn ones.
Default is ``None``, which will take the value from
:rc:`legend.markerscale`.
markerfirst : bool
If *True*, legend marker is placed to the left of the legend label.
If *False*, legend marker is placed to the right of the legend
label.
Default is *True*.
frameon : None or bool
Control whether the legend should be drawn on a patch
(frame).
Default is ``None``, which will take the value from
:rc:`legend.frameon`.
fancybox : None or bool
Control whether round edges should be enabled around the
:class:`~matplotlib.patches.FancyBboxPatch` which makes up the
legend's background.
Default is ``None``, which will take the value from
:rc:`legend.fancybox`.
shadow : None or bool
Control whether to draw a shadow behind the legend.
Default is ``None``, which will take the value from
:rc:`legend.shadow`.
framealpha : None or float
Control the alpha transparency of the legend's background.
Default is ``None``, which will take the value from
:rc:`legend.framealpha`. If shadow is activated and
*framealpha* is ``None``, the default value is ignored.
facecolor : None or "inherit" or a color spec
Control the legend's background color.
Default is ``None``, which will take the value from
:rc:`legend.facecolor`. If ``"inherit"``, it will take
:rc:`axes.facecolor`.
edgecolor : None or "inherit" or a color spec
Control the legend's background patch edge color.
Default is ``None``, which will take the value from
:rc:`legend.edgecolor` If ``"inherit"``, it will take
:rc:`axes.edgecolor`.
mode : {"expand", None}
If `mode` is set to ``"expand"`` the legend will be horizontally
expanded to fill the axes area (or `bbox_to_anchor` if defines
the legend's size).
bbox_transform : None or :class:`matplotlib.transforms.Transform`
The transform for the bounding box (`bbox_to_anchor`). For a value
of ``None`` (default) the Axes'
:data:`~matplotlib.axes.Axes.transAxes` transform will be used.
title : str or None
The legend's title. Default is no title (``None``).
title_fontsize: str or None
The fontsize of the legend's title. Default is the default fontsize.
borderpad : float or None
The fractional whitespace inside the legend border.
Measured in font-size units.
Default is ``None``, which will take the value from
:rc:`legend.borderpad`.
labelspacing : float or None
The vertical space between the legend entries.
Measured in font-size units.
Default is ``None``, which will take the value from
:rc:`legend.labelspacing`.
handlelength : float or None
The length of the legend handles.
Measured in font-size units.
Default is ``None``, which will take the value from
:rc:`legend.handlelength`.
handletextpad : float or None
The pad between the legend handle and text.
Measured in font-size units.
Default is ``None``, which will take the value from
:rc:`legend.handletextpad`.
borderaxespad : float or None
The pad between the axes and legend border.
Measured in font-size units.
Default is ``None``, which will take the value from
:rc:`legend.borderaxespad`.
columnspacing : float or None
The spacing between columns.
Measured in font-size units.
Default is ``None``, which will take the value from
:rc:`legend.columnspacing`.
handler_map : dict or None
The custom dictionary mapping instances or types to a legend
handler. This `handler_map` updates the default handler map
found at :func:`matplotlib.legend.Legend.get_legend_handler_map`.
'''
docstring.interpd.update(_legend_kw_doc=_legend_kw_doc)
class Legend(Artist):
"""
Place a legend on the axes at location loc.
"""
codes = {'best': 0, # only implemented for axes legends
'upper right': 1,
'upper left': 2,
'lower left': 3,
'lower right': 4,
'right': 5,
'center left': 6,
'center right': 7,
'lower center': 8,
'upper center': 9,
'center': 10,
}
zorder = 5
def __str__(self):
return "Legend"
@docstring.dedent_interpd
def __init__(self, parent, handles, labels,
loc=None,
numpoints=None, # the number of points in the legend line
markerscale=None, # the relative size of legend markers
# vs. original
markerfirst=True, # controls ordering (left-to-right) of
# legend marker and label
scatterpoints=None, # number of scatter points
scatteryoffsets=None,
prop=None, # properties for the legend texts
fontsize=None, # keyword to set font size directly
# spacing & pad defined as a fraction of the font-size
borderpad=None, # the whitespace inside the legend border
labelspacing=None, # the vertical space between the legend
# entries
handlelength=None, # the length of the legend handles
handleheight=None, # the height of the legend handles
handletextpad=None, # the pad between the legend handle
# and text
borderaxespad=None, # the pad between the axes and legend
# border
columnspacing=None, # spacing between columns
ncol=1, # number of columns
mode=None, # mode for horizontal distribution of columns.
# None, "expand"
fancybox=None, # True use a fancy box, false use a rounded
# box, none use rc
shadow=None,
title=None, # set a title for the legend
title_fontsize=None, # set to ax.fontsize if None
framealpha=None, # set frame alpha
edgecolor=None, # frame patch edgecolor
facecolor=None, # frame patch facecolor
bbox_to_anchor=None, # bbox that the legend will be anchored.
bbox_transform=None, # transform for the bbox
frameon=None, # draw frame
handler_map=None,
):
"""
Parameters
----------
parent : `~matplotlib.axes.Axes` or `.Figure`
The artist that contains the legend.
handles : sequence of `.Artist`
A list of Artists (lines, patches) to be added to the legend.
labels : sequence of strings
A list of labels to show next to the artists. The length of handles
and labels should be the same. If they are not, they are truncated
to the smaller of both lengths.
Other Parameters
----------------
%(_legend_kw_doc)s
Notes
-----
Users can specify any arbitrary location for the legend using the
*bbox_to_anchor* keyword argument. bbox_to_anchor can be an instance
of BboxBase(or its derivatives) or a tuple of 2 or 4 floats.
See :meth:`set_bbox_to_anchor` for more detail.
The legend location can be specified by setting *loc* with a tuple of
2 floats, which is interpreted as the lower-left corner of the legend
in the normalized axes coordinate.
"""
# local import only to avoid circularity
from matplotlib.axes import Axes
from matplotlib.figure import Figure
Artist.__init__(self)
if prop is None:
if fontsize is not None:
self.prop = FontProperties(size=fontsize)
else:
self.prop = FontProperties(size=rcParams["legend.fontsize"])
elif isinstance(prop, dict):
self.prop = FontProperties(**prop)
if "size" not in prop:
self.prop.set_size(rcParams["legend.fontsize"])
else:
self.prop = prop
self._fontsize = self.prop.get_size_in_points()
self.texts = []
self.legendHandles = []
self._legend_title_box = None
#: A dictionary with the extra handler mappings for this Legend
#: instance.
self._custom_handler_map = handler_map
locals_view = locals()
for name in ["numpoints", "markerscale", "shadow", "columnspacing",
"scatterpoints", "handleheight", 'borderpad',
'labelspacing', 'handlelength', 'handletextpad',
'borderaxespad']:
if locals_view[name] is None:
value = rcParams["legend." + name]
else:
value = locals_view[name]
setattr(self, name, value)
del locals_view
# trim handles and labels if illegal label...
_lab, _hand = [], []
for label, handle in zip(labels, handles):
if isinstance(label, str) and label.startswith('_'):
cbook._warn_external('The handle {!r} has a label of {!r} '
'which cannot be automatically added to'
' the legend.'.format(handle, label))
else:
_lab.append(label)
_hand.append(handle)
labels, handles = _lab, _hand
handles = list(handles)
if len(handles) < 2:
ncol = 1
self._ncol = ncol
if self.numpoints <= 0:
raise ValueError("numpoints must be > 0; it was %d" % numpoints)
# introduce y-offset for handles of the scatter plot
if scatteryoffsets is None:
self._scatteryoffsets = np.array([3. / 8., 4. / 8., 2.5 / 8.])
else:
self._scatteryoffsets = np.asarray(scatteryoffsets)
reps = self.scatterpoints // len(self._scatteryoffsets) + 1
self._scatteryoffsets = np.tile(self._scatteryoffsets,
reps)[:self.scatterpoints]
# _legend_box is an OffsetBox instance that contains all
# legend items and will be initialized from _init_legend_box()
# method.
self._legend_box = None
if isinstance(parent, Axes):
self.isaxes = True
self.axes = parent
self.set_figure(parent.figure)
elif isinstance(parent, Figure):
self.isaxes = False
self.set_figure(parent)
else:
raise TypeError("Legend needs either Axes or Figure as parent")
self.parent = parent
self._loc_used_default = loc is None
if loc is None:
loc = rcParams["legend.loc"]
if not self.isaxes and loc in [0, 'best']:
loc = 'upper right'
if isinstance(loc, str):
if loc not in self.codes:
if self.isaxes:
cbook.warn_deprecated(
"3.1", message="Unrecognized location {!r}. Falling "
"back on 'best'; valid locations are\n\t{}\n"
"This will raise an exception %(removal)s."
.format(loc, '\n\t'.join(self.codes)))
loc = 0
else:
cbook.warn_deprecated(
"3.1", message="Unrecognized location {!r}. Falling "
"back on 'upper right'; valid locations are\n\t{}\n'"
"This will raise an exception %(removal)s."
.format(loc, '\n\t'.join(self.codes)))
loc = 1
else:
loc = self.codes[loc]
if not self.isaxes and loc == 0:
cbook.warn_deprecated(
"3.1", message="Automatic legend placement (loc='best') not "
"implemented for figure legend. Falling back on 'upper "
"right'. This will raise an exception %(removal)s.")
loc = 1
self._mode = mode
self.set_bbox_to_anchor(bbox_to_anchor, bbox_transform)
# We use FancyBboxPatch to draw a legend frame. The location
# and size of the box will be updated during the drawing time.
if facecolor is None:
facecolor = rcParams["legend.facecolor"]
if facecolor == 'inherit':
facecolor = rcParams["axes.facecolor"]
if edgecolor is None:
edgecolor = rcParams["legend.edgecolor"]
if edgecolor == 'inherit':
edgecolor = rcParams["axes.edgecolor"]
self.legendPatch = FancyBboxPatch(
xy=(0.0, 0.0), width=1., height=1.,
facecolor=facecolor,
edgecolor=edgecolor,
mutation_scale=self._fontsize,
snap=True
)
# The width and height of the legendPatch will be set (in the
# draw()) to the length that includes the padding. Thus we set
# pad=0 here.
if fancybox is None:
fancybox = rcParams["legend.fancybox"]
if fancybox:
self.legendPatch.set_boxstyle("round", pad=0,
rounding_size=0.2)
else:
self.legendPatch.set_boxstyle("square", pad=0)
self._set_artist_props(self.legendPatch)
self._drawFrame = frameon
if frameon is None:
self._drawFrame = rcParams["legend.frameon"]
# init with null renderer
self._init_legend_box(handles, labels, markerfirst)
# If shadow is activated use framealpha if not
# explicitly passed. See Issue 8943
if framealpha is None:
if shadow:
self.get_frame().set_alpha(1)
else:
self.get_frame().set_alpha(rcParams["legend.framealpha"])
else:
self.get_frame().set_alpha(framealpha)
tmp = self._loc_used_default
self._set_loc(loc)
self._loc_used_default = tmp # ignore changes done by _set_loc
# figure out title fontsize:
if title_fontsize is None:
title_fontsize = rcParams['legend.title_fontsize']
tprop = FontProperties(size=title_fontsize)
self.set_title(title, prop=tprop)
self._draggable = None
def _set_artist_props(self, a):
"""
Set the boilerplate props for artists added to axes.
"""
a.set_figure(self.figure)
if self.isaxes:
# a.set_axes(self.axes)
a.axes = self.axes
a.set_transform(self.get_transform())
def _set_loc(self, loc):
# find_offset function will be provided to _legend_box and
# _legend_box will draw itself at the location of the return
# value of the find_offset.
self._loc_used_default = False
self._loc_real = loc
self.stale = True
self._legend_box.set_offset(self._findoffset)
def _get_loc(self):
return self._loc_real
_loc = property(_get_loc, _set_loc)
def _findoffset(self, width, height, xdescent, ydescent, renderer):
"Helper function to locate the legend."
if self._loc == 0: # "best".
x, y = self._find_best_position(width, height, renderer)
elif self._loc in Legend.codes.values(): # Fixed location.
bbox = Bbox.from_bounds(0, 0, width, height)
x, y = self._get_anchored_bbox(self._loc, bbox,
self.get_bbox_to_anchor(),
renderer)
else: # Axes or figure coordinates.
fx, fy = self._loc
bbox = self.get_bbox_to_anchor()
x, y = bbox.x0 + bbox.width * fx, bbox.y0 + bbox.height * fy
return x + xdescent, y + ydescent
@allow_rasterization
def draw(self, renderer):
"Draw everything that belongs to the legend."
if not self.get_visible():
return
renderer.open_group('legend')
fontsize = renderer.points_to_pixels(self._fontsize)
# if mode == fill, set the width of the legend_box to the
# width of the parent (minus pads)
if self._mode in ["expand"]:
pad = 2 * (self.borderaxespad + self.borderpad) * fontsize
self._legend_box.set_width(self.get_bbox_to_anchor().width - pad)
# update the location and size of the legend. This needs to
# be done in any case to clip the figure right.
bbox = self._legend_box.get_window_extent(renderer)
self.legendPatch.set_bounds(bbox.x0, bbox.y0,
bbox.width, bbox.height)
self.legendPatch.set_mutation_scale(fontsize)
if self._drawFrame:
if self.shadow:
shadow = Shadow(self.legendPatch, 2, -2)
shadow.draw(renderer)
self.legendPatch.draw(renderer)
self._legend_box.draw(renderer)
renderer.close_group('legend')
self.stale = False
def _approx_text_height(self, renderer=None):
"""
Return the approximate height of the text. This is used to place
the legend handle.
"""
if renderer is None:
return self._fontsize
else:
return renderer.points_to_pixels(self._fontsize)
# _default_handler_map defines the default mapping between plot
# elements and the legend handlers.
_default_handler_map = {
StemContainer: legend_handler.HandlerStem(),
ErrorbarContainer: legend_handler.HandlerErrorbar(),
Line2D: legend_handler.HandlerLine2D(),
Patch: legend_handler.HandlerPatch(),
LineCollection: legend_handler.HandlerLineCollection(),
RegularPolyCollection: legend_handler.HandlerRegularPolyCollection(),
CircleCollection: legend_handler.HandlerCircleCollection(),
BarContainer: legend_handler.HandlerPatch(
update_func=legend_handler.update_from_first_child),
tuple: legend_handler.HandlerTuple(),
PathCollection: legend_handler.HandlerPathCollection(),
PolyCollection: legend_handler.HandlerPolyCollection()
}
# (get|set|update)_default_handler_maps are public interfaces to
# modify the default handler map.
@classmethod
def get_default_handler_map(cls):
"""
A class method that returns the default handler map.
"""
return cls._default_handler_map
@classmethod
def set_default_handler_map(cls, handler_map):
"""
A class method to set the default handler map.
"""
cls._default_handler_map = handler_map
@classmethod
def update_default_handler_map(cls, handler_map):
"""
A class method to update the default handler map.
"""
cls._default_handler_map.update(handler_map)
def get_legend_handler_map(self):
"""
Return the handler map.
"""
default_handler_map = self.get_default_handler_map()
if self._custom_handler_map:
hm = default_handler_map.copy()
hm.update(self._custom_handler_map)
return hm
else:
return default_handler_map
@staticmethod
def get_legend_handler(legend_handler_map, orig_handle):
"""
Return a legend handler from *legend_handler_map* that
corresponds to *orig_handler*.
*legend_handler_map* should be a dictionary object (that is
returned by the get_legend_handler_map method).
It first checks if the *orig_handle* itself is a key in the
*legend_handler_map* and return the associated value.
Otherwise, it checks for each of the classes in its
method-resolution-order. If no matching key is found, it
returns ``None``.
"""
try:
return legend_handler_map[orig_handle]
except (TypeError, KeyError): # TypeError if unhashable.
pass
for handle_type in type(orig_handle).mro():
try:
return legend_handler_map[handle_type]
except KeyError:
pass
return None
def _init_legend_box(self, handles, labels, markerfirst=True):
"""
Initialize the legend_box. The legend_box is an instance of
the OffsetBox, which is packed with legend handles and
texts. Once packed, their location is calculated during the
drawing time.
"""
fontsize = self._fontsize
# legend_box is a HPacker, horizontally packed with
# columns. Each column is a VPacker, vertically packed with
# legend items. Each legend item is HPacker packed with
# legend handleBox and labelBox. handleBox is an instance of
# offsetbox.DrawingArea which contains legend handle. labelBox
# is an instance of offsetbox.TextArea which contains legend
# text.
text_list = [] # the list of text instances
handle_list = [] # the list of text instances
handles_and_labels = []
label_prop = dict(verticalalignment='baseline',
horizontalalignment='left',
fontproperties=self.prop,
)
# The approximate height and descent of text. These values are
# only used for plotting the legend handle.
descent = 0.35 * self._approx_text_height() * (self.handleheight - 0.7)
# 0.35 and 0.7 are just heuristic numbers and may need to be improved.
height = self._approx_text_height() * self.handleheight - descent
# each handle needs to be drawn inside a box of (x, y, w, h) =
# (0, -descent, width, height). And their coordinates should
# be given in the display coordinates.
# The transformation of each handle will be automatically set
# to self.get_transform(). If the artist does not use its
# default transform (e.g., Collections), you need to
# manually set their transform to the self.get_transform().
legend_handler_map = self.get_legend_handler_map()
for orig_handle, lab in zip(handles, labels):
handler = self.get_legend_handler(legend_handler_map, orig_handle)
if handler is None:
cbook._warn_external(
"Legend does not support {!r} instances.\nA proxy artist "
"may be used instead.\nSee: "
"http://matplotlib.org/users/legend_guide.html"
"#creating-artists-specifically-for-adding-to-the-legend-"
"aka-proxy-artists".format(orig_handle))
# We don't have a handle for this artist, so we just defer
# to None.
handle_list.append(None)
else:
textbox = TextArea(lab, textprops=label_prop,
multilinebaseline=True,
minimumdescent=True)
handlebox = DrawingArea(width=self.handlelength * fontsize,
height=height,
xdescent=0., ydescent=descent)
text_list.append(textbox._text)
# Create the artist for the legend which represents the
# original artist/handle.
handle_list.append(handler.legend_artist(self, orig_handle,
fontsize, handlebox))
handles_and_labels.append((handlebox, textbox))
if handles_and_labels:
# We calculate number of rows in each column. The first
# (num_largecol) columns will have (nrows+1) rows, and remaining
# (num_smallcol) columns will have (nrows) rows.
ncol = min(self._ncol, len(handles_and_labels))
nrows, num_largecol = divmod(len(handles_and_labels), ncol)
num_smallcol = ncol - num_largecol
# starting index of each column and number of rows in it.
rows_per_col = [nrows + 1] * num_largecol + [nrows] * num_smallcol
start_idxs = np.concatenate([[0], np.cumsum(rows_per_col)[:-1]])
cols = zip(start_idxs, rows_per_col)
else:
cols = []
columnbox = []
for i0, di in cols:
# pack handleBox and labelBox into itemBox
itemBoxes = [HPacker(pad=0,
sep=self.handletextpad * fontsize,
children=[h, t] if markerfirst else [t, h],
align="baseline")
for h, t in handles_and_labels[i0:i0 + di]]
# minimumdescent=False for the text of the last row of the column
if markerfirst:
itemBoxes[-1].get_children()[1].set_minimumdescent(False)
else:
itemBoxes[-1].get_children()[0].set_minimumdescent(False)
# pack columnBox
alignment = "baseline" if markerfirst else "right"
columnbox.append(VPacker(pad=0,
sep=self.labelspacing * fontsize,
align=alignment,
children=itemBoxes))
mode = "expand" if self._mode == "expand" else "fixed"
sep = self.columnspacing * fontsize
self._legend_handle_box = HPacker(pad=0,
sep=sep, align="baseline",
mode=mode,
children=columnbox)
self._legend_title_box = TextArea("")
self._legend_box = VPacker(pad=self.borderpad * fontsize,
sep=self.labelspacing * fontsize,
align="center",
children=[self._legend_title_box,
self._legend_handle_box])
self._legend_box.set_figure(self.figure)
self.texts = text_list
self.legendHandles = handle_list
def _auto_legend_data(self):
"""
Returns list of vertices and extents covered by the plot.
Returns a two long list.
First element is a list of (x, y) vertices (in
display-coordinates) covered by all the lines and line
collections, in the legend's handles.
Second element is a list of bounding boxes for all the patches in
the legend's handles.
"""
# should always hold because function is only called internally
assert self.isaxes
ax = self.parent
bboxes = []
lines = []
offsets = []
for handle in ax.lines:
assert isinstance(handle, Line2D)
path = handle.get_path()
trans = handle.get_transform()
tpath = trans.transform_path(path)
lines.append(tpath)
for handle in ax.patches:
assert isinstance(handle, Patch)
if isinstance(handle, Rectangle):
transform = handle.get_data_transform()
bboxes.append(handle.get_bbox().transformed(transform))
else:
transform = handle.get_transform()
bboxes.append(handle.get_path().get_extents(transform))
for handle in ax.collections:
transform, transOffset, hoffsets, paths = handle._prepare_points()
if len(hoffsets):
for offset in transOffset.transform(hoffsets):
offsets.append(offset)
try:
vertices = np.concatenate([l.vertices for l in lines])
except ValueError:
vertices = np.array([])
return [vertices, bboxes, lines, offsets]
def draw_frame(self, b):
'''
Set draw frame to b.
Parameters
----------
b : bool
'''
self.set_frame_on(b)
def get_children(self):
'Return a list of child artists.'
children = []
if self._legend_box:
children.append(self._legend_box)
children.append(self.get_frame())
return children
def get_frame(self):
'''
Return the `~.patches.Rectangle` instances used to frame the legend.
'''
return self.legendPatch
def get_lines(self):
'Return a list of `~.lines.Line2D` instances in the legend.'
return [h for h in self.legendHandles if isinstance(h, Line2D)]
def get_patches(self):
'Return a list of `~.patches.Patch` instances in the legend.'
return silent_list('Patch',
[h for h in self.legendHandles
if isinstance(h, Patch)])
def get_texts(self):
'Return a list of `~.text.Text` instances in the legend.'
return silent_list('Text', self.texts)
def set_title(self, title, prop=None):
"""
Set the legend title. Fontproperties can be optionally set
with *prop* parameter.
"""
self._legend_title_box._text.set_text(title)
if title:
self._legend_title_box._text.set_visible(True)
self._legend_title_box.set_visible(True)
else:
self._legend_title_box._text.set_visible(False)
self._legend_title_box.set_visible(False)
if prop is not None:
if isinstance(prop, dict):
prop = FontProperties(**prop)
self._legend_title_box._text.set_fontproperties(prop)
self.stale = True
def get_title(self):
'Return the `.Text` instance for the legend title.'
return self._legend_title_box._text
def get_window_extent(self, renderer=None):
'Return extent of the legend.'
if renderer is None:
renderer = self.figure._cachedRenderer
return self._legend_box.get_window_extent(renderer=renderer)
def get_tightbbox(self, renderer):
"""
Like `.Legend.get_window_extent`, but uses the box for the legend.
Parameters
----------
renderer : `.RendererBase` instance
renderer that will be used to draw the figures (i.e.
``fig.canvas.get_renderer()``)
Returns
-------
`.BboxBase` : containing the bounding box in figure pixel co-ordinates.
"""
return self._legend_box.get_window_extent(renderer)
def get_frame_on(self):
"""Get whether the legend box patch is drawn."""
return self._drawFrame
def set_frame_on(self, b):
"""
Set whether the legend box patch is drawn.
Parameters
----------
b : bool
"""
self._drawFrame = b
self.stale = True
def get_bbox_to_anchor(self):
"""Return the bbox that the legend will be anchored to."""
if self._bbox_to_anchor is None:
return self.parent.bbox
else:
return self._bbox_to_anchor
def set_bbox_to_anchor(self, bbox, transform=None):
"""
Set the bbox that the legend will be anchored to.
*bbox* can be
- A `.BboxBase` instance
- A tuple of ``(left, bottom, width, height)`` in the given transform
(normalized axes coordinate if None)
- A tuple of ``(left, bottom)`` where the width and height will be
assumed to be zero.
"""
if bbox is None:
self._bbox_to_anchor = None
return
elif isinstance(bbox, BboxBase):
self._bbox_to_anchor = bbox
else:
try:
l = len(bbox)
except TypeError:
raise ValueError("Invalid argument for bbox : %s" % str(bbox))
if l == 2:
bbox = [bbox[0], bbox[1], 0, 0]
self._bbox_to_anchor = Bbox.from_bounds(*bbox)
if transform is None:
transform = BboxTransformTo(self.parent.bbox)
self._bbox_to_anchor = TransformedBbox(self._bbox_to_anchor,
transform)
self.stale = True
def _get_anchored_bbox(self, loc, bbox, parentbbox, renderer):
"""
Place the *bbox* inside the *parentbbox* according to a given
location code. Return the (x,y) coordinate of the bbox.
- loc: a location code in range(1, 11).
This corresponds to the possible values for self._loc, excluding
"best".
- bbox: bbox to be placed, display coordinate units.
- parentbbox: a parent box which will contain the bbox. In
display coordinates.
"""
assert loc in range(1, 11) # called only internally
BEST, UR, UL, LL, LR, R, CL, CR, LC, UC, C = range(11)
anchor_coefs = {UR: "NE",
UL: "NW",
LL: "SW",
LR: "SE",
R: "E",
CL: "W",
CR: "E",
LC: "S",
UC: "N",
C: "C"}
c = anchor_coefs[loc]
fontsize = renderer.points_to_pixels(self._fontsize)
container = parentbbox.padded(-(self.borderaxespad) * fontsize)
anchored_box = bbox.anchored(c, container=container)
return anchored_box.x0, anchored_box.y0
def _find_best_position(self, width, height, renderer, consider=None):
"""
Determine the best location to place the legend.
*consider* is a list of ``(x, y)`` pairs to consider as a potential
lower-left corner of the legend. All are display coords.
"""
# should always hold because function is only called internally
assert self.isaxes
verts, bboxes, lines, offsets = self._auto_legend_data()
if self._loc_used_default and verts.shape[0] > 200000:
# this size results in a 3+ second render time on a good machine
cbook._warn_external(
'Creating legend with loc="best" can be slow with large '
'amounts of data.'
)
bbox = Bbox.from_bounds(0, 0, width, height)
if consider is None:
consider = [self._get_anchored_bbox(x, bbox,
self.get_bbox_to_anchor(),
renderer)
for x in range(1, len(self.codes))]
candidates = []
for idx, (l, b) in enumerate(consider):
legendBox = Bbox.from_bounds(l, b, width, height)
badness = 0
# XXX TODO: If markers are present, it would be good to
# take them into account when checking vertex overlaps in
# the next line.
badness = (legendBox.count_contains(verts)
+ legendBox.count_contains(offsets)
+ legendBox.count_overlaps(bboxes)
+ sum(line.intersects_bbox(legendBox, filled=False)
for line in lines))
if badness == 0:
return l, b
# Include the index to favor lower codes in case of a tie.
candidates.append((badness, idx, (l, b)))
_, _, (l, b) = min(candidates)
return l, b
def contains(self, event):
return self.legendPatch.contains(event)
def set_draggable(self, state, use_blit=False, update='loc'):
"""
Enable or disable mouse dragging support of the legend.
Parameters
----------
state : bool
Whether mouse dragging is enabled.
use_blit : bool, optional
Use blitting for faster image composition. For details see
:ref:`func-animation`.
update : {'loc', 'bbox'}, optional
The legend parameter to be changed when dragged:
- 'loc': update the *loc* parameter of the legend
- 'bbox': update the *bbox_to_anchor* parameter of the legend
Returns
-------
If *state* is ``True`` this returns the `~.DraggableLegend` helper
instance. Otherwise this returns ``None``.
"""
if state:
if self._draggable is None:
self._draggable = DraggableLegend(self,
use_blit,
update=update)
else:
if self._draggable is not None:
self._draggable.disconnect()
self._draggable = None
return self._draggable
def get_draggable(self):
"""Return ``True`` if the legend is draggable, ``False`` otherwise."""
return self._draggable is not None
# Helper functions to parse legend arguments for both `figure.legend` and
# `axes.legend`:
def _get_legend_handles(axs, legend_handler_map=None):
"""
Return a generator of artists that can be used as handles in
a legend.
"""
handles_original = []
for ax in axs:
handles_original += (ax.lines + ax.patches +
ax.collections + ax.containers)
# support parasite axes:
if hasattr(ax, 'parasites'):
for axx in ax.parasites:
handles_original += (axx.lines + axx.patches +
axx.collections + axx.containers)
handler_map = Legend.get_default_handler_map()
if legend_handler_map is not None:
handler_map = handler_map.copy()
handler_map.update(legend_handler_map)
has_handler = Legend.get_legend_handler
for handle in handles_original:
label = handle.get_label()
if label != '_nolegend_' and has_handler(handler_map, handle):
yield handle
def _get_legend_handles_labels(axs, legend_handler_map=None):
"""
Return handles and labels for legend, internal method.
"""
handles = []
labels = []
for handle in _get_legend_handles(axs, legend_handler_map):
label = handle.get_label()
if label and not label.startswith('_'):
handles.append(handle)
labels.append(label)
return handles, labels
def _parse_legend_args(axs, *args, handles=None, labels=None, **kwargs):
"""
Get the handles and labels from the calls to either ``figure.legend``
or ``axes.legend``.
``axs`` is a list of axes (to get legend artists from)
"""
log = logging.getLogger(__name__)
handlers = kwargs.get('handler_map', {}) or {}
extra_args = ()
if (handles is not None or labels is not None) and args:
cbook._warn_external("You have mixed positional and keyword "
"arguments, some input may be discarded.")
# if got both handles and labels as kwargs, make same length
if handles and labels:
handles, labels = zip(*zip(handles, labels))
elif handles is not None and labels is None:
labels = [handle.get_label() for handle in handles]
elif labels is not None and handles is None:
# Get as many handles as there are labels.
handles = [handle for handle, label
in zip(_get_legend_handles(axs, handlers), labels)]
# No arguments - automatically detect labels and handles.
elif len(args) == 0:
handles, labels = _get_legend_handles_labels(axs, handlers)
if not handles:
log.warning('No handles with labels found to put in legend.')
# One argument. User defined labels - automatic handle detection.
elif len(args) == 1:
labels, = args
# Get as many handles as there are labels.
handles = [handle for handle, label
in zip(_get_legend_handles(axs, handlers), labels)]
# Two arguments:
# * user defined handles and labels
elif len(args) >= 2:
handles, labels = args[:2]
extra_args = args[2:]
else:
raise TypeError('Invalid arguments to legend.')
return handles, labels, extra_args, kwargs
|
59218c80b489015704e8fe60b99490ad75b46f4a85c7a6c869ae80950d519b56
|
r"""
:mod:`~matplotlib.mathtext` is a module for parsing a subset of the
TeX math syntax and drawing them to a matplotlib backend.
For a tutorial of its usage see :doc:`/tutorials/text/mathtext`. This
document is primarily concerned with implementation details.
The module uses pyparsing_ to parse the TeX expression.
.. _pyparsing: http://pyparsing.wikispaces.com/
The Bakoma distribution of the TeX Computer Modern fonts, and STIX
fonts are supported. There is experimental support for using
arbitrary fonts, but results may vary without proper tweaking and
metrics for those fonts.
"""
from collections import namedtuple
import functools
from io import StringIO
import logging
import os
import types
import unicodedata
import numpy as np
from pyparsing import (
Combine, Empty, FollowedBy, Forward, Group, Literal, oneOf, OneOrMore,
Optional, ParseBaseException, ParseFatalException, ParserElement,
QuotedString, Regex, StringEnd, Suppress, ZeroOrMore)
ParserElement.enablePackrat()
from matplotlib import cbook, colors as mcolors, get_data_path, rcParams
from matplotlib.afm import AFM
from matplotlib.cbook import get_realpath_and_stat
from matplotlib.ft2font import FT2Image, KERNING_DEFAULT, LOAD_NO_HINTING
from matplotlib.font_manager import findfont, FontProperties, get_font
from matplotlib._mathtext_data import (latex_to_bakoma, latex_to_standard,
tex2uni, latex_to_cmex,
stix_virtual_fonts)
_log = logging.getLogger(__name__)
##############################################################################
# FONTS
def get_unicode_index(symbol, math=True):
r"""
Return the integer index (from the Unicode table) of *symbol*.
Parameters
----------
symbol : str
A single unicode character, a TeX command (e.g. r'\pi') or a Type1
symbol name (e.g. 'phi').
math : bool, default is True
If False, always treat as a single unicode character.
"""
# for a non-math symbol, simply return its unicode index
if not math:
return ord(symbol)
# From UTF #25: U+2212 minus sign is the preferred
# representation of the unary and binary minus sign rather than
# the ASCII-derived U+002D hyphen-minus, because minus sign is
# unambiguous and because it is rendered with a more desirable
# length, usually longer than a hyphen.
if symbol == '-':
return 0x2212
try: # This will succeed if symbol is a single unicode char
return ord(symbol)
except TypeError:
pass
try: # Is symbol a TeX symbol (i.e. \alpha)
return tex2uni[symbol.strip("\\")]
except KeyError:
raise ValueError(
"'{}' is not a valid Unicode character or TeX/Type1 symbol"
.format(symbol))
unichr_safe = cbook.deprecated("3.0")(chr)
class MathtextBackend(object):
"""
The base class for the mathtext backend-specific code. The
purpose of :class:`MathtextBackend` subclasses is to interface
between mathtext and a specific matplotlib graphics backend.
Subclasses need to override the following:
- :meth:`render_glyph`
- :meth:`render_rect_filled`
- :meth:`get_results`
And optionally, if you need to use a FreeType hinting style:
- :meth:`get_hinting_type`
"""
def __init__(self):
self.width = 0
self.height = 0
self.depth = 0
def set_canvas_size(self, w, h, d):
'Dimension the drawing canvas'
self.width = w
self.height = h
self.depth = d
def render_glyph(self, ox, oy, info):
"""
Draw a glyph described by *info* to the reference point (*ox*,
*oy*).
"""
raise NotImplementedError()
def render_rect_filled(self, x1, y1, x2, y2):
"""
Draw a filled black rectangle from (*x1*, *y1*) to (*x2*, *y2*).
"""
raise NotImplementedError()
def get_results(self, box):
"""
Return a backend-specific tuple to return to the backend after
all processing is done.
"""
raise NotImplementedError()
def get_hinting_type(self):
"""
Get the FreeType hinting type to use with this particular
backend.
"""
return LOAD_NO_HINTING
class MathtextBackendAgg(MathtextBackend):
"""
Render glyphs and rectangles to an FTImage buffer, which is later
transferred to the Agg image by the Agg backend.
"""
def __init__(self):
self.ox = 0
self.oy = 0
self.image = None
self.mode = 'bbox'
self.bbox = [0, 0, 0, 0]
MathtextBackend.__init__(self)
def _update_bbox(self, x1, y1, x2, y2):
self.bbox = [min(self.bbox[0], x1),
min(self.bbox[1], y1),
max(self.bbox[2], x2),
max(self.bbox[3], y2)]
def set_canvas_size(self, w, h, d):
MathtextBackend.set_canvas_size(self, w, h, d)
if self.mode != 'bbox':
self.image = FT2Image(np.ceil(w), np.ceil(h + max(d, 0)))
def render_glyph(self, ox, oy, info):
if self.mode == 'bbox':
self._update_bbox(ox + info.metrics.xmin,
oy - info.metrics.ymax,
ox + info.metrics.xmax,
oy - info.metrics.ymin)
else:
info.font.draw_glyph_to_bitmap(
self.image, ox, oy - info.metrics.iceberg, info.glyph,
antialiased=rcParams['text.antialiased'])
def render_rect_filled(self, x1, y1, x2, y2):
if self.mode == 'bbox':
self._update_bbox(x1, y1, x2, y2)
else:
height = max(int(y2 - y1) - 1, 0)
if height == 0:
center = (y2 + y1) / 2.0
y = int(center - (height + 1) / 2.0)
else:
y = int(y1)
self.image.draw_rect_filled(int(x1), y, np.ceil(x2), y + height)
def get_results(self, box, used_characters):
self.mode = 'bbox'
orig_height = box.height
orig_depth = box.depth
ship(0, 0, box)
bbox = self.bbox
bbox = [bbox[0] - 1, bbox[1] - 1, bbox[2] + 1, bbox[3] + 1]
self.mode = 'render'
self.set_canvas_size(
bbox[2] - bbox[0],
(bbox[3] - bbox[1]) - orig_depth,
(bbox[3] - bbox[1]) - orig_height)
ship(-bbox[0], -bbox[1], box)
result = (self.ox,
self.oy,
self.width,
self.height + self.depth,
self.depth,
self.image,
used_characters)
self.image = None
return result
def get_hinting_type(self):
from matplotlib.backends import backend_agg
return backend_agg.get_hinting_flag()
class MathtextBackendBitmap(MathtextBackendAgg):
def get_results(self, box, used_characters):
ox, oy, width, height, depth, image, characters = \
MathtextBackendAgg.get_results(self, box, used_characters)
return image, depth
class MathtextBackendPs(MathtextBackend):
"""
Store information to write a mathtext rendering to the PostScript backend.
"""
_PSResult = namedtuple(
"_PSResult", "width height depth pswriter used_characters")
def __init__(self):
self.pswriter = StringIO()
self.lastfont = None
def render_glyph(self, ox, oy, info):
oy = self.height - oy + info.offset
postscript_name = info.postscript_name
fontsize = info.fontsize
symbol_name = info.symbol_name
if (postscript_name, fontsize) != self.lastfont:
ps = """/%(postscript_name)s findfont
%(fontsize)s scalefont
setfont
""" % locals()
self.lastfont = postscript_name, fontsize
self.pswriter.write(ps)
ps = """%(ox)f %(oy)f moveto
/%(symbol_name)s glyphshow\n
""" % locals()
self.pswriter.write(ps)
def render_rect_filled(self, x1, y1, x2, y2):
ps = "%f %f %f %f rectfill\n" % (
x1, self.height - y2, x2 - x1, y2 - y1)
self.pswriter.write(ps)
def get_results(self, box, used_characters):
ship(0, 0, box)
return self._PSResult(self.width,
self.height + self.depth,
self.depth,
self.pswriter,
used_characters)
class MathtextBackendPdf(MathtextBackend):
"""Store information to write a mathtext rendering to the PDF backend."""
_PDFResult = namedtuple(
"_PDFResult", "width height depth glyphs rects used_characters")
def __init__(self):
self.glyphs = []
self.rects = []
def render_glyph(self, ox, oy, info):
filename = info.font.fname
oy = self.height - oy + info.offset
self.glyphs.append(
(ox, oy, filename, info.fontsize,
info.num, info.symbol_name))
def render_rect_filled(self, x1, y1, x2, y2):
self.rects.append((x1, self.height - y2, x2 - x1, y2 - y1))
def get_results(self, box, used_characters):
ship(0, 0, box)
return self._PDFResult(self.width,
self.height + self.depth,
self.depth,
self.glyphs,
self.rects,
used_characters)
class MathtextBackendSvg(MathtextBackend):
"""
Store information to write a mathtext rendering to the SVG
backend.
"""
def __init__(self):
self.svg_glyphs = []
self.svg_rects = []
def render_glyph(self, ox, oy, info):
oy = self.height - oy + info.offset
self.svg_glyphs.append(
(info.font, info.fontsize, info.num, ox, oy, info.metrics))
def render_rect_filled(self, x1, y1, x2, y2):
self.svg_rects.append(
(x1, self.height - y1 + 1, x2 - x1, y2 - y1))
def get_results(self, box, used_characters):
ship(0, 0, box)
svg_elements = types.SimpleNamespace(svg_glyphs=self.svg_glyphs,
svg_rects=self.svg_rects)
return (self.width,
self.height + self.depth,
self.depth,
svg_elements,
used_characters)
class MathtextBackendPath(MathtextBackend):
"""
Store information to write a mathtext rendering to the text path
machinery.
"""
def __init__(self):
self.glyphs = []
self.rects = []
def render_glyph(self, ox, oy, info):
oy = self.height - oy + info.offset
thetext = info.num
self.glyphs.append(
(info.font, info.fontsize, thetext, ox, oy))
def render_rect_filled(self, x1, y1, x2, y2):
self.rects.append((x1, self.height - y2, x2 - x1, y2 - y1))
def get_results(self, box, used_characters):
ship(0, 0, box)
return (self.width,
self.height + self.depth,
self.depth,
self.glyphs,
self.rects)
class MathtextBackendCairo(MathtextBackend):
"""
Store information to write a mathtext rendering to the Cairo
backend.
"""
def __init__(self):
self.glyphs = []
self.rects = []
def render_glyph(self, ox, oy, info):
oy = oy - info.offset - self.height
thetext = chr(info.num)
self.glyphs.append(
(info.font, info.fontsize, thetext, ox, oy))
def render_rect_filled(self, x1, y1, x2, y2):
self.rects.append(
(x1, y1 - self.height, x2 - x1, y2 - y1))
def get_results(self, box, used_characters):
ship(0, 0, box)
return (self.width,
self.height + self.depth,
self.depth,
self.glyphs,
self.rects)
class Fonts(object):
"""
An abstract base class for a system of fonts to use for mathtext.
The class must be able to take symbol keys and font file names and
return the character metrics. It also delegates to a backend class
to do the actual drawing.
"""
def __init__(self, default_font_prop, mathtext_backend):
"""
*default_font_prop*: A
:class:`~matplotlib.font_manager.FontProperties` object to use
for the default non-math font, or the base font for Unicode
(generic) font rendering.
*mathtext_backend*: A subclass of :class:`MathTextBackend`
used to delegate the actual rendering.
"""
self.default_font_prop = default_font_prop
self.mathtext_backend = mathtext_backend
self.used_characters = {}
def destroy(self):
"""
Fix any cyclical references before the object is about
to be destroyed.
"""
self.used_characters = None
def get_kern(self, font1, fontclass1, sym1, fontsize1,
font2, fontclass2, sym2, fontsize2, dpi):
"""
Get the kerning distance for font between *sym1* and *sym2*.
*fontX*: one of the TeX font names::
tt, it, rm, cal, sf, bf or default/regular (non-math)
*fontclassX*: TODO
*symX*: a symbol in raw TeX form. e.g., '1', 'x' or '\\sigma'
*fontsizeX*: the fontsize in points
*dpi*: the current dots-per-inch
"""
return 0.
def get_metrics(self, font, font_class, sym, fontsize, dpi, math=True):
"""
*font*: one of the TeX font names::
tt, it, rm, cal, sf, bf or default/regular (non-math)
*font_class*: TODO
*sym*: a symbol in raw TeX form. e.g., '1', 'x' or '\\sigma'
*fontsize*: font size in points
*dpi*: current dots-per-inch
*math*: whether sym is a math character
Returns an object with the following attributes:
- *advance*: The advance distance (in points) of the glyph.
- *height*: The height of the glyph in points.
- *width*: The width of the glyph in points.
- *xmin*, *xmax*, *ymin*, *ymax* - the ink rectangle of the glyph
- *iceberg* - the distance from the baseline to the top of
the glyph. This corresponds to TeX's definition of
"height".
"""
info = self._get_info(font, font_class, sym, fontsize, dpi, math)
return info.metrics
def set_canvas_size(self, w, h, d):
"""
Set the size of the buffer used to render the math expression.
Only really necessary for the bitmap backends.
"""
self.width, self.height, self.depth = np.ceil([w, h, d])
self.mathtext_backend.set_canvas_size(
self.width, self.height, self.depth)
def render_glyph(self, ox, oy, facename, font_class, sym, fontsize, dpi):
"""
Draw a glyph at
- *ox*, *oy*: position
- *facename*: One of the TeX face names
- *font_class*:
- *sym*: TeX symbol name or single character
- *fontsize*: fontsize in points
- *dpi*: The dpi to draw at.
"""
info = self._get_info(facename, font_class, sym, fontsize, dpi)
realpath, stat_key = get_realpath_and_stat(info.font.fname)
used_characters = self.used_characters.setdefault(
stat_key, (realpath, set()))
used_characters[1].add(info.num)
self.mathtext_backend.render_glyph(ox, oy, info)
def render_rect_filled(self, x1, y1, x2, y2):
"""
Draw a filled rectangle from (*x1*, *y1*) to (*x2*, *y2*).
"""
self.mathtext_backend.render_rect_filled(x1, y1, x2, y2)
def get_xheight(self, font, fontsize, dpi):
"""
Get the xheight for the given *font* and *fontsize*.
"""
raise NotImplementedError()
def get_underline_thickness(self, font, fontsize, dpi):
"""
Get the line thickness that matches the given font. Used as a
base unit for drawing lines such as in a fraction or radical.
"""
raise NotImplementedError()
def get_used_characters(self):
"""
Get the set of characters that were used in the math
expression. Used by backends that need to subset fonts so
they know which glyphs to include.
"""
return self.used_characters
def get_results(self, box):
"""
Get the data needed by the backend to render the math
expression. The return value is backend-specific.
"""
result = self.mathtext_backend.get_results(
box, self.get_used_characters())
self.destroy()
return result
def get_sized_alternatives_for_symbol(self, fontname, sym):
"""
Override if your font provides multiple sizes of the same
symbol. Should return a list of symbols matching *sym* in
various sizes. The expression renderer will select the most
appropriate size for a given situation from this list.
"""
return [(fontname, sym)]
class TruetypeFonts(Fonts):
"""
A generic base class for all font setups that use Truetype fonts
(through FT2Font).
"""
def __init__(self, default_font_prop, mathtext_backend):
Fonts.__init__(self, default_font_prop, mathtext_backend)
self.glyphd = {}
self._fonts = {}
filename = findfont(default_font_prop)
default_font = get_font(filename)
self._fonts['default'] = default_font
self._fonts['regular'] = default_font
def destroy(self):
self.glyphd = None
Fonts.destroy(self)
def _get_font(self, font):
if font in self.fontmap:
basename = self.fontmap[font]
else:
basename = font
cached_font = self._fonts.get(basename)
if cached_font is None and os.path.exists(basename):
cached_font = get_font(basename)
self._fonts[basename] = cached_font
self._fonts[cached_font.postscript_name] = cached_font
self._fonts[cached_font.postscript_name.lower()] = cached_font
return cached_font
def _get_offset(self, font, glyph, fontsize, dpi):
if font.postscript_name == 'Cmex10':
return ((glyph.height/64.0/2.0) + (fontsize/3.0 * dpi/72.0))
return 0.
def _get_info(self, fontname, font_class, sym, fontsize, dpi, math=True):
key = fontname, font_class, sym, fontsize, dpi
bunch = self.glyphd.get(key)
if bunch is not None:
return bunch
font, num, symbol_name, fontsize, slanted = \
self._get_glyph(fontname, font_class, sym, fontsize, math)
font.set_size(fontsize, dpi)
glyph = font.load_char(
num,
flags=self.mathtext_backend.get_hinting_type())
xmin, ymin, xmax, ymax = [val/64.0 for val in glyph.bbox]
offset = self._get_offset(font, glyph, fontsize, dpi)
metrics = types.SimpleNamespace(
advance = glyph.linearHoriAdvance/65536.0,
height = glyph.height/64.0,
width = glyph.width/64.0,
xmin = xmin,
xmax = xmax,
ymin = ymin+offset,
ymax = ymax+offset,
# iceberg is the equivalent of TeX's "height"
iceberg = glyph.horiBearingY/64.0 + offset,
slanted = slanted
)
result = self.glyphd[key] = types.SimpleNamespace(
font = font,
fontsize = fontsize,
postscript_name = font.postscript_name,
metrics = metrics,
symbol_name = symbol_name,
num = num,
glyph = glyph,
offset = offset
)
return result
def get_xheight(self, fontname, fontsize, dpi):
font = self._get_font(fontname)
font.set_size(fontsize, dpi)
pclt = font.get_sfnt_table('pclt')
if pclt is None:
# Some fonts don't store the xHeight, so we do a poor man's xHeight
metrics = self.get_metrics(
fontname, rcParams['mathtext.default'], 'x', fontsize, dpi)
return metrics.iceberg
xHeight = (pclt['xHeight'] / 64.0) * (fontsize / 12.0) * (dpi / 100.0)
return xHeight
def get_underline_thickness(self, font, fontsize, dpi):
# This function used to grab underline thickness from the font
# metrics, but that information is just too un-reliable, so it
# is now hardcoded.
return ((0.75 / 12.0) * fontsize * dpi) / 72.0
def get_kern(self, font1, fontclass1, sym1, fontsize1,
font2, fontclass2, sym2, fontsize2, dpi):
if font1 == font2 and fontsize1 == fontsize2:
info1 = self._get_info(font1, fontclass1, sym1, fontsize1, dpi)
info2 = self._get_info(font2, fontclass2, sym2, fontsize2, dpi)
font = info1.font
return font.get_kerning(info1.num, info2.num, KERNING_DEFAULT) / 64
return Fonts.get_kern(self, font1, fontclass1, sym1, fontsize1,
font2, fontclass2, sym2, fontsize2, dpi)
class BakomaFonts(TruetypeFonts):
"""
Use the Bakoma TrueType fonts for rendering.
Symbols are strewn about a number of font files, each of which has
its own proprietary 8-bit encoding.
"""
_fontmap = { 'cal' : 'cmsy10',
'rm' : 'cmr10',
'tt' : 'cmtt10',
'it' : 'cmmi10',
'bf' : 'cmb10',
'sf' : 'cmss10',
'ex' : 'cmex10'
}
def __init__(self, *args, **kwargs):
self._stix_fallback = StixFonts(*args, **kwargs)
TruetypeFonts.__init__(self, *args, **kwargs)
self.fontmap = {}
for key, val in self._fontmap.items():
fullpath = findfont(val)
self.fontmap[key] = fullpath
self.fontmap[val] = fullpath
_slanted_symbols = set(r"\int \oint".split())
def _get_glyph(self, fontname, font_class, sym, fontsize, math=True):
symbol_name = None
font = None
if fontname in self.fontmap and sym in latex_to_bakoma:
basename, num = latex_to_bakoma[sym]
slanted = (basename == "cmmi10") or sym in self._slanted_symbols
font = self._get_font(basename)
elif len(sym) == 1:
slanted = (fontname == "it")
font = self._get_font(fontname)
if font is not None:
num = ord(sym)
if font is not None:
gid = font.get_char_index(num)
if gid != 0:
symbol_name = font.get_glyph_name(gid)
if symbol_name is None:
return self._stix_fallback._get_glyph(
fontname, font_class, sym, fontsize, math)
return font, num, symbol_name, fontsize, slanted
# The Bakoma fonts contain many pre-sized alternatives for the
# delimiters. The AutoSizedChar class will use these alternatives
# and select the best (closest sized) glyph.
_size_alternatives = {
'(' : [('rm', '('), ('ex', '\xa1'), ('ex', '\xb3'),
('ex', '\xb5'), ('ex', '\xc3')],
')' : [('rm', ')'), ('ex', '\xa2'), ('ex', '\xb4'),
('ex', '\xb6'), ('ex', '\x21')],
'{' : [('cal', '{'), ('ex', '\xa9'), ('ex', '\x6e'),
('ex', '\xbd'), ('ex', '\x28')],
'}' : [('cal', '}'), ('ex', '\xaa'), ('ex', '\x6f'),
('ex', '\xbe'), ('ex', '\x29')],
# The fourth size of '[' is mysteriously missing from the BaKoMa
# font, so I've omitted it for both '[' and ']'
'[' : [('rm', '['), ('ex', '\xa3'), ('ex', '\x68'),
('ex', '\x22')],
']' : [('rm', ']'), ('ex', '\xa4'), ('ex', '\x69'),
('ex', '\x23')],
r'\lfloor' : [('ex', '\xa5'), ('ex', '\x6a'),
('ex', '\xb9'), ('ex', '\x24')],
r'\rfloor' : [('ex', '\xa6'), ('ex', '\x6b'),
('ex', '\xba'), ('ex', '\x25')],
r'\lceil' : [('ex', '\xa7'), ('ex', '\x6c'),
('ex', '\xbb'), ('ex', '\x26')],
r'\rceil' : [('ex', '\xa8'), ('ex', '\x6d'),
('ex', '\xbc'), ('ex', '\x27')],
r'\langle' : [('ex', '\xad'), ('ex', '\x44'),
('ex', '\xbf'), ('ex', '\x2a')],
r'\rangle' : [('ex', '\xae'), ('ex', '\x45'),
('ex', '\xc0'), ('ex', '\x2b')],
r'\__sqrt__' : [('ex', '\x70'), ('ex', '\x71'),
('ex', '\x72'), ('ex', '\x73')],
r'\backslash': [('ex', '\xb2'), ('ex', '\x2f'),
('ex', '\xc2'), ('ex', '\x2d')],
r'/' : [('rm', '/'), ('ex', '\xb1'), ('ex', '\x2e'),
('ex', '\xcb'), ('ex', '\x2c')],
r'\widehat' : [('rm', '\x5e'), ('ex', '\x62'), ('ex', '\x63'),
('ex', '\x64')],
r'\widetilde': [('rm', '\x7e'), ('ex', '\x65'), ('ex', '\x66'),
('ex', '\x67')],
r'<' : [('cal', 'h'), ('ex', 'D')],
r'>' : [('cal', 'i'), ('ex', 'E')]
}
for alias, target in [(r'\leftparen', '('),
(r'\rightparent', ')'),
(r'\leftbrace', '{'),
(r'\rightbrace', '}'),
(r'\leftbracket', '['),
(r'\rightbracket', ']'),
(r'\{', '{'),
(r'\}', '}'),
(r'\[', '['),
(r'\]', ']')]:
_size_alternatives[alias] = _size_alternatives[target]
def get_sized_alternatives_for_symbol(self, fontname, sym):
return self._size_alternatives.get(sym, [(fontname, sym)])
class UnicodeFonts(TruetypeFonts):
"""
An abstract base class for handling Unicode fonts.
While some reasonably complete Unicode fonts (such as DejaVu) may
work in some situations, the only Unicode font I'm aware of with a
complete set of math symbols is STIX.
This class will "fallback" on the Bakoma fonts when a required
symbol can not be found in the font.
"""
use_cmex = True
def __init__(self, *args, **kwargs):
# This must come first so the backend's owner is set correctly
if rcParams['mathtext.fallback_to_cm']:
self.cm_fallback = BakomaFonts(*args, **kwargs)
else:
self.cm_fallback = None
TruetypeFonts.__init__(self, *args, **kwargs)
self.fontmap = {}
for texfont in "cal rm tt it bf sf".split():
prop = rcParams['mathtext.' + texfont]
font = findfont(prop)
self.fontmap[texfont] = font
prop = FontProperties('cmex10')
font = findfont(prop)
self.fontmap['ex'] = font
_slanted_symbols = set(r"\int \oint".split())
def _map_virtual_font(self, fontname, font_class, uniindex):
return fontname, uniindex
def _get_glyph(self, fontname, font_class, sym, fontsize, math=True):
found_symbol = False
if self.use_cmex:
uniindex = latex_to_cmex.get(sym)
if uniindex is not None:
fontname = 'ex'
found_symbol = True
if not found_symbol:
try:
uniindex = get_unicode_index(sym, math)
found_symbol = True
except ValueError:
uniindex = ord('?')
_log.warning(
"No TeX to unicode mapping for {!a}.".format(sym))
fontname, uniindex = self._map_virtual_font(
fontname, font_class, uniindex)
new_fontname = fontname
# Only characters in the "Letter" class should be italicized in 'it'
# mode. Greek capital letters should be Roman.
if found_symbol:
if fontname == 'it' and uniindex < 0x10000:
char = chr(uniindex)
if (not unicodedata.category(char)[0] == "L"
or unicodedata.name(char).startswith("GREEK CAPITAL")):
new_fontname = 'rm'
slanted = (new_fontname == 'it') or sym in self._slanted_symbols
found_symbol = False
font = self._get_font(new_fontname)
if font is not None:
glyphindex = font.get_char_index(uniindex)
if glyphindex != 0:
found_symbol = True
if not found_symbol:
if self.cm_fallback:
if isinstance(self.cm_fallback, BakomaFonts):
_log.warning(
"Substituting with a symbol from Computer Modern.")
if (fontname in ('it', 'regular') and
isinstance(self.cm_fallback, StixFonts)):
return self.cm_fallback._get_glyph(
'rm', font_class, sym, fontsize)
else:
return self.cm_fallback._get_glyph(
fontname, font_class, sym, fontsize)
else:
if (fontname in ('it', 'regular')
and isinstance(self, StixFonts)):
return self._get_glyph('rm', font_class, sym, fontsize)
_log.warning("Font {!r} does not have a glyph for {!a} "
"[U+{:x}], substituting with a dummy "
"symbol.".format(new_fontname, sym, uniindex))
fontname = 'rm'
font = self._get_font(fontname)
uniindex = 0xA4 # currency char, for lack of anything better
glyphindex = font.get_char_index(uniindex)
slanted = False
symbol_name = font.get_glyph_name(glyphindex)
return font, uniindex, symbol_name, fontsize, slanted
def get_sized_alternatives_for_symbol(self, fontname, sym):
if self.cm_fallback:
return self.cm_fallback.get_sized_alternatives_for_symbol(
fontname, sym)
return [(fontname, sym)]
class DejaVuFonts(UnicodeFonts):
use_cmex = False
def __init__(self, *args, **kwargs):
# This must come first so the backend's owner is set correctly
if isinstance(self, DejaVuSerifFonts):
self.cm_fallback = StixFonts(*args, **kwargs)
else:
self.cm_fallback = StixSansFonts(*args, **kwargs)
self.bakoma = BakomaFonts(*args, **kwargs)
TruetypeFonts.__init__(self, *args, **kwargs)
self.fontmap = {}
# Include Stix sized alternatives for glyphs
self._fontmap.update({
1 : 'STIXSizeOneSym',
2 : 'STIXSizeTwoSym',
3 : 'STIXSizeThreeSym',
4 : 'STIXSizeFourSym',
5 : 'STIXSizeFiveSym'})
for key, name in self._fontmap.items():
fullpath = findfont(name)
self.fontmap[key] = fullpath
self.fontmap[name] = fullpath
def _get_glyph(self, fontname, font_class, sym, fontsize, math=True):
# Override prime symbol to use Bakoma.
if sym == r'\prime':
return self.bakoma._get_glyph(
fontname, font_class, sym, fontsize, math)
else:
# check whether the glyph is available in the display font
uniindex = get_unicode_index(sym)
font = self._get_font('ex')
if font is not None:
glyphindex = font.get_char_index(uniindex)
if glyphindex != 0:
return super()._get_glyph(
'ex', font_class, sym, fontsize, math)
# otherwise return regular glyph
return super()._get_glyph(
fontname, font_class, sym, fontsize, math)
class DejaVuSerifFonts(DejaVuFonts):
"""
A font handling class for the DejaVu Serif fonts
If a glyph is not found it will fallback to Stix Serif
"""
_fontmap = { 'rm' : 'DejaVu Serif',
'it' : 'DejaVu Serif:italic',
'bf' : 'DejaVu Serif:weight=bold',
'sf' : 'DejaVu Sans',
'tt' : 'DejaVu Sans Mono',
'ex' : 'DejaVu Serif Display',
0 : 'DejaVu Serif',
}
class DejaVuSansFonts(DejaVuFonts):
"""
A font handling class for the DejaVu Sans fonts
If a glyph is not found it will fallback to Stix Sans
"""
_fontmap = { 'rm' : 'DejaVu Sans',
'it' : 'DejaVu Sans:italic',
'bf' : 'DejaVu Sans:weight=bold',
'sf' : 'DejaVu Sans',
'tt' : 'DejaVu Sans Mono',
'ex' : 'DejaVu Sans Display',
0 : 'DejaVu Sans',
}
class StixFonts(UnicodeFonts):
"""
A font handling class for the STIX fonts.
In addition to what UnicodeFonts provides, this class:
- supports "virtual fonts" which are complete alpha numeric
character sets with different font styles at special Unicode
code points, such as "Blackboard".
- handles sized alternative characters for the STIXSizeX fonts.
"""
_fontmap = { 'rm' : 'STIXGeneral',
'it' : 'STIXGeneral:italic',
'bf' : 'STIXGeneral:weight=bold',
'nonunirm' : 'STIXNonUnicode',
'nonuniit' : 'STIXNonUnicode:italic',
'nonunibf' : 'STIXNonUnicode:weight=bold',
0 : 'STIXGeneral',
1 : 'STIXSizeOneSym',
2 : 'STIXSizeTwoSym',
3 : 'STIXSizeThreeSym',
4 : 'STIXSizeFourSym',
5 : 'STIXSizeFiveSym'
}
use_cmex = False
cm_fallback = False
_sans = False
def __init__(self, *args, **kwargs):
TruetypeFonts.__init__(self, *args, **kwargs)
self.fontmap = {}
for key, name in self._fontmap.items():
fullpath = findfont(name)
self.fontmap[key] = fullpath
self.fontmap[name] = fullpath
def _map_virtual_font(self, fontname, font_class, uniindex):
# Handle these "fonts" that are actually embedded in
# other fonts.
mapping = stix_virtual_fonts.get(fontname)
if (self._sans and mapping is None
and fontname not in ('regular', 'default')):
mapping = stix_virtual_fonts['sf']
doing_sans_conversion = True
else:
doing_sans_conversion = False
if mapping is not None:
if isinstance(mapping, dict):
try:
mapping = mapping[font_class]
except KeyError:
mapping = mapping['rm']
# Binary search for the source glyph
lo = 0
hi = len(mapping)
while lo < hi:
mid = (lo+hi)//2
range = mapping[mid]
if uniindex < range[0]:
hi = mid
elif uniindex <= range[1]:
break
else:
lo = mid + 1
if range[0] <= uniindex <= range[1]:
uniindex = uniindex - range[0] + range[3]
fontname = range[2]
elif not doing_sans_conversion:
# This will generate a dummy character
uniindex = 0x1
fontname = rcParams['mathtext.default']
# Handle private use area glyphs
if fontname in ('it', 'rm', 'bf') and 0xe000 <= uniindex <= 0xf8ff:
fontname = 'nonuni' + fontname
return fontname, uniindex
_size_alternatives = {}
def get_sized_alternatives_for_symbol(self, fontname, sym):
fixes = {'\\{': '{', '\\}': '}', '\\[': '[', '\\]': ']'}
sym = fixes.get(sym, sym)
alternatives = self._size_alternatives.get(sym)
if alternatives:
return alternatives
alternatives = []
try:
uniindex = get_unicode_index(sym)
except ValueError:
return [(fontname, sym)]
fix_ups = {
ord('<'): 0x27e8,
ord('>'): 0x27e9 }
uniindex = fix_ups.get(uniindex, uniindex)
for i in range(6):
font = self._get_font(i)
glyphindex = font.get_char_index(uniindex)
if glyphindex != 0:
alternatives.append((i, chr(uniindex)))
# The largest size of the radical symbol in STIX has incorrect
# metrics that cause it to be disconnected from the stem.
if sym == r'\__sqrt__':
alternatives = alternatives[:-1]
self._size_alternatives[sym] = alternatives
return alternatives
class StixSansFonts(StixFonts):
"""
A font handling class for the STIX fonts (that uses sans-serif
characters by default).
"""
_sans = True
class StandardPsFonts(Fonts):
"""
Use the standard postscript fonts for rendering to backend_ps
Unlike the other font classes, BakomaFont and UnicodeFont, this
one requires the Ps backend.
"""
basepath = os.path.join(get_data_path(), 'fonts', 'afm')
fontmap = { 'cal' : 'pzcmi8a', # Zapf Chancery
'rm' : 'pncr8a', # New Century Schoolbook
'tt' : 'pcrr8a', # Courier
'it' : 'pncri8a', # New Century Schoolbook Italic
'sf' : 'phvr8a', # Helvetica
'bf' : 'pncb8a', # New Century Schoolbook Bold
None : 'psyr' # Symbol
}
def __init__(self, default_font_prop):
Fonts.__init__(self, default_font_prop, MathtextBackendPs())
self.glyphd = {}
self.fonts = {}
filename = findfont(default_font_prop, fontext='afm',
directory=self.basepath)
if filename is None:
filename = findfont('Helvetica', fontext='afm',
directory=self.basepath)
with open(filename, 'rb') as fd:
default_font = AFM(fd)
default_font.fname = filename
self.fonts['default'] = default_font
self.fonts['regular'] = default_font
self.pswriter = StringIO()
def _get_font(self, font):
if font in self.fontmap:
basename = self.fontmap[font]
else:
basename = font
cached_font = self.fonts.get(basename)
if cached_font is None:
fname = os.path.join(self.basepath, basename + ".afm")
with open(fname, 'rb') as fd:
cached_font = AFM(fd)
cached_font.fname = fname
self.fonts[basename] = cached_font
self.fonts[cached_font.get_fontname()] = cached_font
return cached_font
def _get_info(self, fontname, font_class, sym, fontsize, dpi, math=True):
'load the cmfont, metrics and glyph with caching'
key = fontname, sym, fontsize, dpi
tup = self.glyphd.get(key)
if tup is not None:
return tup
# Only characters in the "Letter" class should really be italicized.
# This class includes greek letters, so we're ok
if (fontname == 'it' and
(len(sym) > 1
or not unicodedata.category(sym).startswith("L"))):
fontname = 'rm'
found_symbol = False
if sym in latex_to_standard:
fontname, num = latex_to_standard[sym]
glyph = chr(num)
found_symbol = True
elif len(sym) == 1:
glyph = sym
num = ord(glyph)
found_symbol = True
else:
_log.warning(
"No TeX to built-in Postscript mapping for {!r}".format(sym))
slanted = (fontname == 'it')
font = self._get_font(fontname)
if found_symbol:
try:
symbol_name = font.get_name_char(glyph)
except KeyError:
_log.warning(
"No glyph in standard Postscript font {!r} for {!r}"
.format(font.get_fontname(), sym))
found_symbol = False
if not found_symbol:
glyph = '?'
num = ord(glyph)
symbol_name = font.get_name_char(glyph)
offset = 0
scale = 0.001 * fontsize
xmin, ymin, xmax, ymax = [val * scale
for val in font.get_bbox_char(glyph)]
metrics = types.SimpleNamespace(
advance = font.get_width_char(glyph) * scale,
width = font.get_width_char(glyph) * scale,
height = font.get_height_char(glyph) * scale,
xmin = xmin,
xmax = xmax,
ymin = ymin+offset,
ymax = ymax+offset,
# iceberg is the equivalent of TeX's "height"
iceberg = ymax + offset,
slanted = slanted
)
self.glyphd[key] = types.SimpleNamespace(
font = font,
fontsize = fontsize,
postscript_name = font.get_fontname(),
metrics = metrics,
symbol_name = symbol_name,
num = num,
glyph = glyph,
offset = offset
)
return self.glyphd[key]
def get_kern(self, font1, fontclass1, sym1, fontsize1,
font2, fontclass2, sym2, fontsize2, dpi):
if font1 == font2 and fontsize1 == fontsize2:
info1 = self._get_info(font1, fontclass1, sym1, fontsize1, dpi)
info2 = self._get_info(font2, fontclass2, sym2, fontsize2, dpi)
font = info1.font
return (font.get_kern_dist(info1.glyph, info2.glyph)
* 0.001 * fontsize1)
return Fonts.get_kern(self, font1, fontclass1, sym1, fontsize1,
font2, fontclass2, sym2, fontsize2, dpi)
def get_xheight(self, font, fontsize, dpi):
font = self._get_font(font)
return font.get_xheight() * 0.001 * fontsize
def get_underline_thickness(self, font, fontsize, dpi):
font = self._get_font(font)
return font.get_underline_thickness() * 0.001 * fontsize
##############################################################################
# TeX-LIKE BOX MODEL
# The following is based directly on the document 'woven' from the
# TeX82 source code. This information is also available in printed
# form:
#
# Knuth, Donald E.. 1986. Computers and Typesetting, Volume B:
# TeX: The Program. Addison-Wesley Professional.
#
# The most relevant "chapters" are:
# Data structures for boxes and their friends
# Shipping pages out (Ship class)
# Packaging (hpack and vpack)
# Data structures for math mode
# Subroutines for math mode
# Typesetting math formulas
#
# Many of the docstrings below refer to a numbered "node" in that
# book, e.g., node123
#
# Note that (as TeX) y increases downward, unlike many other parts of
# matplotlib.
# How much text shrinks when going to the next-smallest level. GROW_FACTOR
# must be the inverse of SHRINK_FACTOR.
SHRINK_FACTOR = 0.7
GROW_FACTOR = 1.0 / SHRINK_FACTOR
# The number of different sizes of chars to use, beyond which they will not
# get any smaller
NUM_SIZE_LEVELS = 6
class FontConstantsBase(object):
"""
A set of constants that controls how certain things, such as sub-
and superscripts are laid out. These are all metrics that can't
be reliably retrieved from the font metrics in the font itself.
"""
# Percentage of x-height of additional horiz. space after sub/superscripts
script_space = 0.05
# Percentage of x-height that sub/superscripts drop below the baseline
subdrop = 0.4
# Percentage of x-height that superscripts are raised from the baseline
sup1 = 0.7
# Percentage of x-height that subscripts drop below the baseline
sub1 = 0.3
# Percentage of x-height that subscripts drop below the baseline when a
# superscript is present
sub2 = 0.5
# Percentage of x-height that sub/supercripts are offset relative to the
# nucleus edge for non-slanted nuclei
delta = 0.025
# Additional percentage of last character height above 2/3 of the
# x-height that supercripts are offset relative to the subscript
# for slanted nuclei
delta_slanted = 0.2
# Percentage of x-height that supercripts and subscripts are offset for
# integrals
delta_integral = 0.1
class ComputerModernFontConstants(FontConstantsBase):
script_space = 0.075
subdrop = 0.2
sup1 = 0.45
sub1 = 0.2
sub2 = 0.3
delta = 0.075
delta_slanted = 0.3
delta_integral = 0.3
class STIXFontConstants(FontConstantsBase):
script_space = 0.1
sup1 = 0.8
sub2 = 0.6
delta = 0.05
delta_slanted = 0.3
delta_integral = 0.3
class STIXSansFontConstants(FontConstantsBase):
script_space = 0.05
sup1 = 0.8
delta_slanted = 0.6
delta_integral = 0.3
class DejaVuSerifFontConstants(FontConstantsBase):
pass
class DejaVuSansFontConstants(FontConstantsBase):
pass
# Maps font family names to the FontConstantBase subclass to use
_font_constant_mapping = {
'DejaVu Sans': DejaVuSansFontConstants,
'DejaVu Sans Mono': DejaVuSansFontConstants,
'DejaVu Serif': DejaVuSerifFontConstants,
'cmb10': ComputerModernFontConstants,
'cmex10': ComputerModernFontConstants,
'cmmi10': ComputerModernFontConstants,
'cmr10': ComputerModernFontConstants,
'cmss10': ComputerModernFontConstants,
'cmsy10': ComputerModernFontConstants,
'cmtt10': ComputerModernFontConstants,
'STIXGeneral': STIXFontConstants,
'STIXNonUnicode': STIXFontConstants,
'STIXSizeFiveSym': STIXFontConstants,
'STIXSizeFourSym': STIXFontConstants,
'STIXSizeThreeSym': STIXFontConstants,
'STIXSizeTwoSym': STIXFontConstants,
'STIXSizeOneSym': STIXFontConstants,
# Map the fonts we used to ship, just for good measure
'Bitstream Vera Sans': DejaVuSansFontConstants,
'Bitstream Vera': DejaVuSansFontConstants,
}
def _get_font_constant_set(state):
constants = _font_constant_mapping.get(
state.font_output._get_font(state.font).family_name,
FontConstantsBase)
# STIX sans isn't really its own fonts, just different code points
# in the STIX fonts, so we have to detect this one separately.
if (constants is STIXFontConstants and
isinstance(state.font_output, StixSansFonts)):
return STIXSansFontConstants
return constants
class MathTextWarning(Warning):
pass
class Node(object):
"""
A node in the TeX box model
"""
def __init__(self):
self.size = 0
def __repr__(self):
return self.__class__.__name__
def get_kerning(self, next):
return 0.0
def shrink(self):
"""
Shrinks one level smaller. There are only three levels of
sizes, after which things will no longer get smaller.
"""
self.size += 1
def grow(self):
"""
Grows one level larger. There is no limit to how big
something can get.
"""
self.size -= 1
def render(self, x, y):
pass
class Box(Node):
"""
Represents any node with a physical location.
"""
def __init__(self, width, height, depth):
Node.__init__(self)
self.width = width
self.height = height
self.depth = depth
def shrink(self):
Node.shrink(self)
if self.size < NUM_SIZE_LEVELS:
self.width *= SHRINK_FACTOR
self.height *= SHRINK_FACTOR
self.depth *= SHRINK_FACTOR
def grow(self):
Node.grow(self)
self.width *= GROW_FACTOR
self.height *= GROW_FACTOR
self.depth *= GROW_FACTOR
def render(self, x1, y1, x2, y2):
pass
class Vbox(Box):
"""
A box with only height (zero width).
"""
def __init__(self, height, depth):
Box.__init__(self, 0., height, depth)
class Hbox(Box):
"""
A box with only width (zero height and depth).
"""
def __init__(self, width):
Box.__init__(self, width, 0., 0.)
class Char(Node):
"""
Represents a single character. Unlike TeX, the font information
and metrics are stored with each :class:`Char` to make it easier
to lookup the font metrics when needed. Note that TeX boxes have
a width, height, and depth, unlike Type1 and Truetype which use a
full bounding box and an advance in the x-direction. The metrics
must be converted to the TeX way, and the advance (if different
from width) must be converted into a :class:`Kern` node when the
:class:`Char` is added to its parent :class:`Hlist`.
"""
def __init__(self, c, state, math=True):
Node.__init__(self)
self.c = c
self.font_output = state.font_output
self.font = state.font
self.font_class = state.font_class
self.fontsize = state.fontsize
self.dpi = state.dpi
self.math = math
# The real width, height and depth will be set during the
# pack phase, after we know the real fontsize
self._update_metrics()
def __repr__(self):
return '`%s`' % self.c
def _update_metrics(self):
metrics = self._metrics = self.font_output.get_metrics(
self.font, self.font_class, self.c, self.fontsize, self.dpi,
self.math)
if self.c == ' ':
self.width = metrics.advance
else:
self.width = metrics.width
self.height = metrics.iceberg
self.depth = -(metrics.iceberg - metrics.height)
def is_slanted(self):
return self._metrics.slanted
def get_kerning(self, next):
"""
Return the amount of kerning between this and the given
character. Called when characters are strung together into
:class:`Hlist` to create :class:`Kern` nodes.
"""
advance = self._metrics.advance - self.width
kern = 0.
if isinstance(next, Char):
kern = self.font_output.get_kern(
self.font, self.font_class, self.c, self.fontsize,
next.font, next.font_class, next.c, next.fontsize,
self.dpi)
return advance + kern
def render(self, x, y):
"""
Render the character to the canvas
"""
self.font_output.render_glyph(
x, y,
self.font, self.font_class, self.c, self.fontsize, self.dpi)
def shrink(self):
Node.shrink(self)
if self.size < NUM_SIZE_LEVELS:
self.fontsize *= SHRINK_FACTOR
self.width *= SHRINK_FACTOR
self.height *= SHRINK_FACTOR
self.depth *= SHRINK_FACTOR
def grow(self):
Node.grow(self)
self.fontsize *= GROW_FACTOR
self.width *= GROW_FACTOR
self.height *= GROW_FACTOR
self.depth *= GROW_FACTOR
class Accent(Char):
"""
The font metrics need to be dealt with differently for accents,
since they are already offset correctly from the baseline in
TrueType fonts.
"""
def _update_metrics(self):
metrics = self._metrics = self.font_output.get_metrics(
self.font, self.font_class, self.c, self.fontsize, self.dpi)
self.width = metrics.xmax - metrics.xmin
self.height = metrics.ymax - metrics.ymin
self.depth = 0
def shrink(self):
Char.shrink(self)
self._update_metrics()
def grow(self):
Char.grow(self)
self._update_metrics()
def render(self, x, y):
"""
Render the character to the canvas.
"""
self.font_output.render_glyph(
x - self._metrics.xmin, y + self._metrics.ymin,
self.font, self.font_class, self.c, self.fontsize, self.dpi)
class List(Box):
"""
A list of nodes (either horizontal or vertical).
"""
def __init__(self, elements):
Box.__init__(self, 0., 0., 0.)
self.shift_amount = 0. # An arbitrary offset
self.children = elements # The child nodes of this list
# The following parameters are set in the vpack and hpack functions
self.glue_set = 0. # The glue setting of this list
self.glue_sign = 0 # 0: normal, -1: shrinking, 1: stretching
self.glue_order = 0 # The order of infinity (0 - 3) for the glue
def __repr__(self):
return '[%s <%.02f %.02f %.02f %.02f> %s]' % (
super().__repr__(),
self.width, self.height,
self.depth, self.shift_amount,
' '.join([repr(x) for x in self.children]))
@staticmethod
def _determine_order(totals):
"""
Determine the highest order of glue used by the members of this list.
Helper function used by vpack and hpack.
"""
for i in range(len(totals))[::-1]:
if totals[i] != 0:
return i
return 0
def _set_glue(self, x, sign, totals, error_type):
o = self._determine_order(totals)
self.glue_order = o
self.glue_sign = sign
if totals[o] != 0.:
self.glue_set = x / totals[o]
else:
self.glue_sign = 0
self.glue_ratio = 0.
if o == 0:
if len(self.children):
_log.warning("%s %s: %r",
error_type, self.__class__.__name__, self)
def shrink(self):
for child in self.children:
child.shrink()
Box.shrink(self)
if self.size < NUM_SIZE_LEVELS:
self.shift_amount *= SHRINK_FACTOR
self.glue_set *= SHRINK_FACTOR
def grow(self):
for child in self.children:
child.grow()
Box.grow(self)
self.shift_amount *= GROW_FACTOR
self.glue_set *= GROW_FACTOR
class Hlist(List):
"""
A horizontal list of boxes.
"""
def __init__(self, elements, w=0., m='additional', do_kern=True):
List.__init__(self, elements)
if do_kern:
self.kern()
self.hpack()
def kern(self):
"""
Insert :class:`Kern` nodes between :class:`Char` nodes to set
kerning. The :class:`Char` nodes themselves determine the
amount of kerning they need (in :meth:`~Char.get_kerning`),
and this function just creates the linked list in the correct
way.
"""
new_children = []
num_children = len(self.children)
if num_children:
for i in range(num_children):
elem = self.children[i]
if i < num_children - 1:
next = self.children[i + 1]
else:
next = None
new_children.append(elem)
kerning_distance = elem.get_kerning(next)
if kerning_distance != 0.:
kern = Kern(kerning_distance)
new_children.append(kern)
self.children = new_children
# This is a failed experiment to fake cross-font kerning.
# def get_kerning(self, next):
# if len(self.children) >= 2 and isinstance(self.children[-2], Char):
# if isinstance(next, Char):
# print "CASE A"
# return self.children[-2].get_kerning(next)
# elif (isinstance(next, Hlist) and len(next.children)
# and isinstance(next.children[0], Char)):
# print "CASE B"
# result = self.children[-2].get_kerning(next.children[0])
# print result
# return result
# return 0.0
def hpack(self, w=0., m='additional'):
"""
The main duty of :meth:`hpack` is to compute the dimensions of
the resulting boxes, and to adjust the glue if one of those
dimensions is pre-specified. The computed sizes normally
enclose all of the material inside the new box; but some items
may stick out if negative glue is used, if the box is
overfull, or if a ``\\vbox`` includes other boxes that have
been shifted left.
- *w*: specifies a width
- *m*: is either 'exactly' or 'additional'.
Thus, ``hpack(w, 'exactly')`` produces a box whose width is
exactly *w*, while ``hpack(w, 'additional')`` yields a box
whose width is the natural width plus *w*. The default values
produce a box with the natural width.
"""
# I don't know why these get reset in TeX. Shift_amount is pretty
# much useless if we do.
# self.shift_amount = 0.
h = 0.
d = 0.
x = 0.
total_stretch = [0.] * 4
total_shrink = [0.] * 4
for p in self.children:
if isinstance(p, Char):
x += p.width
h = max(h, p.height)
d = max(d, p.depth)
elif isinstance(p, Box):
x += p.width
if not np.isinf(p.height) and not np.isinf(p.depth):
s = getattr(p, 'shift_amount', 0.)
h = max(h, p.height - s)
d = max(d, p.depth + s)
elif isinstance(p, Glue):
glue_spec = p.glue_spec
x += glue_spec.width
total_stretch[glue_spec.stretch_order] += glue_spec.stretch
total_shrink[glue_spec.shrink_order] += glue_spec.shrink
elif isinstance(p, Kern):
x += p.width
self.height = h
self.depth = d
if m == 'additional':
w += x
self.width = w
x = w - x
if x == 0.:
self.glue_sign = 0
self.glue_order = 0
self.glue_ratio = 0.
return
if x > 0.:
self._set_glue(x, 1, total_stretch, "Overfull")
else:
self._set_glue(x, -1, total_shrink, "Underfull")
class Vlist(List):
"""
A vertical list of boxes.
"""
def __init__(self, elements, h=0., m='additional'):
List.__init__(self, elements)
self.vpack()
def vpack(self, h=0., m='additional', l=np.inf):
"""
The main duty of :meth:`vpack` is to compute the dimensions of
the resulting boxes, and to adjust the glue if one of those
dimensions is pre-specified.
- *h*: specifies a height
- *m*: is either 'exactly' or 'additional'.
- *l*: a maximum height
Thus, ``vpack(h, 'exactly')`` produces a box whose height is
exactly *h*, while ``vpack(h, 'additional')`` yields a box
whose height is the natural height plus *h*. The default
values produce a box with the natural width.
"""
# I don't know why these get reset in TeX. Shift_amount is pretty
# much useless if we do.
# self.shift_amount = 0.
w = 0.
d = 0.
x = 0.
total_stretch = [0.] * 4
total_shrink = [0.] * 4
for p in self.children:
if isinstance(p, Box):
x += d + p.height
d = p.depth
if not np.isinf(p.width):
s = getattr(p, 'shift_amount', 0.)
w = max(w, p.width + s)
elif isinstance(p, Glue):
x += d
d = 0.
glue_spec = p.glue_spec
x += glue_spec.width
total_stretch[glue_spec.stretch_order] += glue_spec.stretch
total_shrink[glue_spec.shrink_order] += glue_spec.shrink
elif isinstance(p, Kern):
x += d + p.width
d = 0.
elif isinstance(p, Char):
raise RuntimeError(
"Internal mathtext error: Char node found in Vlist")
self.width = w
if d > l:
x += d - l
self.depth = l
else:
self.depth = d
if m == 'additional':
h += x
self.height = h
x = h - x
if x == 0:
self.glue_sign = 0
self.glue_order = 0
self.glue_ratio = 0.
return
if x > 0.:
self._set_glue(x, 1, total_stretch, "Overfull")
else:
self._set_glue(x, -1, total_shrink, "Underfull")
class Rule(Box):
"""
A :class:`Rule` node stands for a solid black rectangle; it has
*width*, *depth*, and *height* fields just as in an
:class:`Hlist`. However, if any of these dimensions is inf, the
actual value will be determined by running the rule up to the
boundary of the innermost enclosing box. This is called a "running
dimension." The width is never running in an :class:`Hlist`; the
height and depth are never running in a :class:`Vlist`.
"""
def __init__(self, width, height, depth, state):
Box.__init__(self, width, height, depth)
self.font_output = state.font_output
def render(self, x, y, w, h):
self.font_output.render_rect_filled(x, y, x + w, y + h)
class Hrule(Rule):
"""
Convenience class to create a horizontal rule.
"""
def __init__(self, state, thickness=None):
if thickness is None:
thickness = state.font_output.get_underline_thickness(
state.font, state.fontsize, state.dpi)
height = depth = thickness * 0.5
Rule.__init__(self, np.inf, height, depth, state)
class Vrule(Rule):
"""
Convenience class to create a vertical rule.
"""
def __init__(self, state):
thickness = state.font_output.get_underline_thickness(
state.font, state.fontsize, state.dpi)
Rule.__init__(self, thickness, np.inf, np.inf, state)
class Glue(Node):
"""
Most of the information in this object is stored in the underlying
:class:`GlueSpec` class, which is shared between multiple glue objects.
(This is a memory optimization which probably doesn't matter anymore, but
it's easier to stick to what TeX does.)
"""
def __init__(self, glue_type, copy=False):
Node.__init__(self)
self.glue_subtype = 'normal'
if isinstance(glue_type, str):
glue_spec = GlueSpec.factory(glue_type)
elif isinstance(glue_type, GlueSpec):
glue_spec = glue_type
else:
raise ValueError("glue_type must be a glue spec name or instance")
if copy:
glue_spec = glue_spec.copy()
self.glue_spec = glue_spec
def shrink(self):
Node.shrink(self)
if self.size < NUM_SIZE_LEVELS:
if self.glue_spec.width != 0.:
self.glue_spec = self.glue_spec.copy()
self.glue_spec.width *= SHRINK_FACTOR
def grow(self):
Node.grow(self)
if self.glue_spec.width != 0.:
self.glue_spec = self.glue_spec.copy()
self.glue_spec.width *= GROW_FACTOR
class GlueSpec(object):
"""
See :class:`Glue`.
"""
def __init__(self, width=0., stretch=0., stretch_order=0,
shrink=0., shrink_order=0):
self.width = width
self.stretch = stretch
self.stretch_order = stretch_order
self.shrink = shrink
self.shrink_order = shrink_order
def copy(self):
return GlueSpec(
self.width,
self.stretch,
self.stretch_order,
self.shrink,
self.shrink_order)
def factory(cls, glue_type):
return cls._types[glue_type]
factory = classmethod(factory)
GlueSpec._types = {
'fil': GlueSpec(0., 1., 1, 0., 0),
'fill': GlueSpec(0., 1., 2, 0., 0),
'filll': GlueSpec(0., 1., 3, 0., 0),
'neg_fil': GlueSpec(0., 0., 0, 1., 1),
'neg_fill': GlueSpec(0., 0., 0, 1., 2),
'neg_filll': GlueSpec(0., 0., 0, 1., 3),
'empty': GlueSpec(0., 0., 0, 0., 0),
'ss': GlueSpec(0., 1., 1, -1., 1)
}
# Some convenient ways to get common kinds of glue
class Fil(Glue):
def __init__(self):
Glue.__init__(self, 'fil')
class Fill(Glue):
def __init__(self):
Glue.__init__(self, 'fill')
class Filll(Glue):
def __init__(self):
Glue.__init__(self, 'filll')
class NegFil(Glue):
def __init__(self):
Glue.__init__(self, 'neg_fil')
class NegFill(Glue):
def __init__(self):
Glue.__init__(self, 'neg_fill')
class NegFilll(Glue):
def __init__(self):
Glue.__init__(self, 'neg_filll')
class SsGlue(Glue):
def __init__(self):
Glue.__init__(self, 'ss')
class HCentered(Hlist):
"""
A convenience class to create an :class:`Hlist` whose contents are
centered within its enclosing box.
"""
def __init__(self, elements):
Hlist.__init__(self, [SsGlue()] + elements + [SsGlue()],
do_kern=False)
class VCentered(Hlist):
"""
A convenience class to create a :class:`Vlist` whose contents are
centered within its enclosing box.
"""
def __init__(self, elements):
Vlist.__init__(self, [SsGlue()] + elements + [SsGlue()])
class Kern(Node):
"""
A :class:`Kern` node has a width field to specify a (normally
negative) amount of spacing. This spacing correction appears in
horizontal lists between letters like A and V when the font
designer said that it looks better to move them closer together or
further apart. A kern node can also appear in a vertical list,
when its *width* denotes additional spacing in the vertical
direction.
"""
height = 0
depth = 0
def __init__(self, width):
Node.__init__(self)
self.width = width
def __repr__(self):
return "k%.02f" % self.width
def shrink(self):
Node.shrink(self)
if self.size < NUM_SIZE_LEVELS:
self.width *= SHRINK_FACTOR
def grow(self):
Node.grow(self)
self.width *= GROW_FACTOR
class SubSuperCluster(Hlist):
"""
:class:`SubSuperCluster` is a sort of hack to get around that fact
that this code do a two-pass parse like TeX. This lets us store
enough information in the hlist itself, namely the nucleus, sub-
and super-script, such that if another script follows that needs
to be attached, it can be reconfigured on the fly.
"""
def __init__(self):
self.nucleus = None
self.sub = None
self.super = None
Hlist.__init__(self, [])
class AutoHeightChar(Hlist):
"""
:class:`AutoHeightChar` will create a character as close to the
given height and depth as possible. When using a font with
multiple height versions of some characters (such as the BaKoMa
fonts), the correct glyph will be selected, otherwise this will
always just return a scaled version of the glyph.
"""
def __init__(self, c, height, depth, state, always=False, factor=None):
alternatives = state.font_output.get_sized_alternatives_for_symbol(
state.font, c)
xHeight = state.font_output.get_xheight(
state.font, state.fontsize, state.dpi)
state = state.copy()
target_total = height + depth
for fontname, sym in alternatives:
state.font = fontname
char = Char(sym, state)
# Ensure that size 0 is chosen when the text is regular sized but
# with descender glyphs by subtracting 0.2 * xHeight
if char.height + char.depth >= target_total - 0.2 * xHeight:
break
shift = 0
if state.font != 0:
if factor is None:
factor = (target_total) / (char.height + char.depth)
state.fontsize *= factor
char = Char(sym, state)
shift = (depth - char.depth)
Hlist.__init__(self, [char])
self.shift_amount = shift
class AutoWidthChar(Hlist):
"""
:class:`AutoWidthChar` will create a character as close to the
given width as possible. When using a font with multiple width
versions of some characters (such as the BaKoMa fonts), the
correct glyph will be selected, otherwise this will always just
return a scaled version of the glyph.
"""
def __init__(self, c, width, state, always=False, char_class=Char):
alternatives = state.font_output.get_sized_alternatives_for_symbol(
state.font, c)
state = state.copy()
for fontname, sym in alternatives:
state.font = fontname
char = char_class(sym, state)
if char.width >= width:
break
factor = width / char.width
state.fontsize *= factor
char = char_class(sym, state)
Hlist.__init__(self, [char])
self.width = char.width
class Ship(object):
"""
Once the boxes have been set up, this sends them to output. Since
boxes can be inside of boxes inside of boxes, the main work of
:class:`Ship` is done by two mutually recursive routines,
:meth:`hlist_out` and :meth:`vlist_out`, which traverse the
:class:`Hlist` nodes and :class:`Vlist` nodes inside of horizontal
and vertical boxes. The global variables used in TeX to store
state as it processes have become member variables here.
"""
def __call__(self, ox, oy, box):
self.max_push = 0 # Deepest nesting of push commands so far
self.cur_s = 0
self.cur_v = 0.
self.cur_h = 0.
self.off_h = ox
self.off_v = oy + box.height
self.hlist_out(box)
def clamp(value):
if value < -1000000000.:
return -1000000000.
if value > 1000000000.:
return 1000000000.
return value
clamp = staticmethod(clamp)
def hlist_out(self, box):
cur_g = 0
cur_glue = 0.
glue_order = box.glue_order
glue_sign = box.glue_sign
base_line = self.cur_v
left_edge = self.cur_h
self.cur_s += 1
self.max_push = max(self.cur_s, self.max_push)
clamp = self.clamp
for p in box.children:
if isinstance(p, Char):
p.render(self.cur_h + self.off_h, self.cur_v + self.off_v)
self.cur_h += p.width
elif isinstance(p, Kern):
self.cur_h += p.width
elif isinstance(p, List):
# node623
if len(p.children) == 0:
self.cur_h += p.width
else:
edge = self.cur_h
self.cur_v = base_line + p.shift_amount
if isinstance(p, Hlist):
self.hlist_out(p)
else:
# p.vpack(box.height + box.depth, 'exactly')
self.vlist_out(p)
self.cur_h = edge + p.width
self.cur_v = base_line
elif isinstance(p, Box):
# node624
rule_height = p.height
rule_depth = p.depth
rule_width = p.width
if np.isinf(rule_height):
rule_height = box.height
if np.isinf(rule_depth):
rule_depth = box.depth
if rule_height > 0 and rule_width > 0:
self.cur_v = base_line + rule_depth
p.render(self.cur_h + self.off_h,
self.cur_v + self.off_v,
rule_width, rule_height)
self.cur_v = base_line
self.cur_h += rule_width
elif isinstance(p, Glue):
# node625
glue_spec = p.glue_spec
rule_width = glue_spec.width - cur_g
if glue_sign != 0: # normal
if glue_sign == 1: # stretching
if glue_spec.stretch_order == glue_order:
cur_glue += glue_spec.stretch
cur_g = round(clamp(box.glue_set * cur_glue))
elif glue_spec.shrink_order == glue_order:
cur_glue += glue_spec.shrink
cur_g = round(clamp(box.glue_set * cur_glue))
rule_width += cur_g
self.cur_h += rule_width
self.cur_s -= 1
def vlist_out(self, box):
cur_g = 0
cur_glue = 0.
glue_order = box.glue_order
glue_sign = box.glue_sign
self.cur_s += 1
self.max_push = max(self.max_push, self.cur_s)
left_edge = self.cur_h
self.cur_v -= box.height
top_edge = self.cur_v
clamp = self.clamp
for p in box.children:
if isinstance(p, Kern):
self.cur_v += p.width
elif isinstance(p, List):
if len(p.children) == 0:
self.cur_v += p.height + p.depth
else:
self.cur_v += p.height
self.cur_h = left_edge + p.shift_amount
save_v = self.cur_v
p.width = box.width
if isinstance(p, Hlist):
self.hlist_out(p)
else:
self.vlist_out(p)
self.cur_v = save_v + p.depth
self.cur_h = left_edge
elif isinstance(p, Box):
rule_height = p.height
rule_depth = p.depth
rule_width = p.width
if np.isinf(rule_width):
rule_width = box.width
rule_height += rule_depth
if rule_height > 0 and rule_depth > 0:
self.cur_v += rule_height
p.render(self.cur_h + self.off_h,
self.cur_v + self.off_v,
rule_width, rule_height)
elif isinstance(p, Glue):
glue_spec = p.glue_spec
rule_height = glue_spec.width - cur_g
if glue_sign != 0: # normal
if glue_sign == 1: # stretching
if glue_spec.stretch_order == glue_order:
cur_glue += glue_spec.stretch
cur_g = round(clamp(box.glue_set * cur_glue))
elif glue_spec.shrink_order == glue_order: # shrinking
cur_glue += glue_spec.shrink
cur_g = round(clamp(box.glue_set * cur_glue))
rule_height += cur_g
self.cur_v += rule_height
elif isinstance(p, Char):
raise RuntimeError(
"Internal mathtext error: Char node found in vlist")
self.cur_s -= 1
ship = Ship()
##############################################################################
# PARSER
def Error(msg):
"""
Helper class to raise parser errors.
"""
def raise_error(s, loc, toks):
raise ParseFatalException(s, loc, msg)
empty = Empty()
empty.setParseAction(raise_error)
return empty
class Parser(object):
"""
This is the pyparsing-based parser for math expressions. It
actually parses full strings *containing* math expressions, in
that raw text may also appear outside of pairs of ``$``.
The grammar is based directly on that in TeX, though it cuts a few
corners.
"""
_math_style_dict = dict(displaystyle=0, textstyle=1,
scriptstyle=2, scriptscriptstyle=3)
_binary_operators = set('''
+ * -
\\pm \\sqcap \\rhd
\\mp \\sqcup \\unlhd
\\times \\vee \\unrhd
\\div \\wedge \\oplus
\\ast \\setminus \\ominus
\\star \\wr \\otimes
\\circ \\diamond \\oslash
\\bullet \\bigtriangleup \\odot
\\cdot \\bigtriangledown \\bigcirc
\\cap \\triangleleft \\dagger
\\cup \\triangleright \\ddagger
\\uplus \\lhd \\amalg'''.split())
_relation_symbols = set('''
= < > :
\\leq \\geq \\equiv \\models
\\prec \\succ \\sim \\perp
\\preceq \\succeq \\simeq \\mid
\\ll \\gg \\asymp \\parallel
\\subset \\supset \\approx \\bowtie
\\subseteq \\supseteq \\cong \\Join
\\sqsubset \\sqsupset \\neq \\smile
\\sqsubseteq \\sqsupseteq \\doteq \\frown
\\in \\ni \\propto \\vdash
\\dashv \\dots \\dotplus \\doteqdot'''.split())
_arrow_symbols = set('''
\\leftarrow \\longleftarrow \\uparrow
\\Leftarrow \\Longleftarrow \\Uparrow
\\rightarrow \\longrightarrow \\downarrow
\\Rightarrow \\Longrightarrow \\Downarrow
\\leftrightarrow \\longleftrightarrow \\updownarrow
\\Leftrightarrow \\Longleftrightarrow \\Updownarrow
\\mapsto \\longmapsto \\nearrow
\\hookleftarrow \\hookrightarrow \\searrow
\\leftharpoonup \\rightharpoonup \\swarrow
\\leftharpoondown \\rightharpoondown \\nwarrow
\\rightleftharpoons \\leadsto'''.split())
_spaced_symbols = _binary_operators | _relation_symbols | _arrow_symbols
_punctuation_symbols = set(r', ; . ! \ldotp \cdotp'.split())
_overunder_symbols = set(r'''
\sum \prod \coprod \bigcap \bigcup \bigsqcup \bigvee
\bigwedge \bigodot \bigotimes \bigoplus \biguplus
'''.split())
_overunder_functions = set(
"lim liminf limsup sup max min".split())
_dropsub_symbols = set(r'''\int \oint'''.split())
_fontnames = set(
"rm cal it tt sf bf default bb frak circled scr regular".split())
_function_names = set("""
arccos csc ker min arcsin deg lg Pr arctan det lim sec arg dim
liminf sin cos exp limsup sinh cosh gcd ln sup cot hom log tan
coth inf max tanh""".split())
_ambi_delim = set("""
| \\| / \\backslash \\uparrow \\downarrow \\updownarrow \\Uparrow
\\Downarrow \\Updownarrow . \\vert \\Vert \\\\|""".split())
_left_delim = set(r"( [ \{ < \lfloor \langle \lceil".split())
_right_delim = set(r") ] \} > \rfloor \rangle \rceil".split())
def __init__(self):
p = types.SimpleNamespace()
# All forward declarations are here
p.accent = Forward()
p.ambi_delim = Forward()
p.apostrophe = Forward()
p.auto_delim = Forward()
p.binom = Forward()
p.bslash = Forward()
p.c_over_c = Forward()
p.customspace = Forward()
p.end_group = Forward()
p.float_literal = Forward()
p.font = Forward()
p.frac = Forward()
p.dfrac = Forward()
p.function = Forward()
p.genfrac = Forward()
p.group = Forward()
p.int_literal = Forward()
p.latexfont = Forward()
p.lbracket = Forward()
p.left_delim = Forward()
p.lbrace = Forward()
p.main = Forward()
p.math = Forward()
p.math_string = Forward()
p.non_math = Forward()
p.operatorname = Forward()
p.overline = Forward()
p.placeable = Forward()
p.rbrace = Forward()
p.rbracket = Forward()
p.required_group = Forward()
p.right_delim = Forward()
p.right_delim_safe = Forward()
p.simple = Forward()
p.simple_group = Forward()
p.single_symbol = Forward()
p.snowflake = Forward()
p.space = Forward()
p.sqrt = Forward()
p.stackrel = Forward()
p.start_group = Forward()
p.subsuper = Forward()
p.subsuperop = Forward()
p.symbol = Forward()
p.symbol_name = Forward()
p.token = Forward()
p.unknown_symbol = Forward()
# Set names on everything -- very useful for debugging
for key, val in vars(p).items():
if not key.startswith('_'):
val.setName(key)
p.float_literal <<= Regex(r"[-+]?([0-9]+\.?[0-9]*|\.[0-9]+)")
p.int_literal <<= Regex("[-+]?[0-9]+")
p.lbrace <<= Literal('{').suppress()
p.rbrace <<= Literal('}').suppress()
p.lbracket <<= Literal('[').suppress()
p.rbracket <<= Literal(']').suppress()
p.bslash <<= Literal('\\')
p.space <<= oneOf(list(self._space_widths))
p.customspace <<= (
Suppress(Literal(r'\hspace'))
- ((p.lbrace + p.float_literal + p.rbrace)
| Error(r"Expected \hspace{n}"))
)
unicode_range = "\U00000080-\U0001ffff"
p.single_symbol <<= Regex(
r"([a-zA-Z0-9 +\-*/<>=:,.;!\?&'@()\[\]|%s])|(\\[%%${}\[\]_|])" %
unicode_range)
p.snowflake <<= Suppress(p.bslash) + oneOf(self._snowflake)
p.symbol_name <<= (
Combine(p.bslash + oneOf(list(tex2uni)))
+ FollowedBy(Regex("[^A-Za-z]").leaveWhitespace() | StringEnd())
)
p.symbol <<= (p.single_symbol | p.symbol_name).leaveWhitespace()
p.apostrophe <<= Regex("'+")
p.c_over_c <<= (
Suppress(p.bslash)
+ oneOf(list(self._char_over_chars))
)
p.accent <<= Group(
Suppress(p.bslash)
+ oneOf([*self._accent_map, *self._wide_accents])
- p.placeable
)
p.function <<= (
Suppress(p.bslash)
+ oneOf(list(self._function_names))
)
p.start_group <<= Optional(p.latexfont) + p.lbrace
p.end_group <<= p.rbrace.copy()
p.simple_group <<= Group(p.lbrace + ZeroOrMore(p.token) + p.rbrace)
p.required_group<<= Group(p.lbrace + OneOrMore(p.token) + p.rbrace)
p.group <<= Group(
p.start_group + ZeroOrMore(p.token) + p.end_group
)
p.font <<= Suppress(p.bslash) + oneOf(list(self._fontnames))
p.latexfont <<= (
Suppress(p.bslash)
+ oneOf(['math' + x for x in self._fontnames])
)
p.frac <<= Group(
Suppress(Literal(r"\frac"))
- ((p.required_group + p.required_group)
| Error(r"Expected \frac{num}{den}"))
)
p.dfrac <<= Group(
Suppress(Literal(r"\dfrac"))
- ((p.required_group + p.required_group)
| Error(r"Expected \dfrac{num}{den}"))
)
p.stackrel <<= Group(
Suppress(Literal(r"\stackrel"))
- ((p.required_group + p.required_group)
| Error(r"Expected \stackrel{num}{den}"))
)
p.binom <<= Group(
Suppress(Literal(r"\binom"))
- ((p.required_group + p.required_group)
| Error(r"Expected \binom{num}{den}"))
)
p.ambi_delim <<= oneOf(list(self._ambi_delim))
p.left_delim <<= oneOf(list(self._left_delim))
p.right_delim <<= oneOf(list(self._right_delim))
p.right_delim_safe <<= oneOf([*(self._right_delim - {'}'}), r'\}'])
p.genfrac <<= Group(
Suppress(Literal(r"\genfrac"))
- (( (p.lbrace
+ Optional(p.ambi_delim | p.left_delim, default='')
+ p.rbrace)
+ (p.lbrace
+ Optional(p.ambi_delim | p.right_delim_safe, default='')
+ p.rbrace)
+ (p.lbrace + p.float_literal + p.rbrace)
+ p.simple_group + p.required_group + p.required_group)
| Error("Expected "
r"\genfrac{ldelim}{rdelim}{rulesize}{style}{num}{den}"))
)
p.sqrt <<= Group(
Suppress(Literal(r"\sqrt"))
- ((Optional(p.lbracket + p.int_literal + p.rbracket, default=None)
+ p.required_group)
| Error("Expected \\sqrt{value}"))
)
p.overline <<= Group(
Suppress(Literal(r"\overline"))
- (p.required_group | Error("Expected \\overline{value}"))
)
p.unknown_symbol<<= Combine(p.bslash + Regex("[A-Za-z]*"))
p.operatorname <<= Group(
Suppress(Literal(r"\operatorname"))
- ((p.lbrace + ZeroOrMore(p.simple | p.unknown_symbol) + p.rbrace)
| Error("Expected \\operatorname{value}"))
)
p.placeable <<= (
p.snowflake # Must be before accent so named symbols that are
# prefixed with an accent name work
| p.accent # Must be before symbol as all accents are symbols
| p.symbol # Must be third to catch all named symbols and single
# chars not in a group
| p.c_over_c
| p.function
| p.group
| p.frac
| p.dfrac
| p.stackrel
| p.binom
| p.genfrac
| p.sqrt
| p.overline
| p.operatorname
)
p.simple <<= (
p.space
| p.customspace
| p.font
| p.subsuper
)
p.subsuperop <<= oneOf(["_", "^"])
p.subsuper <<= Group(
(Optional(p.placeable)
+ OneOrMore(p.subsuperop - p.placeable)
+ Optional(p.apostrophe))
| (p.placeable + Optional(p.apostrophe))
| p.apostrophe
)
p.token <<= (
p.simple
| p.auto_delim
| p.unknown_symbol # Must be last
)
p.auto_delim <<= (
Suppress(Literal(r"\left"))
- ((p.left_delim | p.ambi_delim)
| Error("Expected a delimiter"))
+ Group(ZeroOrMore(p.simple | p.auto_delim))
+ Suppress(Literal(r"\right"))
- ((p.right_delim | p.ambi_delim)
| Error("Expected a delimiter"))
)
p.math <<= OneOrMore(p.token)
p.math_string <<= QuotedString('$', '\\', unquoteResults=False)
p.non_math <<= Regex(r"(?:(?:\\[$])|[^$])*").leaveWhitespace()
p.main <<= (
p.non_math + ZeroOrMore(p.math_string + p.non_math) + StringEnd()
)
# Set actions
for key, val in vars(p).items():
if not key.startswith('_'):
if hasattr(self, key):
val.setParseAction(getattr(self, key))
self._expression = p.main
self._math_expression = p.math
def parse(self, s, fonts_object, fontsize, dpi):
"""
Parse expression *s* using the given *fonts_object* for
output, at the given *fontsize* and *dpi*.
Returns the parse tree of :class:`Node` instances.
"""
self._state_stack = [
self.State(fonts_object, 'default', 'rm', fontsize, dpi)]
self._em_width_cache = {}
try:
result = self._expression.parseString(s)
except ParseBaseException as err:
raise ValueError("\n".join(["",
err.line,
" " * (err.column - 1) + "^",
str(err)]))
self._state_stack = None
self._em_width_cache = {}
self._expression.resetCache()
return result[0]
# The state of the parser is maintained in a stack. Upon
# entering and leaving a group { } or math/non-math, the stack
# is pushed and popped accordingly. The current state always
# exists in the top element of the stack.
class State(object):
"""
Stores the state of the parser.
States are pushed and popped from a stack as necessary, and
the "current" state is always at the top of the stack.
"""
def __init__(self, font_output, font, font_class, fontsize, dpi):
self.font_output = font_output
self._font = font
self.font_class = font_class
self.fontsize = fontsize
self.dpi = dpi
def copy(self):
return Parser.State(
self.font_output,
self.font,
self.font_class,
self.fontsize,
self.dpi)
@property
def font(self):
return self._font
@font.setter
def font(self, name):
if name == "circled":
cbook.warn_deprecated(
"3.1", name="\\mathcircled", obj_type="mathtext command",
alternative="unicode characters (e.g. '\\N{CIRCLED LATIN "
"CAPITAL LETTER A}' or '\\u24b6')")
if name in ('rm', 'it', 'bf'):
self.font_class = name
self._font = name
def get_state(self):
"""
Get the current :class:`State` of the parser.
"""
return self._state_stack[-1]
def pop_state(self):
"""
Pop a :class:`State` off of the stack.
"""
self._state_stack.pop()
def push_state(self):
"""
Push a new :class:`State` onto the stack which is just a copy
of the current state.
"""
self._state_stack.append(self.get_state().copy())
def main(self, s, loc, toks):
return [Hlist(toks)]
def math_string(self, s, loc, toks):
return self._math_expression.parseString(toks[0][1:-1])
def math(self, s, loc, toks):
hlist = Hlist(toks)
self.pop_state()
return [hlist]
def non_math(self, s, loc, toks):
s = toks[0].replace(r'\$', '$')
symbols = [Char(c, self.get_state(), math=False) for c in s]
hlist = Hlist(symbols)
# We're going into math now, so set font to 'it'
self.push_state()
self.get_state().font = rcParams['mathtext.default']
return [hlist]
def _make_space(self, percentage):
# All spaces are relative to em width
state = self.get_state()
key = (state.font, state.fontsize, state.dpi)
width = self._em_width_cache.get(key)
if width is None:
metrics = state.font_output.get_metrics(
state.font, rcParams['mathtext.default'], 'm', state.fontsize,
state.dpi)
width = metrics.advance
self._em_width_cache[key] = width
return Kern(width * percentage)
_space_widths = { r'\,' : 0.16667, # 3/18 em = 3 mu
r'\thinspace' : 0.16667, # 3/18 em = 3 mu
r'\/' : 0.16667, # 3/18 em = 3 mu
r'\>' : 0.22222, # 4/18 em = 4 mu
r'\:' : 0.22222, # 4/18 em = 4 mu
r'\;' : 0.27778, # 5/18 em = 5 mu
r'\ ' : 0.33333, # 6/18 em = 6 mu
r'~' : 0.33333, # 6/18 em = 6 mu, nonbreakable
r'\enspace' : 0.5, # 9/18 em = 9 mu
r'\quad' : 1, # 1 em = 18 mu
r'\qquad' : 2, # 2 em = 36 mu
r'\!' : -0.16667, # -3/18 em = -3 mu
}
def space(self, s, loc, toks):
assert len(toks)==1
num = self._space_widths[toks[0]]
box = self._make_space(num)
return [box]
def customspace(self, s, loc, toks):
return [self._make_space(float(toks[0]))]
def symbol(self, s, loc, toks):
c = toks[0]
try:
char = Char(c, self.get_state())
except ValueError:
raise ParseFatalException(s, loc, "Unknown symbol: %s" % c)
if c in self._spaced_symbols:
# iterate until we find previous character, needed for cases
# such as ${ -2}$, $ -2$, or $ -2$.
prev_char = next((c for c in s[:loc][::-1] if c != ' '), '')
# Binary operators at start of string should not be spaced
if (c in self._binary_operators and
(len(s[:loc].split()) == 0 or prev_char == '{' or
prev_char in self._left_delim)):
return [char]
else:
return [Hlist([self._make_space(0.2),
char,
self._make_space(0.2)],
do_kern = True)]
elif c in self._punctuation_symbols:
# Do not space commas between brackets
if c == ',':
prev_char = next((c for c in s[:loc][::-1] if c != ' '), '')
next_char = next((c for c in s[loc + 1:] if c != ' '), '')
if prev_char == '{' and next_char == '}':
return [char]
# Do not space dots as decimal separators
if c == '.' and s[loc - 1].isdigit() and s[loc + 1].isdigit():
return [char]
else:
return [Hlist([char,
self._make_space(0.2)],
do_kern = True)]
return [char]
snowflake = symbol
def unknown_symbol(self, s, loc, toks):
c = toks[0]
raise ParseFatalException(s, loc, "Unknown symbol: %s" % c)
_char_over_chars = {
# The first 2 entries in the tuple are (font, char, sizescale) for
# the two symbols under and over. The third element is the space
# (in multiples of underline height)
r'AA': (('it', 'A', 1.0), (None, '\\circ', 0.5), 0.0),
}
def c_over_c(self, s, loc, toks):
sym = toks[0]
state = self.get_state()
thickness = state.font_output.get_underline_thickness(
state.font, state.fontsize, state.dpi)
under_desc, over_desc, space = \
self._char_over_chars.get(sym, (None, None, 0.0))
if under_desc is None:
raise ParseFatalException("Error parsing symbol")
over_state = state.copy()
if over_desc[0] is not None:
over_state.font = over_desc[0]
over_state.fontsize *= over_desc[2]
over = Accent(over_desc[1], over_state)
under_state = state.copy()
if under_desc[0] is not None:
under_state.font = under_desc[0]
under_state.fontsize *= under_desc[2]
under = Char(under_desc[1], under_state)
width = max(over.width, under.width)
over_centered = HCentered([over])
over_centered.hpack(width, 'exactly')
under_centered = HCentered([under])
under_centered.hpack(width, 'exactly')
return Vlist([
over_centered,
Vbox(0., thickness * space),
under_centered
])
_accent_map = {
r'hat' : r'\circumflexaccent',
r'breve' : r'\combiningbreve',
r'bar' : r'\combiningoverline',
r'grave' : r'\combininggraveaccent',
r'acute' : r'\combiningacuteaccent',
r'tilde' : r'\combiningtilde',
r'dot' : r'\combiningdotabove',
r'ddot' : r'\combiningdiaeresis',
r'vec' : r'\combiningrightarrowabove',
r'"' : r'\combiningdiaeresis',
r"`" : r'\combininggraveaccent',
r"'" : r'\combiningacuteaccent',
r'~' : r'\combiningtilde',
r'.' : r'\combiningdotabove',
r'^' : r'\circumflexaccent',
r'overrightarrow' : r'\rightarrow',
r'overleftarrow' : r'\leftarrow',
r'mathring' : r'\circ'
}
_wide_accents = set(r"widehat widetilde widebar".split())
# make a lambda and call it to get the namespace right
_snowflake = (lambda am: [p for p in tex2uni if
any(p.startswith(a) and a != p for a in am)]
) (set(_accent_map))
def accent(self, s, loc, toks):
assert len(toks)==1
state = self.get_state()
thickness = state.font_output.get_underline_thickness(
state.font, state.fontsize, state.dpi)
if len(toks[0]) != 2:
raise ParseFatalException("Error parsing accent")
accent, sym = toks[0]
if accent in self._wide_accents:
accent_box = AutoWidthChar(
'\\' + accent, sym.width, state, char_class=Accent)
else:
accent_box = Accent(self._accent_map[accent], state)
if accent == 'mathring':
accent_box.shrink()
accent_box.shrink()
centered = HCentered([Hbox(sym.width / 4.0), accent_box])
centered.hpack(sym.width, 'exactly')
return Vlist([
centered,
Vbox(0., thickness * 2.0),
Hlist([sym])
])
def function(self, s, loc, toks):
self.push_state()
state = self.get_state()
state.font = 'rm'
hlist = Hlist([Char(c, state) for c in toks[0]])
self.pop_state()
hlist.function_name = toks[0]
return hlist
def operatorname(self, s, loc, toks):
self.push_state()
state = self.get_state()
state.font = 'rm'
# Change the font of Chars, but leave Kerns alone
for c in toks[0]:
if isinstance(c, Char):
c.font = 'rm'
c._update_metrics()
self.pop_state()
return Hlist(toks[0])
def start_group(self, s, loc, toks):
self.push_state()
# Deal with LaTeX-style font tokens
if len(toks):
self.get_state().font = toks[0][4:]
return []
def group(self, s, loc, toks):
grp = Hlist(toks[0])
return [grp]
required_group = simple_group = group
def end_group(self, s, loc, toks):
self.pop_state()
return []
def font(self, s, loc, toks):
assert len(toks)==1
name = toks[0]
self.get_state().font = name
return []
def is_overunder(self, nucleus):
if isinstance(nucleus, Char):
return nucleus.c in self._overunder_symbols
elif isinstance(nucleus, Hlist) and hasattr(nucleus, 'function_name'):
return nucleus.function_name in self._overunder_functions
return False
def is_dropsub(self, nucleus):
if isinstance(nucleus, Char):
return nucleus.c in self._dropsub_symbols
return False
def is_slanted(self, nucleus):
if isinstance(nucleus, Char):
return nucleus.is_slanted()
return False
def is_between_brackets(self, s, loc):
return False
def subsuper(self, s, loc, toks):
assert len(toks)==1
nucleus = None
sub = None
super = None
# Pick all of the apostrophes out, including first apostrophes that
# have been parsed as characters
napostrophes = 0
new_toks = []
for tok in toks[0]:
if isinstance(tok, str) and tok not in ('^', '_'):
napostrophes += len(tok)
elif isinstance(tok, Char) and tok.c == "'":
napostrophes += 1
else:
new_toks.append(tok)
toks = new_toks
if len(toks) == 0:
assert napostrophes
nucleus = Hbox(0.0)
elif len(toks) == 1:
if not napostrophes:
return toks[0] # .asList()
else:
nucleus = toks[0]
elif len(toks) in (2, 3):
# single subscript or superscript
nucleus = toks[0] if len(toks) == 3 else Hbox(0.0)
op, next = toks[-2:]
if op == '_':
sub = next
else:
super = next
elif len(toks) in (4, 5):
# subscript and superscript
nucleus = toks[0] if len(toks) == 5 else Hbox(0.0)
op1, next1, op2, next2 = toks[-4:]
if op1 == op2:
if op1 == '_':
raise ParseFatalException("Double subscript")
else:
raise ParseFatalException("Double superscript")
if op1 == '_':
sub = next1
super = next2
else:
super = next1
sub = next2
else:
raise ParseFatalException(
"Subscript/superscript sequence is too long. "
"Use braces { } to remove ambiguity.")
state = self.get_state()
rule_thickness = state.font_output.get_underline_thickness(
state.font, state.fontsize, state.dpi)
xHeight = state.font_output.get_xheight(
state.font, state.fontsize, state.dpi)
if napostrophes:
if super is None:
super = Hlist([])
for i in range(napostrophes):
super.children.extend(self.symbol(s, loc, ['\\prime']))
# kern() and hpack() needed to get the metrics right after
# extending
super.kern()
super.hpack()
# Handle over/under symbols, such as sum or integral
if self.is_overunder(nucleus):
vlist = []
shift = 0.
width = nucleus.width
if super is not None:
super.shrink()
width = max(width, super.width)
if sub is not None:
sub.shrink()
width = max(width, sub.width)
if super is not None:
hlist = HCentered([super])
hlist.hpack(width, 'exactly')
vlist.extend([hlist, Kern(rule_thickness * 3.0)])
hlist = HCentered([nucleus])
hlist.hpack(width, 'exactly')
vlist.append(hlist)
if sub is not None:
hlist = HCentered([sub])
hlist.hpack(width, 'exactly')
vlist.extend([Kern(rule_thickness * 3.0), hlist])
shift = hlist.height
vlist = Vlist(vlist)
vlist.shift_amount = shift + nucleus.depth
result = Hlist([vlist])
return [result]
# We remove kerning on the last character for consistency (otherwise
# it will compute kerning based on non-shrunk characters and may put
# them too close together when superscripted)
# We change the width of the last character to match the advance to
# consider some fonts with weird metrics: e.g. stix's f has a width of
# 7.75 and a kerning of -4.0 for an advance of 3.72, and we want to put
# the superscript at the advance
last_char = nucleus
if isinstance(nucleus, Hlist):
new_children = nucleus.children
if len(new_children):
# remove last kern
if (isinstance(new_children[-1], Kern) and
hasattr(new_children[-2], '_metrics')):
new_children = new_children[:-1]
last_char = new_children[-1]
if hasattr(last_char, '_metrics'):
last_char.width = last_char._metrics.advance
# create new Hlist without kerning
nucleus = Hlist(new_children, do_kern=False)
else:
if isinstance(nucleus, Char):
last_char.width = last_char._metrics.advance
nucleus = Hlist([nucleus])
# Handle regular sub/superscripts
constants = _get_font_constant_set(state)
lc_height = last_char.height
lc_baseline = 0
if self.is_dropsub(last_char):
lc_baseline = last_char.depth
# Compute kerning for sub and super
superkern = constants.delta * xHeight
subkern = constants.delta * xHeight
if self.is_slanted(last_char):
superkern += constants.delta * xHeight
superkern += (constants.delta_slanted *
(lc_height - xHeight * 2. / 3.))
if self.is_dropsub(last_char):
subkern = (3 * constants.delta -
constants.delta_integral) * lc_height
superkern = (3 * constants.delta +
constants.delta_integral) * lc_height
else:
subkern = 0
if super is None:
# node757
x = Hlist([Kern(subkern), sub])
x.shrink()
if self.is_dropsub(last_char):
shift_down = lc_baseline + constants.subdrop * xHeight
else:
shift_down = constants.sub1 * xHeight
x.shift_amount = shift_down
else:
x = Hlist([Kern(superkern), super])
x.shrink()
if self.is_dropsub(last_char):
shift_up = lc_height - constants.subdrop * xHeight
else:
shift_up = constants.sup1 * xHeight
if sub is None:
x.shift_amount = -shift_up
else: # Both sub and superscript
y = Hlist([Kern(subkern), sub])
y.shrink()
if self.is_dropsub(last_char):
shift_down = lc_baseline + constants.subdrop * xHeight
else:
shift_down = constants.sub2 * xHeight
# If sub and superscript collide, move super up
clr = (2.0 * rule_thickness -
((shift_up - x.depth) - (y.height - shift_down)))
if clr > 0.:
shift_up += clr
x = Vlist([
x,
Kern((shift_up - x.depth) - (y.height - shift_down)),
y])
x.shift_amount = shift_down
if not self.is_dropsub(last_char):
x.width += constants.script_space * xHeight
result = Hlist([nucleus, x])
return [result]
def _genfrac(self, ldelim, rdelim, rule, style, num, den):
state = self.get_state()
thickness = state.font_output.get_underline_thickness(
state.font, state.fontsize, state.dpi)
rule = float(rule)
# If style != displaystyle == 0, shrink the num and den
if style != self._math_style_dict['displaystyle']:
num.shrink()
den.shrink()
cnum = HCentered([num])
cden = HCentered([den])
width = max(num.width, den.width)
cnum.hpack(width, 'exactly')
cden.hpack(width, 'exactly')
vlist = Vlist([cnum, # numerator
Vbox(0, thickness * 2.0), # space
Hrule(state, rule), # rule
Vbox(0, thickness * 2.0), # space
cden # denominator
])
# Shift so the fraction line sits in the middle of the
# equals sign
metrics = state.font_output.get_metrics(
state.font, rcParams['mathtext.default'],
'=', state.fontsize, state.dpi)
shift = (cden.height -
((metrics.ymax + metrics.ymin) / 2 -
thickness * 3.0))
vlist.shift_amount = shift
result = [Hlist([vlist, Hbox(thickness * 2.)])]
if ldelim or rdelim:
if ldelim == '':
ldelim = '.'
if rdelim == '':
rdelim = '.'
return self._auto_sized_delimiter(ldelim, result, rdelim)
return result
def genfrac(self, s, loc, toks):
assert len(toks) == 1
assert len(toks[0]) == 6
return self._genfrac(*tuple(toks[0]))
def frac(self, s, loc, toks):
assert len(toks) == 1
assert len(toks[0]) == 2
state = self.get_state()
thickness = state.font_output.get_underline_thickness(
state.font, state.fontsize, state.dpi)
num, den = toks[0]
return self._genfrac('', '', thickness,
self._math_style_dict['textstyle'], num, den)
def dfrac(self, s, loc, toks):
assert len(toks) == 1
assert len(toks[0]) == 2
state = self.get_state()
thickness = state.font_output.get_underline_thickness(
state.font, state.fontsize, state.dpi)
num, den = toks[0]
return self._genfrac('', '', thickness,
self._math_style_dict['displaystyle'], num, den)
@cbook.deprecated("3.1", obj_type="mathtext command",
alternative=r"\genfrac")
def stackrel(self, s, loc, toks):
assert len(toks) == 1
assert len(toks[0]) == 2
num, den = toks[0]
return self._genfrac('', '', 0.0,
self._math_style_dict['textstyle'], num, den)
def binom(self, s, loc, toks):
assert len(toks) == 1
assert len(toks[0]) == 2
num, den = toks[0]
return self._genfrac('(', ')', 0.0,
self._math_style_dict['textstyle'], num, den)
def sqrt(self, s, loc, toks):
root, body = toks[0]
state = self.get_state()
thickness = state.font_output.get_underline_thickness(
state.font, state.fontsize, state.dpi)
# Determine the height of the body, and add a little extra to
# the height so it doesn't seem cramped
height = body.height - body.shift_amount + thickness * 5.0
depth = body.depth + body.shift_amount
check = AutoHeightChar(r'\__sqrt__', height, depth, state, always=True)
height = check.height - check.shift_amount
depth = check.depth + check.shift_amount
# Put a little extra space to the left and right of the body
padded_body = Hlist([Hbox(thickness * 2.0),
body,
Hbox(thickness * 2.0)])
rightside = Vlist([Hrule(state),
Fill(),
padded_body])
# Stretch the glue between the hrule and the body
rightside.vpack(height + (state.fontsize * state.dpi) / (100.0 * 12.0),
'exactly', depth)
# Add the root and shift it upward so it is above the tick.
# The value of 0.6 is a hard-coded hack ;)
if root is None:
root = Box(check.width * 0.5, 0., 0.)
else:
root = Hlist([Char(x, state) for x in root])
root.shrink()
root.shrink()
root_vlist = Vlist([Hlist([root])])
root_vlist.shift_amount = -height * 0.6
hlist = Hlist([root_vlist, # Root
# Negative kerning to put root over tick
Kern(-check.width * 0.5),
check, # Check
rightside]) # Body
return [hlist]
def overline(self, s, loc, toks):
assert len(toks)==1
assert len(toks[0])==1
body = toks[0][0]
state = self.get_state()
thickness = state.font_output.get_underline_thickness(
state.font, state.fontsize, state.dpi)
height = body.height - body.shift_amount + thickness * 3.0
depth = body.depth + body.shift_amount
# Place overline above body
rightside = Vlist([Hrule(state),
Fill(),
Hlist([body])])
# Stretch the glue between the hrule and the body
rightside.vpack(height + (state.fontsize * state.dpi) / (100.0 * 12.0),
'exactly', depth)
hlist = Hlist([rightside])
return [hlist]
def _auto_sized_delimiter(self, front, middle, back):
state = self.get_state()
if len(middle):
height = max(x.height for x in middle)
depth = max(x.depth for x in middle)
factor = None
else:
height = 0
depth = 0
factor = 1.0
parts = []
# \left. and \right. aren't supposed to produce any symbols
if front != '.':
parts.append(
AutoHeightChar(front, height, depth, state, factor=factor))
parts.extend(middle)
if back != '.':
parts.append(
AutoHeightChar(back, height, depth, state, factor=factor))
hlist = Hlist(parts)
return hlist
def auto_delim(self, s, loc, toks):
front, middle, back = toks
return self._auto_sized_delimiter(front, middle.asList(), back)
##############################################################################
# MAIN
class MathTextParser(object):
_parser = None
_backend_mapping = {
'bitmap': MathtextBackendBitmap,
'agg' : MathtextBackendAgg,
'ps' : MathtextBackendPs,
'pdf' : MathtextBackendPdf,
'svg' : MathtextBackendSvg,
'path' : MathtextBackendPath,
'cairo' : MathtextBackendCairo,
'macosx': MathtextBackendAgg,
}
_font_type_mapping = {
'cm' : BakomaFonts,
'dejavuserif' : DejaVuSerifFonts,
'dejavusans' : DejaVuSansFonts,
'stix' : StixFonts,
'stixsans' : StixSansFonts,
'custom' : UnicodeFonts
}
def __init__(self, output):
"""
Create a MathTextParser for the given backend *output*.
"""
self._output = output.lower()
@functools.lru_cache(50)
def parse(self, s, dpi = 72, prop = None):
"""
Parse the given math expression *s* at the given *dpi*. If
*prop* is provided, it is a
:class:`~matplotlib.font_manager.FontProperties` object
specifying the "default" font to use in the math expression,
used for all non-math text.
The results are cached, so multiple calls to :meth:`parse`
with the same expression should be fast.
"""
if prop is None:
prop = FontProperties()
if self._output == 'ps' and rcParams['ps.useafm']:
font_output = StandardPsFonts(prop)
else:
backend = self._backend_mapping[self._output]()
fontset = rcParams['mathtext.fontset'].lower()
cbook._check_in_list(self._font_type_mapping, fontset=fontset)
fontset_class = self._font_type_mapping[fontset]
font_output = fontset_class(prop, backend)
fontsize = prop.get_size_in_points()
# This is a class variable so we don't rebuild the parser
# with each request.
if self._parser is None:
self.__class__._parser = Parser()
box = self._parser.parse(s, font_output, fontsize, dpi)
font_output.set_canvas_size(box.width, box.height, box.depth)
return font_output.get_results(box)
def to_mask(self, texstr, dpi=120, fontsize=14):
r"""
Parameters
----------
texstr : str
A valid mathtext string, e.g., r'IQ: $\sigma_i=15$'.
dpi : float
The dots-per-inch setting used to render the text.
fontsize : int
The font size in points
Returns
-------
array : 2D uint8 alpha
Mask array of rasterized tex.
depth : int
Offset of the baseline from the bottom of the image, in pixels.
"""
assert self._output == "bitmap"
prop = FontProperties(size=fontsize)
ftimage, depth = self.parse(texstr, dpi=dpi, prop=prop)
x = ftimage.as_array()
return x, depth
def to_rgba(self, texstr, color='black', dpi=120, fontsize=14):
r"""
Parameters
----------
texstr : str
A valid mathtext string, e.g., r'IQ: $\sigma_i=15$'.
color : color
The text color.
dpi : float
The dots-per-inch setting used to render the text.
fontsize : int
The font size in points.
Returns
-------
array : (M, N, 4) array
RGBA color values of rasterized tex, colorized with *color*.
depth : int
Offset of the baseline from the bottom of the image, in pixels.
"""
x, depth = self.to_mask(texstr, dpi=dpi, fontsize=fontsize)
r, g, b, a = mcolors.to_rgba(color)
RGBA = np.zeros((x.shape[0], x.shape[1], 4), dtype=np.uint8)
RGBA[:, :, 0] = 255 * r
RGBA[:, :, 1] = 255 * g
RGBA[:, :, 2] = 255 * b
RGBA[:, :, 3] = x
return RGBA, depth
def to_png(self, filename, texstr, color='black', dpi=120, fontsize=14):
r"""
Render a tex expression to a PNG file.
Parameters
----------
filename
A writable filename or fileobject.
texstr : str
A valid mathtext string, e.g., r'IQ: $\sigma_i=15$'.
color : color
The text color.
dpi : float
The dots-per-inch setting used to render the text.
fontsize : int
The font size in points.
Returns
-------
depth : int
Offset of the baseline from the bottom of the image, in pixels.
"""
from matplotlib import _png
rgba, depth = self.to_rgba(
texstr, color=color, dpi=dpi, fontsize=fontsize)
_png.write_png(rgba, filename)
return depth
def get_depth(self, texstr, dpi=120, fontsize=14):
r"""
Parameters
----------
texstr : str
A valid mathtext string, e.g., r'IQ: $\sigma_i=15$'.
dpi : float
The dots-per-inch setting used to render the text.
Returns
-------
depth : int
Offset of the baseline from the bottom of the image, in pixels.
"""
assert self._output=="bitmap"
prop = FontProperties(size=fontsize)
ftimage, depth = self.parse(texstr, dpi=dpi, prop=prop)
return depth
def math_to_image(s, filename_or_obj, prop=None, dpi=None, format=None):
"""
Given a math expression, renders it in a closely-clipped bounding
box to an image file.
*s*
A math expression. The math portion should be enclosed in
dollar signs.
*filename_or_obj*
A filepath or writable file-like object to write the image data
to.
*prop*
If provided, a FontProperties() object describing the size and
style of the text.
*dpi*
Override the output dpi, otherwise use the default associated
with the output format.
*format*
The output format, e.g., 'svg', 'pdf', 'ps' or 'png'. If not
provided, will be deduced from the filename.
"""
from matplotlib import figure
# backend_agg supports all of the core output formats
from matplotlib.backends import backend_agg
if prop is None:
prop = FontProperties()
parser = MathTextParser('path')
width, height, depth, _, _ = parser.parse(s, dpi=72, prop=prop)
fig = figure.Figure(figsize=(width / 72.0, height / 72.0))
fig.text(0, depth/height, s, fontproperties=prop)
backend_agg.FigureCanvasAgg(fig)
fig.savefig(filename_or_obj, dpi=dpi, format=format)
return depth
|
c38b82e5f241e83edbbe9bcfdcb8747f11071b32fbc8b7c950e38260a0059edb
|
try:
__import__('pkg_resources').declare_namespace(__name__)
except ImportError:
pass # must not have setuptools
|
559ed87853254eb06ce7ff31d1e932119fbef16695988524e8e83a1daf09f21f
|
from .. import axes, cbook
from .geo import AitoffAxes, HammerAxes, LambertAxes, MollweideAxes
from .polar import PolarAxes
from mpl_toolkits.mplot3d import Axes3D
class ProjectionRegistry:
"""
Manages the set of projections available to the system.
"""
def __init__(self):
self._all_projection_types = {}
def register(self, *projections):
"""
Register a new set of projections.
"""
for projection in projections:
name = projection.name
self._all_projection_types[name] = projection
def get_projection_class(self, name):
"""
Get a projection class from its *name*.
"""
return self._all_projection_types[name]
def get_projection_names(self):
"""
Get a list of the names of all projections currently registered.
"""
return sorted(self._all_projection_types)
projection_registry = ProjectionRegistry()
projection_registry.register(
axes.Axes,
PolarAxes,
AitoffAxes,
HammerAxes,
LambertAxes,
MollweideAxes,
Axes3D,
)
def register_projection(cls):
projection_registry.register(cls)
def get_projection_class(projection=None):
"""
Get a projection class from its name.
If *projection* is None, a standard rectilinear projection is returned.
"""
if projection is None:
projection = 'rectilinear'
try:
return projection_registry.get_projection_class(projection)
except KeyError:
raise ValueError("Unknown projection %r" % projection)
@cbook.deprecated("3.1")
def process_projection_requirements(figure, *args, **kwargs):
return figure._process_projection_requirements(*args, **kwargs)
def get_projection_names():
"""
Get a list of acceptable projection names.
"""
return projection_registry.get_projection_names()
|
44dd23e8b3c57d119f246b44b0721f8ea56574bb1d1a90c0c415deab33adcc06
|
from collections import OrderedDict
import types
import numpy as np
from matplotlib import cbook, rcParams
from matplotlib.axes import Axes
import matplotlib.axis as maxis
import matplotlib.markers as mmarkers
import matplotlib.patches as mpatches
import matplotlib.path as mpath
import matplotlib.ticker as mticker
import matplotlib.transforms as mtransforms
import matplotlib.spines as mspines
class PolarTransform(mtransforms.Transform):
"""
The base polar transform. This handles projection *theta* and
*r* into Cartesian coordinate space *x* and *y*, but does not
perform the ultimate affine transformation into the correct
position.
"""
input_dims = 2
output_dims = 2
is_separable = False
def __init__(self, axis=None, use_rmin=True,
_apply_theta_transforms=True):
mtransforms.Transform.__init__(self)
self._axis = axis
self._use_rmin = use_rmin
self._apply_theta_transforms = _apply_theta_transforms
def __str__(self):
return ("{}(\n"
"{},\n"
" use_rmin={},\n"
" _apply_theta_transforms={})"
.format(type(self).__name__,
mtransforms._indent_str(self._axis),
self._use_rmin,
self._apply_theta_transforms))
def transform_non_affine(self, tr):
# docstring inherited
t, r = np.transpose(tr)
# PolarAxes does not use the theta transforms here, but apply them for
# backwards-compatibility if not being used by it.
if self._apply_theta_transforms and self._axis is not None:
t *= self._axis.get_theta_direction()
t += self._axis.get_theta_offset()
if self._use_rmin and self._axis is not None:
r = (r - self._axis.get_rorigin()) * self._axis.get_rsign()
r = np.where(r >= 0, r, np.nan)
return np.column_stack([r * np.cos(t), r * np.sin(t)])
def transform_path_non_affine(self, path):
# docstring inherited
vertices = path.vertices
if len(vertices) == 2 and vertices[0, 0] == vertices[1, 0]:
return mpath.Path(self.transform(vertices), path.codes)
ipath = path.interpolated(path._interpolation_steps)
return mpath.Path(self.transform(ipath.vertices), ipath.codes)
def inverted(self):
# docstring inherited
return PolarAxes.InvertedPolarTransform(self._axis, self._use_rmin,
self._apply_theta_transforms)
class PolarAffine(mtransforms.Affine2DBase):
"""
The affine part of the polar projection. Scales the output so
that maximum radius rests on the edge of the axes circle.
"""
def __init__(self, scale_transform, limits):
"""
*limits* is the view limit of the data. The only part of
its bounds that is used is the y limits (for the radius limits).
The theta range is handled by the non-affine transform.
"""
mtransforms.Affine2DBase.__init__(self)
self._scale_transform = scale_transform
self._limits = limits
self.set_children(scale_transform, limits)
self._mtx = None
def __str__(self):
return ("{}(\n"
"{},\n"
"{})"
.format(type(self).__name__,
mtransforms._indent_str(self._scale_transform),
mtransforms._indent_str(self._limits)))
def get_matrix(self):
# docstring inherited
if self._invalid:
limits_scaled = self._limits.transformed(self._scale_transform)
yscale = limits_scaled.ymax - limits_scaled.ymin
affine = mtransforms.Affine2D() \
.scale(0.5 / yscale) \
.translate(0.5, 0.5)
self._mtx = affine.get_matrix()
self._inverted = None
self._invalid = 0
return self._mtx
class InvertedPolarTransform(mtransforms.Transform):
"""
The inverse of the polar transform, mapping Cartesian
coordinate space *x* and *y* back to *theta* and *r*.
"""
input_dims = 2
output_dims = 2
is_separable = False
def __init__(self, axis=None, use_rmin=True,
_apply_theta_transforms=True):
mtransforms.Transform.__init__(self)
self._axis = axis
self._use_rmin = use_rmin
self._apply_theta_transforms = _apply_theta_transforms
def __str__(self):
return ("{}(\n"
"{},\n"
" use_rmin={},\n"
" _apply_theta_transforms={})"
.format(type(self).__name__,
mtransforms._indent_str(self._axis),
self._use_rmin,
self._apply_theta_transforms))
def transform_non_affine(self, xy):
# docstring inherited
x = xy[:, 0:1]
y = xy[:, 1:]
r = np.hypot(x, y)
theta = (np.arctan2(y, x) + 2 * np.pi) % (2 * np.pi)
# PolarAxes does not use the theta transforms here, but apply them for
# backwards-compatibility if not being used by it.
if self._apply_theta_transforms and self._axis is not None:
theta -= self._axis.get_theta_offset()
theta *= self._axis.get_theta_direction()
theta %= 2 * np.pi
if self._use_rmin and self._axis is not None:
r += self._axis.get_rorigin()
r *= self._axis.get_rsign()
return np.concatenate((theta, r), 1)
def inverted(self):
# docstring inherited
return PolarAxes.PolarTransform(self._axis, self._use_rmin,
self._apply_theta_transforms)
class ThetaFormatter(mticker.Formatter):
"""
Used to format the *theta* tick labels. Converts the native
unit of radians into degrees and adds a degree symbol.
"""
def __call__(self, x, pos=None):
vmin, vmax = self.axis.get_view_interval()
d = np.rad2deg(abs(vmax - vmin))
digits = max(-int(np.log10(d) - 1.5), 0)
if rcParams['text.usetex'] and not rcParams['text.latex.unicode']:
format_str = r"${value:0.{digits:d}f}^\circ$"
return format_str.format(value=np.rad2deg(x), digits=digits)
else:
# we use unicode, rather than mathtext with \circ, so
# that it will work correctly with any arbitrary font
# (assuming it has a degree sign), whereas $5\circ$
# will only work correctly with one of the supported
# math fonts (Computer Modern and STIX)
format_str = "{value:0.{digits:d}f}\N{DEGREE SIGN}"
return format_str.format(value=np.rad2deg(x), digits=digits)
class _AxisWrapper(object):
def __init__(self, axis):
self._axis = axis
def get_view_interval(self):
return np.rad2deg(self._axis.get_view_interval())
def set_view_interval(self, vmin, vmax):
self._axis.set_view_interval(*np.deg2rad((vmin, vmax)))
def get_minpos(self):
return np.rad2deg(self._axis.get_minpos())
def get_data_interval(self):
return np.rad2deg(self._axis.get_data_interval())
def set_data_interval(self, vmin, vmax):
self._axis.set_data_interval(*np.deg2rad((vmin, vmax)))
def get_tick_space(self):
return self._axis.get_tick_space()
class ThetaLocator(mticker.Locator):
"""
Used to locate theta ticks.
This will work the same as the base locator except in the case that the
view spans the entire circle. In such cases, the previously used default
locations of every 45 degrees are returned.
"""
def __init__(self, base):
self.base = base
self.axis = self.base.axis = _AxisWrapper(self.base.axis)
def set_axis(self, axis):
self.axis = _AxisWrapper(axis)
self.base.set_axis(self.axis)
def __call__(self):
lim = self.axis.get_view_interval()
if _is_full_circle_deg(lim[0], lim[1]):
return np.arange(8) * 2 * np.pi / 8
else:
return np.deg2rad(self.base())
def autoscale(self):
return self.base.autoscale()
def pan(self, numsteps):
return self.base.pan(numsteps)
def refresh(self):
return self.base.refresh()
def view_limits(self, vmin, vmax):
vmin, vmax = np.rad2deg((vmin, vmax))
return np.deg2rad(self.base.view_limits(vmin, vmax))
def zoom(self, direction):
return self.base.zoom(direction)
class ThetaTick(maxis.XTick):
"""
A theta-axis tick.
This subclass of `XTick` provides angular ticks with some small
modification to their re-positioning such that ticks are rotated based on
tick location. This results in ticks that are correctly perpendicular to
the arc spine.
When 'auto' rotation is enabled, labels are also rotated to be parallel to
the spine. The label padding is also applied here since it's not possible
to use a generic axes transform to produce tick-specific padding.
"""
def __init__(self, axes, *args, **kwargs):
self._text1_translate = mtransforms.ScaledTranslation(
0, 0,
axes.figure.dpi_scale_trans)
self._text2_translate = mtransforms.ScaledTranslation(
0, 0,
axes.figure.dpi_scale_trans)
super().__init__(axes, *args, **kwargs)
def _get_text1(self):
t = super()._get_text1()
t.set_rotation_mode('anchor')
t.set_transform(t.get_transform() + self._text1_translate)
return t
def _get_text2(self):
t = super()._get_text2()
t.set_rotation_mode('anchor')
t.set_transform(t.get_transform() + self._text2_translate)
return t
def _apply_params(self, **kw):
super()._apply_params(**kw)
# Ensure transform is correct; sometimes this gets reset.
trans = self.label1.get_transform()
if not trans.contains_branch(self._text1_translate):
self.label1.set_transform(trans + self._text1_translate)
trans = self.label2.get_transform()
if not trans.contains_branch(self._text2_translate):
self.label2.set_transform(trans + self._text2_translate)
def _update_padding(self, pad, angle):
padx = pad * np.cos(angle) / 72
pady = pad * np.sin(angle) / 72
self._text1_translate._t = (padx, pady)
self._text1_translate.invalidate()
self._text2_translate._t = (-padx, -pady)
self._text2_translate.invalidate()
def update_position(self, loc):
super().update_position(loc)
axes = self.axes
angle = loc * axes.get_theta_direction() + axes.get_theta_offset()
text_angle = np.rad2deg(angle) % 360 - 90
angle -= np.pi / 2
marker = self.tick1line.get_marker()
if marker in (mmarkers.TICKUP, '|'):
trans = mtransforms.Affine2D().scale(1, 1).rotate(angle)
elif marker == mmarkers.TICKDOWN:
trans = mtransforms.Affine2D().scale(1, -1).rotate(angle)
else:
# Don't modify custom tick line markers.
trans = self.tick1line._marker._transform
self.tick1line._marker._transform = trans
marker = self.tick2line.get_marker()
if marker in (mmarkers.TICKUP, '|'):
trans = mtransforms.Affine2D().scale(1, 1).rotate(angle)
elif marker == mmarkers.TICKDOWN:
trans = mtransforms.Affine2D().scale(1, -1).rotate(angle)
else:
# Don't modify custom tick line markers.
trans = self.tick2line._marker._transform
self.tick2line._marker._transform = trans
mode, user_angle = self._labelrotation
if mode == 'default':
text_angle = user_angle
else:
if text_angle > 90:
text_angle -= 180
elif text_angle < -90:
text_angle += 180
text_angle += user_angle
self.label1.set_rotation(text_angle)
self.label2.set_rotation(text_angle)
# This extra padding helps preserve the look from previous releases but
# is also needed because labels are anchored to their center.
pad = self._pad + 7
self._update_padding(pad,
self._loc * axes.get_theta_direction() +
axes.get_theta_offset())
class ThetaAxis(maxis.XAxis):
"""
A theta Axis.
This overrides certain properties of an `XAxis` to provide special-casing
for an angular axis.
"""
__name__ = 'thetaaxis'
axis_name = 'theta'
def _get_tick(self, major):
if major:
tick_kw = self._major_tick_kw
else:
tick_kw = self._minor_tick_kw
return ThetaTick(self.axes, 0, '', major=major, **tick_kw)
def _wrap_locator_formatter(self):
self.set_major_locator(ThetaLocator(self.get_major_locator()))
self.set_major_formatter(ThetaFormatter())
self.isDefault_majloc = True
self.isDefault_majfmt = True
def cla(self):
super().cla()
self.set_ticks_position('none')
self._wrap_locator_formatter()
def _set_scale(self, value, **kwargs):
super()._set_scale(value, **kwargs)
self._wrap_locator_formatter()
def _copy_tick_props(self, src, dest):
'Copy the props from src tick to dest tick'
if src is None or dest is None:
return
super()._copy_tick_props(src, dest)
# Ensure that tick transforms are independent so that padding works.
trans = dest._get_text1_transform()[0]
dest.label1.set_transform(trans + dest._text1_translate)
trans = dest._get_text2_transform()[0]
dest.label2.set_transform(trans + dest._text2_translate)
class RadialLocator(mticker.Locator):
"""
Used to locate radius ticks.
Ensures that all ticks are strictly positive. For all other
tasks, it delegates to the base
:class:`~matplotlib.ticker.Locator` (which may be different
depending on the scale of the *r*-axis.
"""
def __init__(self, base, axes=None):
self.base = base
self._axes = axes
def __call__(self):
show_all = True
# Ensure previous behaviour with full circle non-annular views.
if self._axes:
if _is_full_circle_rad(*self._axes.viewLim.intervalx):
rorigin = self._axes.get_rorigin() * self._axes.get_rsign()
if self._axes.get_rmin() <= rorigin:
show_all = False
if show_all:
return self.base()
else:
return [tick for tick in self.base() if tick > rorigin]
def autoscale(self):
return self.base.autoscale()
def pan(self, numsteps):
return self.base.pan(numsteps)
def zoom(self, direction):
return self.base.zoom(direction)
def refresh(self):
return self.base.refresh()
def view_limits(self, vmin, vmax):
vmin, vmax = self.base.view_limits(vmin, vmax)
if vmax > vmin:
# this allows inverted r/y-lims
vmin = min(0, vmin)
return mtransforms.nonsingular(vmin, vmax)
class _ThetaShift(mtransforms.ScaledTranslation):
"""
Apply a padding shift based on axes theta limits.
This is used to create padding for radial ticks.
Parameters
----------
axes : matplotlib.axes.Axes
The owning axes; used to determine limits.
pad : float
The padding to apply, in points.
start : str, {'min', 'max', 'rlabel'}
Whether to shift away from the start (``'min'``) or the end (``'max'``)
of the axes, or using the rlabel position (``'rlabel'``).
"""
def __init__(self, axes, pad, mode):
mtransforms.ScaledTranslation.__init__(self, pad, pad,
axes.figure.dpi_scale_trans)
self.set_children(axes._realViewLim)
self.axes = axes
self.mode = mode
self.pad = pad
def __str__(self):
return ("{}(\n"
"{},\n"
"{},\n"
"{})"
.format(type(self).__name__,
mtransforms._indent_str(self.axes),
mtransforms._indent_str(self.pad),
mtransforms._indent_str(repr(self.mode))))
def get_matrix(self):
if self._invalid:
if self.mode == 'rlabel':
angle = (
np.deg2rad(self.axes.get_rlabel_position()) *
self.axes.get_theta_direction() +
self.axes.get_theta_offset()
)
else:
if self.mode == 'min':
angle = self.axes._realViewLim.xmin
elif self.mode == 'max':
angle = self.axes._realViewLim.xmax
if self.mode in ('rlabel', 'min'):
padx = np.cos(angle - np.pi / 2)
pady = np.sin(angle - np.pi / 2)
else:
padx = np.cos(angle + np.pi / 2)
pady = np.sin(angle + np.pi / 2)
self._t = (self.pad * padx / 72, self.pad * pady / 72)
return mtransforms.ScaledTranslation.get_matrix(self)
class RadialTick(maxis.YTick):
"""
A radial-axis tick.
This subclass of `YTick` provides radial ticks with some small modification
to their re-positioning such that ticks are rotated based on axes limits.
This results in ticks that are correctly perpendicular to the spine. Labels
are also rotated to be perpendicular to the spine, when 'auto' rotation is
enabled.
"""
def _get_text1(self):
t = super()._get_text1()
t.set_rotation_mode('anchor')
return t
def _get_text2(self):
t = super()._get_text2()
t.set_rotation_mode('anchor')
return t
def _determine_anchor(self, mode, angle, start):
# Note: angle is the (spine angle - 90) because it's used for the tick
# & text setup, so all numbers below are -90 from (normed) spine angle.
if mode == 'auto':
if start:
if -90 <= angle <= 90:
return 'left', 'center'
else:
return 'right', 'center'
else:
if -90 <= angle <= 90:
return 'right', 'center'
else:
return 'left', 'center'
else:
if start:
if angle < -68.5:
return 'center', 'top'
elif angle < -23.5:
return 'left', 'top'
elif angle < 22.5:
return 'left', 'center'
elif angle < 67.5:
return 'left', 'bottom'
elif angle < 112.5:
return 'center', 'bottom'
elif angle < 157.5:
return 'right', 'bottom'
elif angle < 202.5:
return 'right', 'center'
elif angle < 247.5:
return 'right', 'top'
else:
return 'center', 'top'
else:
if angle < -68.5:
return 'center', 'bottom'
elif angle < -23.5:
return 'right', 'bottom'
elif angle < 22.5:
return 'right', 'center'
elif angle < 67.5:
return 'right', 'top'
elif angle < 112.5:
return 'center', 'top'
elif angle < 157.5:
return 'left', 'top'
elif angle < 202.5:
return 'left', 'center'
elif angle < 247.5:
return 'left', 'bottom'
else:
return 'center', 'bottom'
def update_position(self, loc):
super().update_position(loc)
axes = self.axes
thetamin = axes.get_thetamin()
thetamax = axes.get_thetamax()
direction = axes.get_theta_direction()
offset_rad = axes.get_theta_offset()
offset = np.rad2deg(offset_rad)
full = _is_full_circle_deg(thetamin, thetamax)
if full:
angle = (axes.get_rlabel_position() * direction +
offset) % 360 - 90
tick_angle = 0
else:
angle = (thetamin * direction + offset) % 360 - 90
if direction > 0:
tick_angle = np.deg2rad(angle)
else:
tick_angle = np.deg2rad(angle + 180)
text_angle = (angle + 90) % 180 - 90 # between -90 and +90.
mode, user_angle = self._labelrotation
if mode == 'auto':
text_angle += user_angle
else:
text_angle = user_angle
if full:
ha = self.label1.get_horizontalalignment()
va = self.label1.get_verticalalignment()
else:
ha, va = self._determine_anchor(mode, angle, direction > 0)
self.label1.set_horizontalalignment(ha)
self.label1.set_verticalalignment(va)
self.label1.set_rotation(text_angle)
marker = self.tick1line.get_marker()
if marker == mmarkers.TICKLEFT:
trans = mtransforms.Affine2D().rotate(tick_angle)
elif marker == '_':
trans = mtransforms.Affine2D().rotate(tick_angle + np.pi / 2)
elif marker == mmarkers.TICKRIGHT:
trans = mtransforms.Affine2D().scale(-1, 1).rotate(tick_angle)
else:
# Don't modify custom tick line markers.
trans = self.tick1line._marker._transform
self.tick1line._marker._transform = trans
if full:
self.label2.set_visible(False)
self.tick2line.set_visible(False)
angle = (thetamax * direction + offset) % 360 - 90
if direction > 0:
tick_angle = np.deg2rad(angle)
else:
tick_angle = np.deg2rad(angle + 180)
text_angle = (angle + 90) % 180 - 90 # between -90 and +90.
mode, user_angle = self._labelrotation
if mode == 'auto':
text_angle += user_angle
else:
text_angle = user_angle
ha, va = self._determine_anchor(mode, angle, direction < 0)
self.label2.set_ha(ha)
self.label2.set_va(va)
self.label2.set_rotation(text_angle)
marker = self.tick2line.get_marker()
if marker == mmarkers.TICKLEFT:
trans = mtransforms.Affine2D().rotate(tick_angle)
elif marker == '_':
trans = mtransforms.Affine2D().rotate(tick_angle + np.pi / 2)
elif marker == mmarkers.TICKRIGHT:
trans = mtransforms.Affine2D().scale(-1, 1).rotate(tick_angle)
else:
# Don't modify custom tick line markers.
trans = self.tick2line._marker._transform
self.tick2line._marker._transform = trans
class RadialAxis(maxis.YAxis):
"""
A radial Axis.
This overrides certain properties of a `YAxis` to provide special-casing
for a radial axis.
"""
__name__ = 'radialaxis'
axis_name = 'radius'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.sticky_edges.y.append(0)
def _get_tick(self, major):
if major:
tick_kw = self._major_tick_kw
else:
tick_kw = self._minor_tick_kw
return RadialTick(self.axes, 0, '', major=major, **tick_kw)
def _wrap_locator_formatter(self):
self.set_major_locator(RadialLocator(self.get_major_locator(),
self.axes))
self.isDefault_majloc = True
def cla(self):
super().cla()
self.set_ticks_position('none')
self._wrap_locator_formatter()
def _set_scale(self, value, **kwargs):
super()._set_scale(value, **kwargs)
self._wrap_locator_formatter()
def _is_full_circle_deg(thetamin, thetamax):
"""
Determine if a wedge (in degrees) spans the full circle.
The condition is derived from :class:`~matplotlib.patches.Wedge`.
"""
return abs(abs(thetamax - thetamin) - 360.0) < 1e-12
def _is_full_circle_rad(thetamin, thetamax):
"""
Determine if a wedge (in radians) spans the full circle.
The condition is derived from :class:`~matplotlib.patches.Wedge`.
"""
return abs(abs(thetamax - thetamin) - 2 * np.pi) < 1.74e-14
class _WedgeBbox(mtransforms.Bbox):
"""
Transform (theta,r) wedge Bbox into axes bounding box.
Parameters
----------
center : (float, float)
Center of the wedge
viewLim : `~matplotlib.transforms.Bbox`
Bbox determining the boundaries of the wedge
originLim : `~matplotlib.transforms.Bbox`
Bbox determining the origin for the wedge, if different from *viewLim*
"""
def __init__(self, center, viewLim, originLim, **kwargs):
mtransforms.Bbox.__init__(self,
np.array([[0.0, 0.0], [1.0, 1.0]], np.float),
**kwargs)
self._center = center
self._viewLim = viewLim
self._originLim = originLim
self.set_children(viewLim, originLim)
def __str__(self):
return ("{}(\n"
"{},\n"
"{},\n"
"{})"
.format(type(self).__name__,
mtransforms._indent_str(self._center),
mtransforms._indent_str(self._viewLim),
mtransforms._indent_str(self._originLim)))
def get_points(self):
# docstring inherited
if self._invalid:
points = self._viewLim.get_points().copy()
# Scale angular limits to work with Wedge.
points[:, 0] *= 180 / np.pi
if points[0, 0] > points[1, 0]:
points[:, 0] = points[::-1, 0]
# Scale radial limits based on origin radius.
points[:, 1] -= self._originLim.y0
# Scale radial limits to match axes limits.
rscale = 0.5 / points[1, 1]
points[:, 1] *= rscale
width = min(points[1, 1] - points[0, 1], 0.5)
# Generate bounding box for wedge.
wedge = mpatches.Wedge(self._center, points[1, 1],
points[0, 0], points[1, 0],
width=width)
self.update_from_path(wedge.get_path())
# Ensure equal aspect ratio.
w, h = self._points[1] - self._points[0]
deltah = max(w - h, 0) / 2
deltaw = max(h - w, 0) / 2
self._points += np.array([[-deltaw, -deltah], [deltaw, deltah]])
self._invalid = 0
return self._points
class PolarAxes(Axes):
"""
A polar graph projection, where the input dimensions are *theta*, *r*.
Theta starts pointing east and goes anti-clockwise.
"""
name = 'polar'
def __init__(self, *args,
theta_offset=0, theta_direction=1, rlabel_position=22.5,
**kwargs):
# docstring inherited
self._default_theta_offset = theta_offset
self._default_theta_direction = theta_direction
self._default_rlabel_position = np.deg2rad(rlabel_position)
super().__init__(*args, **kwargs)
self.use_sticky_edges = True
self.set_aspect('equal', adjustable='box', anchor='C')
self.cla()
def cla(self):
Axes.cla(self)
self.title.set_y(1.05)
start = self.spines.get('start', None)
if start:
start.set_visible(False)
end = self.spines.get('end', None)
if end:
end.set_visible(False)
self.set_xlim(0.0, 2 * np.pi)
self.grid(rcParams['polaraxes.grid'])
inner = self.spines.get('inner', None)
if inner:
inner.set_visible(False)
self.set_rorigin(None)
self.set_theta_offset(self._default_theta_offset)
self.set_theta_direction(self._default_theta_direction)
def _init_axis(self):
"move this out of __init__ because non-separable axes don't use it"
self.xaxis = ThetaAxis(self)
self.yaxis = RadialAxis(self)
# Calling polar_axes.xaxis.cla() or polar_axes.xaxis.cla()
# results in weird artifacts. Therefore we disable this for
# now.
# self.spines['polar'].register_axis(self.yaxis)
self._update_transScale()
def _set_lim_and_transforms(self):
# A view limit where the minimum radius can be locked if the user
# specifies an alternate origin.
self._originViewLim = mtransforms.LockableBbox(self.viewLim)
# Handle angular offset and direction.
self._direction = mtransforms.Affine2D() \
.scale(self._default_theta_direction, 1.0)
self._theta_offset = mtransforms.Affine2D() \
.translate(self._default_theta_offset, 0.0)
self.transShift = mtransforms.composite_transform_factory(
self._direction,
self._theta_offset)
# A view limit shifted to the correct location after accounting for
# orientation and offset.
self._realViewLim = mtransforms.TransformedBbox(self.viewLim,
self.transShift)
# Transforms the x and y axis separately by a scale factor
# It is assumed that this part will have non-linear components
self.transScale = mtransforms.TransformWrapper(
mtransforms.IdentityTransform())
# Scale view limit into a bbox around the selected wedge. This may be
# smaller than the usual unit axes rectangle if not plotting the full
# circle.
self.axesLim = _WedgeBbox((0.5, 0.5),
self._realViewLim, self._originViewLim)
# Scale the wedge to fill the axes.
self.transWedge = mtransforms.BboxTransformFrom(self.axesLim)
# Scale the axes to fill the figure.
self.transAxes = mtransforms.BboxTransformTo(self.bbox)
# A (possibly non-linear) projection on the (already scaled)
# data. This one is aware of rmin
self.transProjection = self.PolarTransform(
self,
_apply_theta_transforms=False)
# Add dependency on rorigin.
self.transProjection.set_children(self._originViewLim)
# An affine transformation on the data, generally to limit the
# range of the axes
self.transProjectionAffine = self.PolarAffine(self.transScale,
self._originViewLim)
# The complete data transformation stack -- from data all the
# way to display coordinates
self.transData = (
self.transScale + self.transShift + self.transProjection +
(self.transProjectionAffine + self.transWedge + self.transAxes))
# This is the transform for theta-axis ticks. It is
# equivalent to transData, except it always puts r == 0.0 and r == 1.0
# at the edge of the axis circles.
self._xaxis_transform = (
mtransforms.blended_transform_factory(
mtransforms.IdentityTransform(),
mtransforms.BboxTransformTo(self.viewLim)) +
self.transData)
# The theta labels are flipped along the radius, so that text 1 is on
# the outside by default. This should work the same as before.
flipr_transform = mtransforms.Affine2D() \
.translate(0.0, -0.5) \
.scale(1.0, -1.0) \
.translate(0.0, 0.5)
self._xaxis_text_transform = flipr_transform + self._xaxis_transform
# This is the transform for r-axis ticks. It scales the theta
# axis so the gridlines from 0.0 to 1.0, now go from thetamin to
# thetamax.
self._yaxis_transform = (
mtransforms.blended_transform_factory(
mtransforms.BboxTransformTo(self.viewLim),
mtransforms.IdentityTransform()) +
self.transData)
# The r-axis labels are put at an angle and padded in the r-direction
self._r_label_position = mtransforms.Affine2D() \
.translate(self._default_rlabel_position, 0.0)
self._yaxis_text_transform = mtransforms.TransformWrapper(
self._r_label_position + self.transData)
def get_xaxis_transform(self, which='grid'):
cbook._check_in_list(['tick1', 'tick2', 'grid'], which=which)
return self._xaxis_transform
def get_xaxis_text1_transform(self, pad):
return self._xaxis_text_transform, 'center', 'center'
def get_xaxis_text2_transform(self, pad):
return self._xaxis_text_transform, 'center', 'center'
def get_yaxis_transform(self, which='grid'):
if which in ('tick1', 'tick2'):
return self._yaxis_text_transform
elif which == 'grid':
return self._yaxis_transform
else:
cbook._check_in_list(['tick1', 'tick2', 'grid'], which=which)
def get_yaxis_text1_transform(self, pad):
thetamin, thetamax = self._realViewLim.intervalx
if _is_full_circle_rad(thetamin, thetamax):
return self._yaxis_text_transform, 'bottom', 'left'
elif self.get_theta_direction() > 0:
halign = 'left'
pad_shift = _ThetaShift(self, pad, 'min')
else:
halign = 'right'
pad_shift = _ThetaShift(self, pad, 'max')
return self._yaxis_text_transform + pad_shift, 'center', halign
def get_yaxis_text2_transform(self, pad):
if self.get_theta_direction() > 0:
halign = 'right'
pad_shift = _ThetaShift(self, pad, 'max')
else:
halign = 'left'
pad_shift = _ThetaShift(self, pad, 'min')
return self._yaxis_text_transform + pad_shift, 'center', halign
def draw(self, *args, **kwargs):
thetamin, thetamax = np.rad2deg(self._realViewLim.intervalx)
if thetamin > thetamax:
thetamin, thetamax = thetamax, thetamin
rmin, rmax = ((self._realViewLim.intervaly - self.get_rorigin()) *
self.get_rsign())
if isinstance(self.patch, mpatches.Wedge):
# Backwards-compatibility: Any subclassed Axes might override the
# patch to not be the Wedge that PolarAxes uses.
center = self.transWedge.transform_point((0.5, 0.5))
self.patch.set_center(center)
self.patch.set_theta1(thetamin)
self.patch.set_theta2(thetamax)
edge, _ = self.transWedge.transform_point((1, 0))
radius = edge - center[0]
width = min(radius * (rmax - rmin) / rmax, radius)
self.patch.set_radius(radius)
self.patch.set_width(width)
inner_width = radius - width
inner = self.spines.get('inner', None)
if inner:
inner.set_visible(inner_width != 0.0)
visible = not _is_full_circle_deg(thetamin, thetamax)
# For backwards compatibility, any subclassed Axes might override the
# spines to not include start/end that PolarAxes uses.
start = self.spines.get('start', None)
end = self.spines.get('end', None)
if start:
start.set_visible(visible)
if end:
end.set_visible(visible)
if visible:
yaxis_text_transform = self._yaxis_transform
else:
yaxis_text_transform = self._r_label_position + self.transData
if self._yaxis_text_transform != yaxis_text_transform:
self._yaxis_text_transform.set(yaxis_text_transform)
self.yaxis.reset_ticks()
self.yaxis.set_clip_path(self.patch)
Axes.draw(self, *args, **kwargs)
def _gen_axes_patch(self):
return mpatches.Wedge((0.5, 0.5), 0.5, 0.0, 360.0)
def _gen_axes_spines(self):
spines = OrderedDict([
('polar', mspines.Spine.arc_spine(self, 'top',
(0.5, 0.5), 0.5, 0.0, 360.0)),
('start', mspines.Spine.linear_spine(self, 'left')),
('end', mspines.Spine.linear_spine(self, 'right')),
('inner', mspines.Spine.arc_spine(self, 'bottom',
(0.5, 0.5), 0.0, 0.0, 360.0))
])
spines['polar'].set_transform(self.transWedge + self.transAxes)
spines['inner'].set_transform(self.transWedge + self.transAxes)
spines['start'].set_transform(self._yaxis_transform)
spines['end'].set_transform(self._yaxis_transform)
return spines
def set_thetamax(self, thetamax):
self.viewLim.x1 = np.deg2rad(thetamax)
def get_thetamax(self):
return np.rad2deg(self.viewLim.xmax)
def set_thetamin(self, thetamin):
self.viewLim.x0 = np.deg2rad(thetamin)
def get_thetamin(self):
return np.rad2deg(self.viewLim.xmin)
def set_thetalim(self, *args, **kwargs):
if 'thetamin' in kwargs:
kwargs['xmin'] = np.deg2rad(kwargs.pop('thetamin'))
if 'thetamax' in kwargs:
kwargs['xmax'] = np.deg2rad(kwargs.pop('thetamax'))
return tuple(np.rad2deg(self.set_xlim(*args, **kwargs)))
def set_theta_offset(self, offset):
"""
Set the offset for the location of 0 in radians.
"""
mtx = self._theta_offset.get_matrix()
mtx[0, 2] = offset
self._theta_offset.invalidate()
def get_theta_offset(self):
"""
Get the offset for the location of 0 in radians.
"""
return self._theta_offset.get_matrix()[0, 2]
def set_theta_zero_location(self, loc, offset=0.0):
"""
Sets the location of theta's zero. (Calls set_theta_offset
with the correct value in radians under the hood.)
loc : str
May be one of "N", "NW", "W", "SW", "S", "SE", "E", or "NE".
offset : float, optional
An offset in degrees to apply from the specified `loc`. **Note:**
this offset is *always* applied counter-clockwise regardless of
the direction setting.
"""
mapping = {
'N': np.pi * 0.5,
'NW': np.pi * 0.75,
'W': np.pi,
'SW': np.pi * 1.25,
'S': np.pi * 1.5,
'SE': np.pi * 1.75,
'E': 0,
'NE': np.pi * 0.25}
return self.set_theta_offset(mapping[loc] + np.deg2rad(offset))
def set_theta_direction(self, direction):
"""
Set the direction in which theta increases.
clockwise, -1:
Theta increases in the clockwise direction
counterclockwise, anticlockwise, 1:
Theta increases in the counterclockwise direction
"""
mtx = self._direction.get_matrix()
if direction in ('clockwise', -1):
mtx[0, 0] = -1
elif direction in ('counterclockwise', 'anticlockwise', 1):
mtx[0, 0] = 1
else:
cbook._check_in_list(
[-1, 1, 'clockwise', 'counterclockwise', 'anticlockwise'],
direction=direction)
self._direction.invalidate()
def get_theta_direction(self):
"""
Get the direction in which theta increases.
-1:
Theta increases in the clockwise direction
1:
Theta increases in the counterclockwise direction
"""
return self._direction.get_matrix()[0, 0]
def set_rmax(self, rmax):
self.viewLim.y1 = rmax
def get_rmax(self):
return self.viewLim.ymax
def set_rmin(self, rmin):
self.viewLim.y0 = rmin
def get_rmin(self):
return self.viewLim.ymin
def set_rorigin(self, rorigin):
self._originViewLim.locked_y0 = rorigin
def get_rorigin(self):
return self._originViewLim.y0
def get_rsign(self):
return np.sign(self._originViewLim.y1 - self._originViewLim.y0)
def set_rlim(self, bottom=None, top=None, emit=True, auto=False, **kwargs):
"""
See `~.polar.PolarAxes.set_ylim`.
"""
if 'rmin' in kwargs:
if bottom is None:
bottom = kwargs.pop('rmin')
else:
raise ValueError('Cannot supply both positional "bottom"'
'argument and kwarg "rmin"')
if 'rmax' in kwargs:
if top is None:
top = kwargs.pop('rmax')
else:
raise ValueError('Cannot supply both positional "top"'
'argument and kwarg "rmax"')
return self.set_ylim(bottom=bottom, top=top, emit=emit, auto=auto,
**kwargs)
def set_ylim(self, bottom=None, top=None, emit=True, auto=False,
*, ymin=None, ymax=None):
"""
Set the data limits for the radial axis.
Parameters
----------
bottom : scalar, optional
The bottom limit (default: None, which leaves the bottom
limit unchanged).
The bottom and top ylims may be passed as the tuple
(*bottom*, *top*) as the first positional argument (or as
the *bottom* keyword argument).
top : scalar, optional
The top limit (default: None, which leaves the top limit
unchanged).
emit : bool, optional
Whether to notify observers of limit change (default: True).
auto : bool or None, optional
Whether to turn on autoscaling of the y-axis. True turns on,
False turns off (default action), None leaves unchanged.
ymin, ymax : scalar, optional
These arguments are deprecated and will be removed in a future
version. They are equivalent to *bottom* and *top* respectively,
and it is an error to pass both *ymin* and *bottom* or
*ymax* and *top*.
Returns
-------
bottom, top : (float, float)
The new y-axis limits in data coordinates.
"""
if ymin is not None:
if bottom is not None:
raise ValueError('Cannot supply both positional "bottom" '
'argument and kwarg "ymin"')
else:
bottom = ymin
if ymax is not None:
if top is not None:
raise ValueError('Cannot supply both positional "top" '
'argument and kwarg "ymax"')
else:
top = ymax
if top is None and np.iterable(bottom):
bottom, top = bottom[0], bottom[1]
return super().set_ylim(bottom=bottom, top=top, emit=emit, auto=auto)
def get_rlabel_position(self):
"""
Returns
-------
float
The theta position of the radius labels in degrees.
"""
return np.rad2deg(self._r_label_position.get_matrix()[0, 2])
def set_rlabel_position(self, value):
"""Updates the theta position of the radius labels.
Parameters
----------
value : number
The angular position of the radius labels in degrees.
"""
self._r_label_position.clear().translate(np.deg2rad(value), 0.0)
def set_yscale(self, *args, **kwargs):
Axes.set_yscale(self, *args, **kwargs)
self.yaxis.set_major_locator(
self.RadialLocator(self.yaxis.get_major_locator(), self))
def set_rscale(self, *args, **kwargs):
return Axes.set_yscale(self, *args, **kwargs)
def set_rticks(self, *args, **kwargs):
return Axes.set_yticks(self, *args, **kwargs)
def set_thetagrids(self, angles, labels=None, fmt=None, **kwargs):
"""
Set the theta gridlines in a polar plot.
Parameters
----------
angles : tuple with floats, degrees
The angles of the theta gridlines.
labels : tuple with strings or None
The labels to use at each theta gridline. The
`.projections.polar.ThetaFormatter` will be used if None.
fmt : str or None
Format string used in `matplotlib.ticker.FormatStrFormatter`.
For example '%f'. Note that the angle that is used is in
radians.
Returns
-------
lines, labels : list of `.lines.Line2D`, list of `.text.Text`
*lines* are the theta gridlines and *labels* are the tick labels.
Other Parameters
----------------
**kwargs
*kwargs* are optional `~.Text` properties for the labels.
See Also
--------
.PolarAxes.set_rgrids
.Axis.get_gridlines
.Axis.get_ticklabels
"""
# Make sure we take into account unitized data
angles = self.convert_yunits(angles)
angles = np.deg2rad(angles)
self.set_xticks(angles)
if labels is not None:
self.set_xticklabels(labels)
elif fmt is not None:
self.xaxis.set_major_formatter(mticker.FormatStrFormatter(fmt))
for t in self.xaxis.get_ticklabels():
t.update(kwargs)
return self.xaxis.get_ticklines(), self.xaxis.get_ticklabels()
def set_rgrids(self, radii, labels=None, angle=None, fmt=None,
**kwargs):
"""
Set the radial gridlines on a polar plot.
Parameters
----------
radii : tuple with floats
The radii for the radial gridlines
labels : tuple with strings or None
The labels to use at each radial gridline. The
`matplotlib.ticker.ScalarFormatter` will be used if None.
angle : float
The angular position of the radius labels in degrees.
fmt : str or None
Format string used in `matplotlib.ticker.FormatStrFormatter`.
For example '%f'.
Returns
-------
lines, labels : list of `.lines.Line2D`, list of `.text.Text`
*lines* are the radial gridlines and *labels* are the tick labels.
Other Parameters
----------------
**kwargs
*kwargs* are optional `~.Text` properties for the labels.
See Also
--------
.PolarAxes.set_thetagrids
.Axis.get_gridlines
.Axis.get_ticklabels
"""
# Make sure we take into account unitized data
radii = self.convert_xunits(radii)
radii = np.asarray(radii)
self.set_yticks(radii)
if labels is not None:
self.set_yticklabels(labels)
elif fmt is not None:
self.yaxis.set_major_formatter(mticker.FormatStrFormatter(fmt))
if angle is None:
angle = self.get_rlabel_position()
self.set_rlabel_position(angle)
for t in self.yaxis.get_ticklabels():
t.update(kwargs)
return self.yaxis.get_gridlines(), self.yaxis.get_ticklabels()
def set_xscale(self, scale, *args, **kwargs):
if scale != 'linear':
raise NotImplementedError(
"You can not set the xscale on a polar plot.")
def format_coord(self, theta, r):
"""
Return a format string formatting the coordinate using Unicode
characters.
"""
if theta < 0:
theta += 2 * np.pi
theta /= np.pi
return ('\N{GREEK SMALL LETTER THETA}=%0.3f\N{GREEK SMALL LETTER PI} '
'(%0.3f\N{DEGREE SIGN}), r=%0.3f') % (theta, theta * 180.0, r)
def get_data_ratio(self):
'''
Return the aspect ratio of the data itself. For a polar plot,
this should always be 1.0
'''
return 1.0
# # # Interactive panning
def can_zoom(self):
"""
Return *True* if this axes supports the zoom box button functionality.
Polar axes do not support zoom boxes.
"""
return False
def can_pan(self):
"""
Return *True* if this axes supports the pan/zoom button functionality.
For polar axes, this is slightly misleading. Both panning and
zooming are performed by the same button. Panning is performed
in azimuth while zooming is done along the radial.
"""
return True
def start_pan(self, x, y, button):
angle = np.deg2rad(self.get_rlabel_position())
mode = ''
if button == 1:
epsilon = np.pi / 45.0
t, r = self.transData.inverted().transform_point((x, y))
if angle - epsilon <= t <= angle + epsilon:
mode = 'drag_r_labels'
elif button == 3:
mode = 'zoom'
self._pan_start = types.SimpleNamespace(
rmax=self.get_rmax(),
trans=self.transData.frozen(),
trans_inverse=self.transData.inverted().frozen(),
r_label_angle=self.get_rlabel_position(),
x=x,
y=y,
mode=mode)
def end_pan(self):
del self._pan_start
def drag_pan(self, button, key, x, y):
p = self._pan_start
if p.mode == 'drag_r_labels':
startt, startr = p.trans_inverse.transform_point((p.x, p.y))
t, r = p.trans_inverse.transform_point((x, y))
# Deal with theta
dt0 = t - startt
dt1 = startt - t
if abs(dt1) < abs(dt0):
dt = abs(dt1) * np.sign(dt0) * -1.0
else:
dt = dt0 * -1.0
dt = (dt / np.pi) * 180.0
self.set_rlabel_position(p.r_label_angle - dt)
trans, vert1, horiz1 = self.get_yaxis_text1_transform(0.0)
trans, vert2, horiz2 = self.get_yaxis_text2_transform(0.0)
for t in self.yaxis.majorTicks + self.yaxis.minorTicks:
t.label1.set_va(vert1)
t.label1.set_ha(horiz1)
t.label2.set_va(vert2)
t.label2.set_ha(horiz2)
elif p.mode == 'zoom':
startt, startr = p.trans_inverse.transform_point((p.x, p.y))
t, r = p.trans_inverse.transform_point((x, y))
# Deal with r
scale = r / startr
self.set_rmax(p.rmax / scale)
# to keep things all self contained, we can put aliases to the Polar classes
# defined above. This isn't strictly necessary, but it makes some of the
# code more readable (and provides a backwards compatible Polar API)
PolarAxes.PolarTransform = PolarTransform
PolarAxes.PolarAffine = PolarAffine
PolarAxes.InvertedPolarTransform = InvertedPolarTransform
PolarAxes.ThetaFormatter = ThetaFormatter
PolarAxes.RadialLocator = RadialLocator
PolarAxes.ThetaLocator = ThetaLocator
|
31ba620549a3d91ff0eb1afb4a76703589b9f426ea1a2a6821fe4336aaea0bea
|
import numpy as np
from matplotlib import cbook, rcParams
from matplotlib.axes import Axes
import matplotlib.axis as maxis
from matplotlib.patches import Circle
from matplotlib.path import Path
import matplotlib.spines as mspines
from matplotlib.ticker import (
Formatter, NullLocator, FixedLocator, NullFormatter)
from matplotlib.transforms import Affine2D, BboxTransformTo, Transform
class GeoAxes(Axes):
"""An abstract base class for geographic projections."""
class ThetaFormatter(Formatter):
"""
Used to format the theta tick labels. Converts the native
unit of radians into degrees and adds a degree symbol.
"""
def __init__(self, round_to=1.0):
self._round_to = round_to
def __call__(self, x, pos=None):
degrees = (x / np.pi) * 180.0
degrees = np.round(degrees / self._round_to) * self._round_to
if rcParams['text.usetex'] and not rcParams['text.latex.unicode']:
return r"$%0.0f^\circ$" % degrees
else:
return "%0.0f\N{DEGREE SIGN}" % degrees
RESOLUTION = 75
def _init_axis(self):
self.xaxis = maxis.XAxis(self)
self.yaxis = maxis.YAxis(self)
# Do not register xaxis or yaxis with spines -- as done in
# Axes._init_axis() -- until GeoAxes.xaxis.cla() works.
# self.spines['geo'].register_axis(self.yaxis)
self._update_transScale()
def cla(self):
Axes.cla(self)
self.set_longitude_grid(30)
self.set_latitude_grid(15)
self.set_longitude_grid_ends(75)
self.xaxis.set_minor_locator(NullLocator())
self.yaxis.set_minor_locator(NullLocator())
self.xaxis.set_ticks_position('none')
self.yaxis.set_ticks_position('none')
self.yaxis.set_tick_params(label1On=True)
# Why do we need to turn on yaxis tick labels, but
# xaxis tick labels are already on?
self.grid(rcParams['axes.grid'])
Axes.set_xlim(self, -np.pi, np.pi)
Axes.set_ylim(self, -np.pi / 2.0, np.pi / 2.0)
def _set_lim_and_transforms(self):
# A (possibly non-linear) projection on the (already scaled) data
self.transProjection = self._get_core_transform(self.RESOLUTION)
self.transAffine = self._get_affine_transform()
self.transAxes = BboxTransformTo(self.bbox)
# The complete data transformation stack -- from data all the
# way to display coordinates
self.transData = \
self.transProjection + \
self.transAffine + \
self.transAxes
# This is the transform for longitude ticks.
self._xaxis_pretransform = \
Affine2D() \
.scale(1, self._longitude_cap * 2) \
.translate(0, -self._longitude_cap)
self._xaxis_transform = \
self._xaxis_pretransform + \
self.transData
self._xaxis_text1_transform = \
Affine2D().scale(1, 0) + \
self.transData + \
Affine2D().translate(0, 4)
self._xaxis_text2_transform = \
Affine2D().scale(1, 0) + \
self.transData + \
Affine2D().translate(0, -4)
# This is the transform for latitude ticks.
yaxis_stretch = Affine2D().scale(np.pi * 2, 1).translate(-np.pi, 0)
yaxis_space = Affine2D().scale(1, 1.1)
self._yaxis_transform = \
yaxis_stretch + \
self.transData
yaxis_text_base = \
yaxis_stretch + \
self.transProjection + \
(yaxis_space + \
self.transAffine + \
self.transAxes)
self._yaxis_text1_transform = \
yaxis_text_base + \
Affine2D().translate(-8, 0)
self._yaxis_text2_transform = \
yaxis_text_base + \
Affine2D().translate(8, 0)
def _get_affine_transform(self):
transform = self._get_core_transform(1)
xscale, _ = transform.transform_point((np.pi, 0))
_, yscale = transform.transform_point((0, np.pi / 2))
return Affine2D() \
.scale(0.5 / xscale, 0.5 / yscale) \
.translate(0.5, 0.5)
def get_xaxis_transform(self, which='grid'):
cbook._check_in_list(['tick1', 'tick2', 'grid'], which=which)
return self._xaxis_transform
def get_xaxis_text1_transform(self, pad):
return self._xaxis_text1_transform, 'bottom', 'center'
def get_xaxis_text2_transform(self, pad):
return self._xaxis_text2_transform, 'top', 'center'
def get_yaxis_transform(self, which='grid'):
cbook._check_in_list(['tick1', 'tick2', 'grid'], which=which)
return self._yaxis_transform
def get_yaxis_text1_transform(self, pad):
return self._yaxis_text1_transform, 'center', 'right'
def get_yaxis_text2_transform(self, pad):
return self._yaxis_text2_transform, 'center', 'left'
def _gen_axes_patch(self):
return Circle((0.5, 0.5), 0.5)
def _gen_axes_spines(self):
return {'geo': mspines.Spine.circular_spine(self, (0.5, 0.5), 0.5)}
def set_yscale(self, *args, **kwargs):
if args[0] != 'linear':
raise NotImplementedError
set_xscale = set_yscale
def set_xlim(self, *args, **kwargs):
raise TypeError("It is not possible to change axes limits "
"for geographic projections. Please consider "
"using Basemap or Cartopy.")
set_ylim = set_xlim
def format_coord(self, lon, lat):
'return a format string formatting the coordinate'
lon, lat = np.rad2deg([lon, lat])
if lat >= 0.0:
ns = 'N'
else:
ns = 'S'
if lon >= 0.0:
ew = 'E'
else:
ew = 'W'
return ('%f\N{DEGREE SIGN}%s, %f\N{DEGREE SIGN}%s'
% (abs(lat), ns, abs(lon), ew))
def set_longitude_grid(self, degrees):
"""
Set the number of degrees between each longitude grid.
"""
# Skip -180 and 180, which are the fixed limits.
grid = np.arange(-180 + degrees, 180, degrees)
self.xaxis.set_major_locator(FixedLocator(np.deg2rad(grid)))
self.xaxis.set_major_formatter(self.ThetaFormatter(degrees))
def set_latitude_grid(self, degrees):
"""
Set the number of degrees between each latitude grid.
"""
# Skip -90 and 90, which are the fixed limits.
grid = np.arange(-90 + degrees, 90, degrees)
self.yaxis.set_major_locator(FixedLocator(np.deg2rad(grid)))
self.yaxis.set_major_formatter(self.ThetaFormatter(degrees))
def set_longitude_grid_ends(self, degrees):
"""
Set the latitude(s) at which to stop drawing the longitude grids.
"""
self._longitude_cap = np.deg2rad(degrees)
self._xaxis_pretransform \
.clear() \
.scale(1.0, self._longitude_cap * 2.0) \
.translate(0.0, -self._longitude_cap)
def get_data_ratio(self):
'''
Return the aspect ratio of the data itself.
'''
return 1.0
### Interactive panning
def can_zoom(self):
"""
Return *True* if this axes supports the zoom box button functionality.
This axes object does not support interactive zoom box.
"""
return False
def can_pan(self) :
"""
Return *True* if this axes supports the pan/zoom button functionality.
This axes object does not support interactive pan/zoom.
"""
return False
def start_pan(self, x, y, button):
pass
def end_pan(self):
pass
def drag_pan(self, button, key, x, y):
pass
class _GeoTransform(Transform):
# Factoring out some common functionality.
input_dims = 2
output_dims = 2
is_separable = False
def __init__(self, resolution):
"""
Create a new geographical transform.
Resolution is the number of steps to interpolate between each input
line segment to approximate its path in curved space.
"""
Transform.__init__(self)
self._resolution = resolution
def __str__(self):
return "{}({})".format(type(self).__name__, self._resolution)
def transform_path_non_affine(self, path):
# docstring inherited
ipath = path.interpolated(self._resolution)
return Path(self.transform(ipath.vertices), ipath.codes)
class AitoffAxes(GeoAxes):
name = 'aitoff'
class AitoffTransform(_GeoTransform):
"""The base Aitoff transform."""
def transform_non_affine(self, ll):
# docstring inherited
longitude = ll[:, 0]
latitude = ll[:, 1]
# Pre-compute some values
half_long = longitude / 2.0
cos_latitude = np.cos(latitude)
alpha = np.arccos(cos_latitude * np.cos(half_long))
# Avoid divide-by-zero errors using same method as NumPy.
alpha[alpha == 0.0] = 1e-20
# We want unnormalized sinc. numpy.sinc gives us normalized
sinc_alpha = np.sin(alpha) / alpha
xy = np.empty_like(ll, float)
xy[:, 0] = (cos_latitude * np.sin(half_long)) / sinc_alpha
xy[:, 1] = np.sin(latitude) / sinc_alpha
return xy
def inverted(self):
# docstring inherited
return AitoffAxes.InvertedAitoffTransform(self._resolution)
class InvertedAitoffTransform(_GeoTransform):
def transform_non_affine(self, xy):
# docstring inherited
# MGDTODO: Math is hard ;(
return xy
def inverted(self):
# docstring inherited
return AitoffAxes.AitoffTransform(self._resolution)
def __init__(self, *args, **kwargs):
self._longitude_cap = np.pi / 2.0
GeoAxes.__init__(self, *args, **kwargs)
self.set_aspect(0.5, adjustable='box', anchor='C')
self.cla()
def _get_core_transform(self, resolution):
return self.AitoffTransform(resolution)
class HammerAxes(GeoAxes):
name = 'hammer'
class HammerTransform(_GeoTransform):
"""The base Hammer transform."""
def transform_non_affine(self, ll):
# docstring inherited
longitude = ll[:, 0:1]
latitude = ll[:, 1:2]
# Pre-compute some values
half_long = longitude / 2.0
cos_latitude = np.cos(latitude)
sqrt2 = np.sqrt(2.0)
alpha = np.sqrt(1.0 + cos_latitude * np.cos(half_long))
x = (2.0 * sqrt2) * (cos_latitude * np.sin(half_long)) / alpha
y = (sqrt2 * np.sin(latitude)) / alpha
return np.concatenate((x, y), 1)
def inverted(self):
# docstring inherited
return HammerAxes.InvertedHammerTransform(self._resolution)
class InvertedHammerTransform(_GeoTransform):
def transform_non_affine(self, xy):
# docstring inherited
x, y = xy.T
z = np.sqrt(1 - (x / 4) ** 2 - (y / 2) ** 2)
longitude = 2 * np.arctan((z * x) / (2 * (2 * z ** 2 - 1)))
latitude = np.arcsin(y*z)
return np.column_stack([longitude, latitude])
def inverted(self):
# docstring inherited
return HammerAxes.HammerTransform(self._resolution)
def __init__(self, *args, **kwargs):
self._longitude_cap = np.pi / 2.0
GeoAxes.__init__(self, *args, **kwargs)
self.set_aspect(0.5, adjustable='box', anchor='C')
self.cla()
def _get_core_transform(self, resolution):
return self.HammerTransform(resolution)
class MollweideAxes(GeoAxes):
name = 'mollweide'
class MollweideTransform(_GeoTransform):
"""The base Mollweide transform."""
def transform_non_affine(self, ll):
# docstring inherited
def d(theta):
delta = (-(theta + np.sin(theta) - pi_sin_l)
/ (1 + np.cos(theta)))
return delta, np.abs(delta) > 0.001
longitude = ll[:, 0]
latitude = ll[:, 1]
clat = np.pi/2 - np.abs(latitude)
ihigh = clat < 0.087 # within 5 degrees of the poles
ilow = ~ihigh
aux = np.empty(latitude.shape, dtype=float)
if ilow.any(): # Newton-Raphson iteration
pi_sin_l = np.pi * np.sin(latitude[ilow])
theta = 2.0 * latitude[ilow]
delta, large_delta = d(theta)
while np.any(large_delta):
theta[large_delta] += delta[large_delta]
delta, large_delta = d(theta)
aux[ilow] = theta / 2
if ihigh.any(): # Taylor series-based approx. solution
e = clat[ihigh]
d = 0.5 * (3 * np.pi * e**2) ** (1.0/3)
aux[ihigh] = (np.pi/2 - d) * np.sign(latitude[ihigh])
xy = np.empty(ll.shape, dtype=float)
xy[:, 0] = (2.0 * np.sqrt(2.0) / np.pi) * longitude * np.cos(aux)
xy[:, 1] = np.sqrt(2.0) * np.sin(aux)
return xy
def inverted(self):
# docstring inherited
return MollweideAxes.InvertedMollweideTransform(self._resolution)
class InvertedMollweideTransform(_GeoTransform):
def transform_non_affine(self, xy):
# docstring inherited
x = xy[:, 0:1]
y = xy[:, 1:2]
# from Equations (7, 8) of
# http://mathworld.wolfram.com/MollweideProjection.html
theta = np.arcsin(y / np.sqrt(2))
lon = (np.pi / (2 * np.sqrt(2))) * x / np.cos(theta)
lat = np.arcsin((2 * theta + np.sin(2 * theta)) / np.pi)
return np.concatenate((lon, lat), 1)
def inverted(self):
# docstring inherited
return MollweideAxes.MollweideTransform(self._resolution)
def __init__(self, *args, **kwargs):
self._longitude_cap = np.pi / 2.0
GeoAxes.__init__(self, *args, **kwargs)
self.set_aspect(0.5, adjustable='box', anchor='C')
self.cla()
def _get_core_transform(self, resolution):
return self.MollweideTransform(resolution)
class LambertAxes(GeoAxes):
name = 'lambert'
class LambertTransform(_GeoTransform):
"""The base Lambert transform."""
def __init__(self, center_longitude, center_latitude, resolution):
"""
Create a new Lambert transform. Resolution is the number of steps
to interpolate between each input line segment to approximate its
path in curved Lambert space.
"""
_GeoTransform.__init__(self, resolution)
self._center_longitude = center_longitude
self._center_latitude = center_latitude
def transform_non_affine(self, ll):
# docstring inherited
longitude = ll[:, 0:1]
latitude = ll[:, 1:2]
clong = self._center_longitude
clat = self._center_latitude
cos_lat = np.cos(latitude)
sin_lat = np.sin(latitude)
diff_long = longitude - clong
cos_diff_long = np.cos(diff_long)
inner_k = np.maximum( # Prevent divide-by-zero problems
1 + np.sin(clat)*sin_lat + np.cos(clat)*cos_lat*cos_diff_long,
1e-15)
k = np.sqrt(2 / inner_k)
x = k * cos_lat*np.sin(diff_long)
y = k * (np.cos(clat)*sin_lat - np.sin(clat)*cos_lat*cos_diff_long)
return np.concatenate((x, y), 1)
def inverted(self):
# docstring inherited
return LambertAxes.InvertedLambertTransform(
self._center_longitude,
self._center_latitude,
self._resolution)
class InvertedLambertTransform(_GeoTransform):
def __init__(self, center_longitude, center_latitude, resolution):
_GeoTransform.__init__(self, resolution)
self._center_longitude = center_longitude
self._center_latitude = center_latitude
def transform_non_affine(self, xy):
# docstring inherited
x = xy[:, 0:1]
y = xy[:, 1:2]
clong = self._center_longitude
clat = self._center_latitude
p = np.maximum(np.hypot(x, y), 1e-9)
c = 2 * np.arcsin(0.5 * p)
sin_c = np.sin(c)
cos_c = np.cos(c)
lat = np.arcsin(cos_c*np.sin(clat) +
((y*sin_c*np.cos(clat)) / p))
lon = clong + np.arctan(
(x*sin_c) / (p*np.cos(clat)*cos_c - y*np.sin(clat)*sin_c))
return np.concatenate((lon, lat), 1)
def inverted(self):
# docstring inherited
return LambertAxes.LambertTransform(
self._center_longitude,
self._center_latitude,
self._resolution)
def __init__(self, *args, center_longitude=0, center_latitude=0, **kwargs):
self._longitude_cap = np.pi / 2
self._center_longitude = center_longitude
self._center_latitude = center_latitude
GeoAxes.__init__(self, *args, **kwargs)
self.set_aspect('equal', adjustable='box', anchor='C')
self.cla()
def cla(self):
GeoAxes.cla(self)
self.yaxis.set_major_formatter(NullFormatter())
def _get_core_transform(self, resolution):
return self.LambertTransform(
self._center_longitude,
self._center_latitude,
resolution)
def _get_affine_transform(self):
return Affine2D() \
.scale(0.25) \
.translate(0.5, 0.5)
|
35959ffc1f6e2a02c751bc2a8314962387ec55e86e5159d5e4539db8895d6565
|
"""
Core functions and attributes for the matplotlib style library:
``use``
Select style sheet to override the current matplotlib settings.
``context``
Context manager to use a style sheet temporarily.
``available``
List available style sheets.
``library``
A dictionary of style names and matplotlib settings.
"""
import contextlib
import logging
import os
import re
import warnings
import matplotlib as mpl
from matplotlib import cbook, rc_params_from_file, rcParamsDefault
_log = logging.getLogger(__name__)
__all__ = ['use', 'context', 'available', 'library', 'reload_library']
BASE_LIBRARY_PATH = os.path.join(mpl.get_data_path(), 'stylelib')
# Users may want multiple library paths, so store a list of paths.
USER_LIBRARY_PATHS = [os.path.join(mpl.get_configdir(), 'stylelib')]
STYLE_EXTENSION = 'mplstyle'
STYLE_FILE_PATTERN = re.compile(r'([\S]+).%s$' % STYLE_EXTENSION)
# A list of rcParams that should not be applied from styles
STYLE_BLACKLIST = {
'interactive', 'backend', 'backend.qt4', 'webagg.port', 'webagg.address',
'webagg.port_retries', 'webagg.open_in_browser', 'backend_fallback',
'toolbar', 'timezone', 'datapath', 'figure.max_open_warning',
'savefig.directory', 'tk.window_focus', 'docstring.hardcopy'}
def _remove_blacklisted_style_params(d, warn=True):
o = {}
for key, val in d.items():
if key in STYLE_BLACKLIST:
if warn:
cbook._warn_external(
"Style includes a parameter, '{0}', that is not related "
"to style. Ignoring".format(key))
else:
o[key] = val
return o
def is_style_file(filename):
"""Return True if the filename looks like a style file."""
return STYLE_FILE_PATTERN.match(filename) is not None
def _apply_style(d, warn=True):
mpl.rcParams.update(_remove_blacklisted_style_params(d, warn=warn))
def use(style):
"""Use matplotlib style settings from a style specification.
The style name of 'default' is reserved for reverting back to
the default style settings.
Parameters
----------
style : str, dict, or list
A style specification. Valid options are:
+------+-------------------------------------------------------------+
| str | The name of a style or a path/URL to a style file. For a |
| | list of available style names, see `style.available`. |
+------+-------------------------------------------------------------+
| dict | Dictionary with valid key/value pairs for |
| | `matplotlib.rcParams`. |
+------+-------------------------------------------------------------+
| list | A list of style specifiers (str or dict) applied from first |
| | to last in the list. |
+------+-------------------------------------------------------------+
"""
style_alias = {'mpl20': 'default',
'mpl15': 'classic'}
if isinstance(style, str) or hasattr(style, 'keys'):
# If name is a single str or dict, make it a single element list.
styles = [style]
else:
styles = style
styles = (style_alias.get(s, s) if isinstance(s, str) else s
for s in styles)
for style in styles:
if not isinstance(style, str):
_apply_style(style)
elif style == 'default':
# Deprecation warnings were already handled when creating
# rcParamsDefault, no need to reemit them here.
with cbook._suppress_matplotlib_deprecation_warning():
_apply_style(rcParamsDefault, warn=False)
elif style in library:
_apply_style(library[style])
else:
try:
rc = rc_params_from_file(style, use_default_template=False)
_apply_style(rc)
except IOError:
raise IOError(
"{!r} not found in the style library and input is not a "
"valid URL or path; see `style.available` for list of "
"available styles".format(style))
@contextlib.contextmanager
def context(style, after_reset=False):
"""Context manager for using style settings temporarily.
Parameters
----------
style : str, dict, or list
A style specification. Valid options are:
+------+-------------------------------------------------------------+
| str | The name of a style or a path/URL to a style file. For a |
| | list of available style names, see `style.available`. |
+------+-------------------------------------------------------------+
| dict | Dictionary with valid key/value pairs for |
| | `matplotlib.rcParams`. |
+------+-------------------------------------------------------------+
| list | A list of style specifiers (str or dict) applied from first |
| | to last in the list. |
+------+-------------------------------------------------------------+
after_reset : bool
If True, apply style after resetting settings to their defaults;
otherwise, apply style on top of the current settings.
"""
with mpl.rc_context():
if after_reset:
mpl.rcdefaults()
use(style)
yield
def load_base_library():
"""Load style library defined in this package."""
library = read_style_directory(BASE_LIBRARY_PATH)
return library
def iter_user_libraries():
for stylelib_path in USER_LIBRARY_PATHS:
stylelib_path = os.path.expanduser(stylelib_path)
if os.path.exists(stylelib_path) and os.path.isdir(stylelib_path):
yield stylelib_path
def update_user_library(library):
"""Update style library with user-defined rc files"""
for stylelib_path in iter_user_libraries():
styles = read_style_directory(stylelib_path)
update_nested_dict(library, styles)
return library
def iter_style_files(style_dir):
"""Yield file path and name of styles in the given directory."""
for path in os.listdir(style_dir):
filename = os.path.basename(path)
if is_style_file(filename):
match = STYLE_FILE_PATTERN.match(filename)
path = os.path.abspath(os.path.join(style_dir, path))
yield path, match.group(1)
def read_style_directory(style_dir):
"""Return dictionary of styles defined in `style_dir`."""
styles = dict()
for path, name in iter_style_files(style_dir):
with warnings.catch_warnings(record=True) as warns:
styles[name] = rc_params_from_file(path,
use_default_template=False)
for w in warns:
message = 'In %s: %s' % (path, w.message)
_log.warning(message)
return styles
def update_nested_dict(main_dict, new_dict):
"""Update nested dict (only level of nesting) with new values.
Unlike dict.update, this assumes that the values of the parent dict are
dicts (or dict-like), so you shouldn't replace the nested dict if it
already exists. Instead you should update the sub-dict.
"""
# update named styles specified by user
for name, rc_dict in new_dict.items():
main_dict.setdefault(name, {}).update(rc_dict)
return main_dict
# Load style library
# ==================
_base_library = load_base_library()
library = None
available = []
def reload_library():
"""Reload style library."""
global library
available[:] = library = update_user_library(_base_library)
reload_library()
|
104c4e01402adeefebb1c53091f2ad6681202c0e67a6696d0ab61938ff5fb63c
|
from .core import use, context, available, library, reload_library
|
54366d60d5a310248680a41b483432ba771fb48e58fe9e45a2b4f3ab769d192e
|
"""
A directive for including a matplotlib plot in a Sphinx document.
By default, in HTML output, `plot` will include a .png file with a
link to a high-res .png and .pdf. In LaTeX output, it will include a
.pdf.
The source code for the plot may be included in one of three ways:
1. **A path to a source file** as the argument to the directive::
.. plot:: path/to/plot.py
When a path to a source file is given, the content of the
directive may optionally contain a caption for the plot::
.. plot:: path/to/plot.py
This is the caption for the plot
Additionally, one may specify the name of a function to call (with
no arguments) immediately after importing the module::
.. plot:: path/to/plot.py plot_function1
2. Included as **inline content** to the directive::
.. plot::
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
img = mpimg.imread('_static/stinkbug.png')
imgplot = plt.imshow(img)
3. Using **doctest** syntax::
.. plot::
A plotting example:
>>> import matplotlib.pyplot as plt
>>> plt.plot([1,2,3], [4,5,6])
Options
-------
The ``plot`` directive supports the following options:
format : {'python', 'doctest'}
Specify the format of the input
include-source : bool
Whether to display the source code. The default can be changed
using the `plot_include_source` variable in conf.py
encoding : str
If this source file is in a non-UTF8 or non-ASCII encoding,
the encoding must be specified using the `:encoding:` option.
The encoding will not be inferred using the ``-*- coding -*-``
metacomment.
context : bool or str
If provided, the code will be run in the context of all
previous plot directives for which the `:context:` option was
specified. This only applies to inline code plot directives,
not those run from files. If the ``:context: reset`` option is
specified, the context is reset for this and future plots, and
previous figures are closed prior to running the code.
``:context:close-figs`` keeps the context but closes previous figures
before running the code.
nofigs : bool
If specified, the code block will be run, but no figures will
be inserted. This is usually useful with the ``:context:``
option.
Additionally, this directive supports all of the options of the
`image` directive, except for `target` (since plot will add its own
target). These include `alt`, `height`, `width`, `scale`, `align` and
`class`.
Configuration options
---------------------
The plot directive has the following configuration options:
plot_include_source
Default value for the include-source option
plot_html_show_source_link
Whether to show a link to the source in HTML.
plot_pre_code
Code that should be executed before each plot. If not specified or None
it will default to a string containing::
import numpy as np
from matplotlib import pyplot as plt
plot_basedir
Base directory, to which ``plot::`` file names are relative
to. (If None or empty, file names are relative to the
directory where the file containing the directive is.)
plot_formats
File formats to generate. List of tuples or strings::
[(suffix, dpi), suffix, ...]
that determine the file format and the DPI. For entries whose
DPI was omitted, sensible defaults are chosen. When passing from
the command line through sphinx_build the list should be passed as
suffix:dpi,suffix:dpi, ....
plot_html_show_formats
Whether to show links to the files in HTML.
plot_rcparams
A dictionary containing any non-standard rcParams that should
be applied before each plot.
plot_apply_rcparams
By default, rcParams are applied when `context` option is not used in
a plot directive. This configuration option overrides this behavior
and applies rcParams before each plot.
plot_working_directory
By default, the working directory will be changed to the directory of
the example, so the code can get at its data files, if any. Also its
path will be added to `sys.path` so it can import any helper modules
sitting beside it. This configuration option can be used to specify
a central directory (also added to `sys.path`) where data files and
helper modules for all code are located.
plot_template
Provide a customized template for preparing restructured text.
"""
import contextlib
from io import StringIO
import itertools
import os
from os.path import relpath
from pathlib import Path
import re
import shutil
import sys
import textwrap
import traceback
import warnings
from docutils.parsers.rst import directives, Directive
from docutils.parsers.rst.directives.images import Image
import jinja2 # Sphinx dependency.
import matplotlib
from matplotlib.backend_bases import FigureManagerBase
try:
with warnings.catch_warnings(record=True):
warnings.simplefilter("error", UserWarning)
matplotlib.use('Agg')
except UserWarning:
import matplotlib.pyplot as plt
plt.switch_backend("Agg")
else:
import matplotlib.pyplot as plt
from matplotlib import _pylab_helpers, cbook
align = Image.align
__version__ = 2
# -----------------------------------------------------------------------------
# Registration hook
# -----------------------------------------------------------------------------
@cbook.deprecated("3.1", alternative="PlotDirective")
def plot_directive(name, arguments, options, content, lineno,
content_offset, block_text, state, state_machine):
"""Implementation of the ``.. plot::`` directive.
See the module docstring for details.
"""
return run(arguments, content, options, state_machine, state, lineno)
def _option_boolean(arg):
if not arg or not arg.strip():
# no argument given, assume used as a flag
return True
elif arg.strip().lower() in ('no', '0', 'false'):
return False
elif arg.strip().lower() in ('yes', '1', 'true'):
return True
else:
raise ValueError('"%s" unknown boolean' % arg)
def _option_context(arg):
if arg in [None, 'reset', 'close-figs']:
return arg
raise ValueError("argument should be None or 'reset' or 'close-figs'")
def _option_format(arg):
return directives.choice(arg, ('python', 'doctest'))
def _option_align(arg):
return directives.choice(arg, ("top", "middle", "bottom", "left", "center",
"right"))
def mark_plot_labels(app, document):
"""
To make plots referenceable, we need to move the reference from
the "htmlonly" (or "latexonly") node to the actual figure node
itself.
"""
for name, explicit in document.nametypes.items():
if not explicit:
continue
labelid = document.nameids[name]
if labelid is None:
continue
node = document.ids[labelid]
if node.tagname in ('html_only', 'latex_only'):
for n in node:
if n.tagname == 'figure':
sectname = name
for c in n:
if c.tagname == 'caption':
sectname = c.astext()
break
node['ids'].remove(labelid)
node['names'].remove(name)
n['ids'].append(labelid)
n['names'].append(name)
document.settings.env.labels[name] = \
document.settings.env.docname, labelid, sectname
break
class PlotDirective(Directive):
"""Implementation of the ``.. plot::`` directive.
See the module docstring for details.
"""
has_content = True
required_arguments = 0
optional_arguments = 2
final_argument_whitespace = False
option_spec = {
'alt': directives.unchanged,
'height': directives.length_or_unitless,
'width': directives.length_or_percentage_or_unitless,
'scale': directives.nonnegative_int,
'align': _option_align,
'class': directives.class_option,
'include-source': _option_boolean,
'format': _option_format,
'context': _option_context,
'nofigs': directives.flag,
'encoding': directives.encoding,
}
def run(self):
"""Run the plot directive."""
return run(self.arguments, self.content, self.options,
self.state_machine, self.state, self.lineno)
def setup(app):
import matplotlib
setup.app = app
setup.config = app.config
setup.confdir = app.confdir
app.add_directive('plot', PlotDirective)
app.add_config_value('plot_pre_code', None, True)
app.add_config_value('plot_include_source', False, True)
app.add_config_value('plot_html_show_source_link', True, True)
app.add_config_value('plot_formats', ['png', 'hires.png', 'pdf'], True)
app.add_config_value('plot_basedir', None, True)
app.add_config_value('plot_html_show_formats', True, True)
app.add_config_value('plot_rcparams', {}, True)
app.add_config_value('plot_apply_rcparams', False, True)
app.add_config_value('plot_working_directory', None, True)
app.add_config_value('plot_template', None, True)
app.connect('doctree-read', mark_plot_labels)
metadata = {'parallel_read_safe': True, 'parallel_write_safe': True,
'version': matplotlib.__version__}
return metadata
# -----------------------------------------------------------------------------
# Doctest handling
# -----------------------------------------------------------------------------
def contains_doctest(text):
try:
# check if it's valid Python as-is
compile(text, '<string>', 'exec')
return False
except SyntaxError:
pass
r = re.compile(r'^\s*>>>', re.M)
m = r.search(text)
return bool(m)
def unescape_doctest(text):
"""
Extract code from a piece of text, which contains either Python code
or doctests.
"""
if not contains_doctest(text):
return text
code = ""
for line in text.split("\n"):
m = re.match(r'^\s*(>>>|\.\.\.) (.*)$', line)
if m:
code += m.group(2) + "\n"
elif line.strip():
code += "# " + line.strip() + "\n"
else:
code += "\n"
return code
def split_code_at_show(text):
"""Split code at plt.show()."""
parts = []
is_doctest = contains_doctest(text)
part = []
for line in text.split("\n"):
if (not is_doctest and line.strip() == 'plt.show()') or \
(is_doctest and line.strip() == '>>> plt.show()'):
part.append(line)
parts.append("\n".join(part))
part = []
else:
part.append(line)
if "\n".join(part).strip():
parts.append("\n".join(part))
return parts
def remove_coding(text):
r"""Remove the coding comment, which six.exec\_ doesn't like."""
cbook.warn_deprecated('3.0', name='remove_coding', removal='3.1')
sub_re = re.compile(r"^#\s*-\*-\s*coding:\s*.*-\*-$", flags=re.MULTILINE)
return sub_re.sub("", text)
# -----------------------------------------------------------------------------
# Template
# -----------------------------------------------------------------------------
TEMPLATE = """
{{ source_code }}
{{ only_html }}
{% if source_link or (html_show_formats and not multi_image) %}
(
{%- if source_link -%}
`Source code <{{ source_link }}>`__
{%- endif -%}
{%- if html_show_formats and not multi_image -%}
{%- for img in images -%}
{%- for fmt in img.formats -%}
{%- if source_link or not loop.first -%}, {% endif -%}
`{{ fmt }} <{{ dest_dir }}/{{ img.basename }}.{{ fmt }}>`__
{%- endfor -%}
{%- endfor -%}
{%- endif -%}
)
{% endif %}
{% for img in images %}
.. figure:: {{ build_dir }}/{{ img.basename }}.{{ default_fmt }}
{% for option in options -%}
{{ option }}
{% endfor %}
{% if html_show_formats and multi_image -%}
(
{%- for fmt in img.formats -%}
{%- if not loop.first -%}, {% endif -%}
`{{ fmt }} <{{ dest_dir }}/{{ img.basename }}.{{ fmt }}>`__
{%- endfor -%}
)
{%- endif -%}
{{ caption }}
{% endfor %}
{{ only_latex }}
{% for img in images %}
{% if 'pdf' in img.formats -%}
.. figure:: {{ build_dir }}/{{ img.basename }}.pdf
{% for option in options -%}
{{ option }}
{% endfor %}
{{ caption }}
{% endif -%}
{% endfor %}
{{ only_texinfo }}
{% for img in images %}
{% if 'png' in img.formats -%}
.. image:: {{ build_dir }}/{{ img.basename }}.png
{% for option in options -%}
{{ option }}
{% endfor %}
{% endif -%}
{% endfor %}
"""
exception_template = """
.. only:: html
[`source code <%(linkdir)s/%(basename)s.py>`__]
Exception occurred rendering plot.
"""
# the context of the plot for all directives specified with the
# :context: option
plot_context = dict()
class ImageFile(object):
def __init__(self, basename, dirname):
self.basename = basename
self.dirname = dirname
self.formats = []
def filename(self, format):
return os.path.join(self.dirname, "%s.%s" % (self.basename, format))
def filenames(self):
return [self.filename(fmt) for fmt in self.formats]
def out_of_date(original, derived):
"""
Return whether *derived* is out-of-date relative to *original*, both of
which are full file paths.
"""
return (not os.path.exists(derived) or
(os.path.exists(original) and
os.stat(derived).st_mtime < os.stat(original).st_mtime))
class PlotError(RuntimeError):
pass
def run_code(code, code_path, ns=None, function_name=None):
"""
Import a Python module from a path, and run the function given by
name, if function_name is not None.
"""
# Change the working directory to the directory of the example, so
# it can get at its data files, if any. Add its path to sys.path
# so it can import any helper modules sitting beside it.
pwd = os.getcwd()
if setup.config.plot_working_directory is not None:
try:
os.chdir(setup.config.plot_working_directory)
except OSError as err:
raise OSError(str(err) + '\n`plot_working_directory` option in'
'Sphinx configuration file must be a valid '
'directory path')
except TypeError as err:
raise TypeError(str(err) + '\n`plot_working_directory` option in '
'Sphinx configuration file must be a string or '
'None')
elif code_path is not None:
dirname = os.path.abspath(os.path.dirname(code_path))
os.chdir(dirname)
with cbook._setattr_cm(
sys, argv=[code_path], path=[os.getcwd(), *sys.path]), \
contextlib.redirect_stdout(StringIO()):
try:
code = unescape_doctest(code)
if ns is None:
ns = {}
if not ns:
if setup.config.plot_pre_code is None:
exec('import numpy as np\n'
'from matplotlib import pyplot as plt\n', ns)
else:
exec(str(setup.config.plot_pre_code), ns)
if "__main__" in code:
ns['__name__'] = '__main__'
# Patch out non-interactive show() to avoid triggering a warning.
with cbook._setattr_cm(FigureManagerBase, show=lambda self: None):
exec(code, ns)
if function_name is not None:
exec(function_name + "()", ns)
except (Exception, SystemExit) as err:
raise PlotError(traceback.format_exc())
finally:
os.chdir(pwd)
return ns
def clear_state(plot_rcparams, close=True):
if close:
plt.close('all')
matplotlib.rc_file_defaults()
matplotlib.rcParams.update(plot_rcparams)
def get_plot_formats(config):
default_dpi = {'png': 80, 'hires.png': 200, 'pdf': 200}
formats = []
plot_formats = config.plot_formats
for fmt in plot_formats:
if isinstance(fmt, str):
if ':' in fmt:
suffix, dpi = fmt.split(':')
formats.append((str(suffix), int(dpi)))
else:
formats.append((fmt, default_dpi.get(fmt, 80)))
elif isinstance(fmt, (tuple, list)) and len(fmt) == 2:
formats.append((str(fmt[0]), int(fmt[1])))
else:
raise PlotError('invalid image format "%r" in plot_formats' % fmt)
return formats
def render_figures(code, code_path, output_dir, output_base, context,
function_name, config, context_reset=False,
close_figs=False):
"""
Run a pyplot script and save the images in *output_dir*.
Save the images under *output_dir* with file names derived from
*output_base*
"""
formats = get_plot_formats(config)
# -- Try to determine if all images already exist
code_pieces = split_code_at_show(code)
# Look for single-figure output files first
all_exists = True
img = ImageFile(output_base, output_dir)
if not any(out_of_date(code_path, img.filename(fmt))
for fmt, dpi in formats):
return [(code, [img])]
img.formats.extend(fmt for fmt, dpi in formats)
# Then look for multi-figure output files
results = []
all_exists = True
for i, code_piece in enumerate(code_pieces):
images = []
for j in itertools.count():
if len(code_pieces) > 1:
img = ImageFile('%s_%02d_%02d' % (output_base, i, j),
output_dir)
else:
img = ImageFile('%s_%02d' % (output_base, j), output_dir)
for format, dpi in formats:
if out_of_date(code_path, img.filename(format)):
all_exists = False
break
img.formats.append(format)
# assume that if we have one, we have them all
if not all_exists:
all_exists = (j > 0)
break
images.append(img)
if not all_exists:
break
results.append((code_piece, images))
if all_exists:
return results
# We didn't find the files, so build them
results = []
if context:
ns = plot_context
else:
ns = {}
if context_reset:
clear_state(config.plot_rcparams)
plot_context.clear()
close_figs = not context or close_figs
for i, code_piece in enumerate(code_pieces):
if not context or config.plot_apply_rcparams:
clear_state(config.plot_rcparams, close_figs)
elif close_figs:
plt.close('all')
run_code(code_piece, code_path, ns, function_name)
images = []
fig_managers = _pylab_helpers.Gcf.get_all_fig_managers()
for j, figman in enumerate(fig_managers):
if len(fig_managers) == 1 and len(code_pieces) == 1:
img = ImageFile(output_base, output_dir)
elif len(code_pieces) == 1:
img = ImageFile("%s_%02d" % (output_base, j), output_dir)
else:
img = ImageFile("%s_%02d_%02d" % (output_base, i, j),
output_dir)
images.append(img)
for format, dpi in formats:
try:
figman.canvas.figure.savefig(img.filename(format), dpi=dpi)
except Exception as err:
raise PlotError(traceback.format_exc())
img.formats.append(format)
results.append((code_piece, images))
if not context or config.plot_apply_rcparams:
clear_state(config.plot_rcparams, close=not context)
return results
def run(arguments, content, options, state_machine, state, lineno):
document = state_machine.document
config = document.settings.env.config
nofigs = 'nofigs' in options
formats = get_plot_formats(config)
default_fmt = formats[0][0]
options.setdefault('include-source', config.plot_include_source)
keep_context = 'context' in options
context_opt = None if not keep_context else options['context']
rst_file = document.attributes['source']
rst_dir = os.path.dirname(rst_file)
if len(arguments):
if not config.plot_basedir:
source_file_name = os.path.join(setup.app.builder.srcdir,
directives.uri(arguments[0]))
else:
source_file_name = os.path.join(setup.confdir, config.plot_basedir,
directives.uri(arguments[0]))
# If there is content, it will be passed as a caption.
caption = '\n'.join(content)
# If the optional function name is provided, use it
if len(arguments) == 2:
function_name = arguments[1]
else:
function_name = None
code = Path(source_file_name).read_text(encoding='utf-8')
output_base = os.path.basename(source_file_name)
else:
source_file_name = rst_file
code = textwrap.dedent("\n".join(map(str, content)))
counter = document.attributes.get('_plot_counter', 0) + 1
document.attributes['_plot_counter'] = counter
base, ext = os.path.splitext(os.path.basename(source_file_name))
output_base = '%s-%d.py' % (base, counter)
function_name = None
caption = ''
base, source_ext = os.path.splitext(output_base)
if source_ext in ('.py', '.rst', '.txt'):
output_base = base
else:
source_ext = ''
# ensure that LaTeX includegraphics doesn't choke in foo.bar.pdf filenames
output_base = output_base.replace('.', '-')
# is it in doctest format?
is_doctest = contains_doctest(code)
if 'format' in options:
if options['format'] == 'python':
is_doctest = False
else:
is_doctest = True
# determine output directory name fragment
source_rel_name = relpath(source_file_name, setup.confdir)
source_rel_dir = os.path.dirname(source_rel_name)
while source_rel_dir.startswith(os.path.sep):
source_rel_dir = source_rel_dir[1:]
# build_dir: where to place output files (temporarily)
build_dir = os.path.join(os.path.dirname(setup.app.doctreedir),
'plot_directive',
source_rel_dir)
# get rid of .. in paths, also changes pathsep
# see note in Python docs for warning about symbolic links on Windows.
# need to compare source and dest paths at end
build_dir = os.path.normpath(build_dir)
if not os.path.exists(build_dir):
os.makedirs(build_dir)
# output_dir: final location in the builder's directory
dest_dir = os.path.abspath(os.path.join(setup.app.builder.outdir,
source_rel_dir))
if not os.path.exists(dest_dir):
os.makedirs(dest_dir) # no problem here for me, but just use built-ins
# how to link to files from the RST file
dest_dir_link = os.path.join(relpath(setup.confdir, rst_dir),
source_rel_dir).replace(os.path.sep, '/')
try:
build_dir_link = relpath(build_dir, rst_dir).replace(os.path.sep, '/')
except ValueError:
# on Windows, relpath raises ValueError when path and start are on
# different mounts/drives
build_dir_link = build_dir
source_link = dest_dir_link + '/' + output_base + source_ext
# make figures
try:
results = render_figures(code,
source_file_name,
build_dir,
output_base,
keep_context,
function_name,
config,
context_reset=context_opt == 'reset',
close_figs=context_opt == 'close-figs')
errors = []
except PlotError as err:
reporter = state.memo.reporter
sm = reporter.system_message(
2, "Exception occurred in plotting {}\n from {}:\n{}".format(
output_base, source_file_name, err),
line=lineno)
results = [(code, [])]
errors = [sm]
# Properly indent the caption
caption = '\n'.join(' ' + line.strip()
for line in caption.split('\n'))
# generate output restructuredtext
total_lines = []
for j, (code_piece, images) in enumerate(results):
if options['include-source']:
if is_doctest:
lines = ['', *code_piece.splitlines()]
else:
lines = ['.. code-block:: python', '',
*textwrap.indent(code_piece, ' ').splitlines()]
source_code = "\n".join(lines)
else:
source_code = ""
if nofigs:
images = []
opts = [
':%s: %s' % (key, val) for key, val in options.items()
if key in ('alt', 'height', 'width', 'scale', 'align', 'class')]
only_html = ".. only:: html"
only_latex = ".. only:: latex"
only_texinfo = ".. only:: texinfo"
# Not-None src_link signals the need for a source link in the generated
# html
if j == 0 and config.plot_html_show_source_link:
src_link = source_link
else:
src_link = None
result = jinja2.Template(config.plot_template or TEMPLATE).render(
default_fmt=default_fmt,
dest_dir=dest_dir_link,
build_dir=build_dir_link,
source_link=src_link,
multi_image=len(images) > 1,
only_html=only_html,
only_latex=only_latex,
only_texinfo=only_texinfo,
options=opts,
images=images,
source_code=source_code,
html_show_formats=config.plot_html_show_formats and len(images),
caption=caption)
total_lines.extend(result.split("\n"))
total_lines.extend("\n")
if total_lines:
state_machine.insert_input(total_lines, source=source_file_name)
# copy image files to builder's output directory, if necessary
Path(dest_dir).mkdir(parents=True, exist_ok=True)
for code_piece, images in results:
for img in images:
for fn in img.filenames():
destimg = os.path.join(dest_dir, os.path.basename(fn))
if fn != destimg:
shutil.copyfile(fn, destimg)
# copy script (if necessary)
Path(dest_dir, output_base + source_ext).write_text(
unescape_doctest(code) if source_file_name == rst_file else code,
encoding='utf-8')
return errors
|
8d3ab005fc4b2c68f1fb84f0133c18be2d96742a09a6a1df0dc6cb2ab81c2acb
|
import hashlib
import os
import sys
from docutils import nodes
from docutils.parsers.rst import Directive, directives
import sphinx
from matplotlib import rcParams
from matplotlib import cbook
from matplotlib.mathtext import MathTextParser
rcParams['mathtext.fontset'] = 'cm'
mathtext_parser = MathTextParser("Bitmap")
# Define LaTeX math node:
class latex_math(nodes.General, nodes.Element):
pass
def fontset_choice(arg):
return directives.choice(arg, ['cm', 'stix', 'stixsans'])
def math_role(role, rawtext, text, lineno, inliner,
options={}, content=[]):
i = rawtext.find('`')
latex = rawtext[i+1:-1]
node = latex_math(rawtext)
node['latex'] = latex
node['fontset'] = options.get('fontset', 'cm')
return [node], []
math_role.options = {'fontset': fontset_choice}
@cbook.deprecated("3.1", alternative="MathDirective")
def math_directive(name, arguments, options, content, lineno,
content_offset, block_text, state, state_machine):
latex = ''.join(content)
node = latex_math(block_text)
node['latex'] = latex
node['fontset'] = options.get('fontset', 'cm')
return [node]
class MathDirective(Directive):
has_content = True
required_arguments = 0
optional_arguments = 0
final_argument_whitespace = False
option_spec = {'fontset': fontset_choice}
def run(self):
latex = ''.join(self.content)
node = latex_math(self.block_text)
node['latex'] = latex
node['fontset'] = self.options.get('fontset', 'cm')
return [node]
# This uses mathtext to render the expression
def latex2png(latex, filename, fontset='cm'):
latex = "$%s$" % latex
orig_fontset = rcParams['mathtext.fontset']
rcParams['mathtext.fontset'] = fontset
if os.path.exists(filename):
depth = mathtext_parser.get_depth(latex, dpi=100)
else:
try:
depth = mathtext_parser.to_png(filename, latex, dpi=100)
except Exception:
cbook._warn_external("Could not render math expression %s" % latex,
Warning)
depth = 0
rcParams['mathtext.fontset'] = orig_fontset
sys.stdout.write("#")
sys.stdout.flush()
return depth
# LaTeX to HTML translation stuff:
def latex2html(node, source):
inline = isinstance(node.parent, nodes.TextElement)
latex = node['latex']
name = 'math-%s' % hashlib.md5(latex.encode()).hexdigest()[-10:]
destdir = os.path.join(setup.app.builder.outdir, '_images', 'mathmpl')
if not os.path.exists(destdir):
os.makedirs(destdir)
dest = os.path.join(destdir, '%s.png' % name)
path = '/'.join((setup.app.builder.imgpath, 'mathmpl'))
depth = latex2png(latex, dest, node['fontset'])
if inline:
cls = ''
else:
cls = 'class="center" '
if inline and depth != 0:
style = 'style="position: relative; bottom: -%dpx"' % (depth + 1)
else:
style = ''
return '<img src="%s/%s.png" %s%s/>' % (path, name, cls, style)
def setup(app):
setup.app = app
# Add visit/depart methods to HTML-Translator:
def visit_latex_math_html(self, node):
source = self.document.attributes['source']
self.body.append(latex2html(node, source))
def depart_latex_math_html(self, node):
pass
# Add visit/depart methods to LaTeX-Translator:
def visit_latex_math_latex(self, node):
inline = isinstance(node.parent, nodes.TextElement)
if inline:
self.body.append('$%s$' % node['latex'])
else:
self.body.extend(['\\begin{equation}',
node['latex'],
'\\end{equation}'])
def depart_latex_math_latex(self, node):
pass
app.add_node(latex_math,
html=(visit_latex_math_html, depart_latex_math_html),
latex=(visit_latex_math_latex, depart_latex_math_latex))
app.add_role('mathmpl', math_role)
app.add_directive('mathmpl', MathDirective)
if sphinx.version_info < (1, 8):
app.add_role('math', math_role)
app.add_directive('math', MathDirective)
metadata = {'parallel_read_safe': True, 'parallel_write_safe': True}
return metadata
|
bca542efa4021eba6ccb6da9e19fd5c7651945f8803d4dd0afb7f076b7feb313
|
"""
Displays Agg images in the browser, with interactivity
"""
# The WebAgg backend is divided into two modules:
#
# - `backend_webagg_core.py` contains code necessary to embed a WebAgg
# plot inside of a web application, and communicate in an abstract
# way over a web socket.
#
# - `backend_webagg.py` contains a concrete implementation of a basic
# application, implemented with tornado.
from contextlib import contextmanager
import errno
from io import BytesIO
import json
from pathlib import Path
import random
import sys
import signal
import socket
import threading
try:
import tornado
except ImportError:
raise RuntimeError("The WebAgg backend requires Tornado.")
import tornado.web
import tornado.ioloop
import tornado.websocket
from matplotlib import rcParams
from matplotlib.backend_bases import _Backend
from matplotlib._pylab_helpers import Gcf
from . import backend_webagg_core as core
from .backend_webagg_core import TimerTornado
class ServerThread(threading.Thread):
def run(self):
tornado.ioloop.IOLoop.instance().start()
webagg_server_thread = ServerThread()
class FigureCanvasWebAgg(core.FigureCanvasWebAggCore):
def show(self):
# show the figure window
global show # placates pyflakes: created by @_Backend.export below
show()
def new_timer(self, *args, **kwargs):
# docstring inherited
return TimerTornado(*args, **kwargs)
class WebAggApplication(tornado.web.Application):
initialized = False
started = False
class FavIcon(tornado.web.RequestHandler):
def get(self):
self.set_header('Content-Type', 'image/png')
image_path = Path(rcParams["datapath"], "images", "matplotlib.png")
self.write(image_path.read_bytes())
class SingleFigurePage(tornado.web.RequestHandler):
def __init__(self, application, request, *, url_prefix='', **kwargs):
self.url_prefix = url_prefix
super().__init__(application, request, **kwargs)
def get(self, fignum):
fignum = int(fignum)
manager = Gcf.get_fig_manager(fignum)
ws_uri = 'ws://{req.host}{prefix}/'.format(req=self.request,
prefix=self.url_prefix)
self.render(
"single_figure.html",
prefix=self.url_prefix,
ws_uri=ws_uri,
fig_id=fignum,
toolitems=core.NavigationToolbar2WebAgg.toolitems,
canvas=manager.canvas)
class AllFiguresPage(tornado.web.RequestHandler):
def __init__(self, application, request, *, url_prefix='', **kwargs):
self.url_prefix = url_prefix
super().__init__(application, request, **kwargs)
def get(self):
ws_uri = 'ws://{req.host}{prefix}/'.format(req=self.request,
prefix=self.url_prefix)
self.render(
"all_figures.html",
prefix=self.url_prefix,
ws_uri=ws_uri,
figures=sorted(Gcf.figs.items()),
toolitems=core.NavigationToolbar2WebAgg.toolitems)
class MplJs(tornado.web.RequestHandler):
def get(self):
self.set_header('Content-Type', 'application/javascript')
js_content = core.FigureManagerWebAgg.get_javascript()
self.write(js_content)
class Download(tornado.web.RequestHandler):
def get(self, fignum, fmt):
fignum = int(fignum)
manager = Gcf.get_fig_manager(fignum)
# TODO: Move this to a central location
mimetypes = {
'ps': 'application/postscript',
'eps': 'application/postscript',
'pdf': 'application/pdf',
'svg': 'image/svg+xml',
'png': 'image/png',
'jpeg': 'image/jpeg',
'tif': 'image/tiff',
'emf': 'application/emf'
}
self.set_header('Content-Type', mimetypes.get(fmt, 'binary'))
buff = BytesIO()
manager.canvas.figure.savefig(buff, format=fmt)
self.write(buff.getvalue())
class WebSocket(tornado.websocket.WebSocketHandler):
supports_binary = True
def open(self, fignum):
self.fignum = int(fignum)
self.manager = Gcf.get_fig_manager(self.fignum)
self.manager.add_web_socket(self)
if hasattr(self, 'set_nodelay'):
self.set_nodelay(True)
def on_close(self):
self.manager.remove_web_socket(self)
def on_message(self, message):
message = json.loads(message)
# The 'supports_binary' message is on a client-by-client
# basis. The others affect the (shared) canvas as a
# whole.
if message['type'] == 'supports_binary':
self.supports_binary = message['value']
else:
manager = Gcf.get_fig_manager(self.fignum)
# It is possible for a figure to be closed,
# but a stale figure UI is still sending messages
# from the browser.
if manager is not None:
manager.handle_json(message)
def send_json(self, content):
self.write_message(json.dumps(content))
def send_binary(self, blob):
if self.supports_binary:
self.write_message(blob, binary=True)
else:
data_uri = "data:image/png;base64,{0}".format(
blob.encode('base64').replace('\n', ''))
self.write_message(data_uri)
def __init__(self, url_prefix=''):
if url_prefix:
assert url_prefix[0] == '/' and url_prefix[-1] != '/', \
'url_prefix must start with a "/" and not end with one.'
super().__init__(
[
# Static files for the CSS and JS
(url_prefix + r'/_static/(.*)',
tornado.web.StaticFileHandler,
{'path': core.FigureManagerWebAgg.get_static_file_path()}),
# An MPL favicon
(url_prefix + r'/favicon.ico', self.FavIcon),
# The page that contains all of the pieces
(url_prefix + r'/([0-9]+)', self.SingleFigurePage,
{'url_prefix': url_prefix}),
# The page that contains all of the figures
(url_prefix + r'/?', self.AllFiguresPage,
{'url_prefix': url_prefix}),
(url_prefix + r'/js/mpl.js', self.MplJs),
# Sends images and events to the browser, and receives
# events from the browser
(url_prefix + r'/([0-9]+)/ws', self.WebSocket),
# Handles the downloading (i.e., saving) of static images
(url_prefix + r'/([0-9]+)/download.([a-z0-9.]+)',
self.Download),
],
template_path=core.FigureManagerWebAgg.get_static_file_path())
@classmethod
def initialize(cls, url_prefix='', port=None, address=None):
if cls.initialized:
return
# Create the class instance
app = cls(url_prefix=url_prefix)
cls.url_prefix = url_prefix
# This port selection algorithm is borrowed, more or less
# verbatim, from IPython.
def random_ports(port, n):
"""
Generate a list of n random ports near the given port.
The first 5 ports will be sequential, and the remaining n-5 will be
randomly selected in the range [port-2*n, port+2*n].
"""
for i in range(min(5, n)):
yield port + i
for i in range(n - 5):
yield port + random.randint(-2 * n, 2 * n)
if address is None:
cls.address = rcParams['webagg.address']
else:
cls.address = address
cls.port = rcParams['webagg.port']
for port in random_ports(cls.port, rcParams['webagg.port_retries']):
try:
app.listen(port, cls.address)
except socket.error as e:
if e.errno != errno.EADDRINUSE:
raise
else:
cls.port = port
break
else:
raise SystemExit(
"The webagg server could not be started because an available "
"port could not be found")
cls.initialized = True
@classmethod
def start(cls):
if cls.started:
return
"""
IOLoop.running() was removed as of Tornado 2.4; see for example
https://groups.google.com/forum/#!topic/python-tornado/QLMzkpQBGOY
Thus there is no correct way to check if the loop has already been
launched. We may end up with two concurrently running loops in that
unlucky case with all the expected consequences.
"""
ioloop = tornado.ioloop.IOLoop.instance()
def shutdown():
ioloop.stop()
print("Server is stopped")
sys.stdout.flush()
cls.started = False
@contextmanager
def catch_sigint():
old_handler = signal.signal(
signal.SIGINT,
lambda sig, frame: ioloop.add_callback_from_signal(shutdown))
try:
yield
finally:
signal.signal(signal.SIGINT, old_handler)
# Set the flag to True *before* blocking on ioloop.start()
cls.started = True
print("Press Ctrl+C to stop WebAgg server")
sys.stdout.flush()
with catch_sigint():
ioloop.start()
def ipython_inline_display(figure):
import tornado.template
WebAggApplication.initialize()
if not webagg_server_thread.is_alive():
webagg_server_thread.start()
fignum = figure.number
tpl = Path(core.FigureManagerWebAgg.get_static_file_path(),
"ipython_inline_figure.html").read_text()
t = tornado.template.Template(tpl)
return t.generate(
prefix=WebAggApplication.url_prefix,
fig_id=fignum,
toolitems=core.NavigationToolbar2WebAgg.toolitems,
canvas=figure.canvas,
port=WebAggApplication.port).decode('utf-8')
@_Backend.export
class _BackendWebAgg(_Backend):
FigureCanvas = FigureCanvasWebAgg
FigureManager = core.FigureManagerWebAgg
@staticmethod
def trigger_manager_draw(manager):
manager.canvas.draw_idle()
@staticmethod
def show():
WebAggApplication.initialize()
url = "http://{address}:{port}{prefix}".format(
address=WebAggApplication.address,
port=WebAggApplication.port,
prefix=WebAggApplication.url_prefix)
if rcParams['webagg.open_in_browser']:
import webbrowser
webbrowser.open(url)
else:
print("To view figure, visit {0}".format(url))
WebAggApplication.start()
|
2e9421b1aec678f22b2104d6b73bf2d33a645046c55848a199542e123560a20d
|
"""
A PDF matplotlib backend
Author: Jouni K Seppänen <[email protected]>
"""
import codecs
import collections
from datetime import datetime
from functools import total_ordering
from io import BytesIO
import logging
import math
import os
import pathlib
import re
import struct
import time
import types
import warnings
import zlib
import numpy as np
from matplotlib import cbook, __version__, rcParams
from matplotlib._pylab_helpers import Gcf
from matplotlib.backend_bases import (
_Backend, FigureCanvasBase, FigureManagerBase, GraphicsContextBase,
RendererBase)
from matplotlib.backends.backend_mixed import MixedModeRenderer
from matplotlib.figure import Figure
from matplotlib.font_manager import findfont, is_opentype_cff_font, get_font
from matplotlib.afm import AFM
import matplotlib.type1font as type1font
import matplotlib.dviread as dviread
from matplotlib.ft2font import (FIXED_WIDTH, ITALIC, LOAD_NO_SCALE,
LOAD_NO_HINTING, KERNING_UNFITTED)
from matplotlib.mathtext import MathTextParser
from matplotlib.transforms import Affine2D, BboxBase
from matplotlib.path import Path
from matplotlib.dates import UTC
from matplotlib import _path
from matplotlib import _png
from matplotlib import ttconv
from . import _backend_pdf_ps
_log = logging.getLogger(__name__)
# Overview
#
# The low-level knowledge about pdf syntax lies mainly in the pdfRepr
# function and the classes Reference, Name, Operator, and Stream. The
# PdfFile class knows about the overall structure of pdf documents.
# It provides a "write" method for writing arbitrary strings in the
# file, and an "output" method that passes objects through the pdfRepr
# function before writing them in the file. The output method is
# called by the RendererPdf class, which contains the various draw_foo
# methods. RendererPdf contains a GraphicsContextPdf instance, and
# each draw_foo calls self.check_gc before outputting commands. This
# method checks whether the pdf graphics state needs to be modified
# and outputs the necessary commands. GraphicsContextPdf represents
# the graphics state, and its "delta" method returns the commands that
# modify the state.
# Add "pdf.use14corefonts: True" in your configuration file to use only
# the 14 PDF core fonts. These fonts do not need to be embedded; every
# PDF viewing application is required to have them. This results in very
# light PDF files you can use directly in LaTeX or ConTeXt documents
# generated with pdfTeX, without any conversion.
# These fonts are: Helvetica, Helvetica-Bold, Helvetica-Oblique,
# Helvetica-BoldOblique, Courier, Courier-Bold, Courier-Oblique,
# Courier-BoldOblique, Times-Roman, Times-Bold, Times-Italic,
# Times-BoldItalic, Symbol, ZapfDingbats.
#
# Some tricky points:
#
# 1. The clip path can only be widened by popping from the state
# stack. Thus the state must be pushed onto the stack before narrowing
# the clip path. This is taken care of by GraphicsContextPdf.
#
# 2. Sometimes it is necessary to refer to something (e.g., font,
# image, or extended graphics state, which contains the alpha value)
# in the page stream by a name that needs to be defined outside the
# stream. PdfFile provides the methods fontName, imageObject, and
# alphaState for this purpose. The implementations of these methods
# should perhaps be generalized.
# TODOs:
#
# * encoding of fonts, including mathtext fonts and unicode support
# * TTF support has lots of small TODOs, e.g., how do you know if a font
# is serif/sans-serif, or symbolic/non-symbolic?
# * draw_markers, draw_line_collection, etc.
def fill(strings, linelen=75):
"""Make one string from sequence of strings, with whitespace
in between. The whitespace is chosen to form lines of at most
linelen characters, if possible."""
currpos = 0
lasti = 0
result = []
for i, s in enumerate(strings):
length = len(s)
if currpos + length < linelen:
currpos += length + 1
else:
result.append(b' '.join(strings[lasti:i]))
lasti = i
currpos = length
result.append(b' '.join(strings[lasti:]))
return b'\n'.join(result)
# PDF strings are supposed to be able to include any eight-bit data,
# except that unbalanced parens and backslashes must be escaped by a
# backslash. However, sf bug #2708559 shows that the carriage return
# character may get read as a newline; these characters correspond to
# \gamma and \Omega in TeX's math font encoding. Escaping them fixes
# the bug.
_string_escape_regex = re.compile(br'([\\()\r\n])')
def _string_escape(match):
m = match.group(0)
if m in br'\()':
return b'\\' + m
elif m == b'\n':
return br'\n'
elif m == b'\r':
return br'\r'
assert False
def pdfRepr(obj):
"""Map Python objects to PDF syntax."""
# Some objects defined later have their own pdfRepr method.
if hasattr(obj, 'pdfRepr'):
return obj.pdfRepr()
# Floats. PDF does not have exponential notation (1.0e-10) so we
# need to use %f with some precision. Perhaps the precision
# should adapt to the magnitude of the number?
elif isinstance(obj, (float, np.floating)):
if not np.isfinite(obj):
raise ValueError("Can only output finite numbers in PDF")
r = b"%.10f" % obj
return r.rstrip(b'0').rstrip(b'.')
# Booleans. Needs to be tested before integers since
# isinstance(True, int) is true.
elif isinstance(obj, bool):
return [b'false', b'true'][obj]
# Integers are written as such.
elif isinstance(obj, (int, np.integer)):
return b"%d" % obj
# Unicode strings are encoded in UTF-16BE with byte-order mark.
elif isinstance(obj, str):
try:
# But maybe it's really ASCII?
s = obj.encode('ASCII')
return pdfRepr(s)
except UnicodeEncodeError:
s = codecs.BOM_UTF16_BE + obj.encode('UTF-16BE')
return pdfRepr(s)
# Strings are written in parentheses, with backslashes and parens
# escaped. Actually balanced parens are allowed, but it is
# simpler to escape them all. TODO: cut long strings into lines;
# I believe there is some maximum line length in PDF.
elif isinstance(obj, bytes):
return b'(' + _string_escape_regex.sub(_string_escape, obj) + b')'
# Dictionaries. The keys must be PDF names, so if we find strings
# there, we make Name objects from them. The values may be
# anything, so the caller must ensure that PDF names are
# represented as Name objects.
elif isinstance(obj, dict):
r = [b"<<"]
r.extend([Name(key).pdfRepr() + b" " + pdfRepr(obj[key])
for key in sorted(obj)])
r.append(b">>")
return fill(r)
# Lists.
elif isinstance(obj, (list, tuple)):
r = [b"["]
r.extend([pdfRepr(val) for val in obj])
r.append(b"]")
return fill(r)
# The null keyword.
elif obj is None:
return b'null'
# A date.
elif isinstance(obj, datetime):
r = obj.strftime('D:%Y%m%d%H%M%S')
z = obj.utcoffset()
if z is not None:
z = z.seconds
else:
if time.daylight:
z = time.altzone
else:
z = time.timezone
if z == 0:
r += 'Z'
elif z < 0:
r += "+%02d'%02d'" % ((-z) // 3600, (-z) % 3600)
else:
r += "-%02d'%02d'" % (z // 3600, z % 3600)
return pdfRepr(r)
# A bounding box
elif isinstance(obj, BboxBase):
return fill([pdfRepr(val) for val in obj.bounds])
else:
raise TypeError("Don't know a PDF representation for {} objects"
.format(type(obj)))
class Reference(object):
"""PDF reference object.
Use PdfFile.reserveObject() to create References.
"""
def __init__(self, id):
self.id = id
def __repr__(self):
return "<Reference %d>" % self.id
def pdfRepr(self):
return b"%d 0 R" % self.id
def write(self, contents, file):
write = file.write
write(b"%d 0 obj\n" % self.id)
write(pdfRepr(contents))
write(b"\nendobj\n")
@total_ordering
class Name(object):
"""PDF name object."""
__slots__ = ('name',)
_regex = re.compile(r'[^!-~]')
def __init__(self, name):
if isinstance(name, Name):
self.name = name.name
else:
if isinstance(name, bytes):
name = name.decode('ascii')
self.name = self._regex.sub(Name.hexify, name).encode('ascii')
def __repr__(self):
return "<Name %s>" % self.name
def __str__(self):
return '/' + str(self.name)
def __eq__(self, other):
return isinstance(other, Name) and self.name == other.name
def __lt__(self, other):
return isinstance(other, Name) and self.name < other.name
def __hash__(self):
return hash(self.name)
@staticmethod
def hexify(match):
return '#%02x' % ord(match.group())
def pdfRepr(self):
return b'/' + self.name
class Operator(object):
"""PDF operator object."""
__slots__ = ('op',)
def __init__(self, op):
self.op = op
def __repr__(self):
return '<Operator %s>' % self.op
def pdfRepr(self):
return self.op
class Verbatim(object):
"""Store verbatim PDF command content for later inclusion in the
stream."""
def __init__(self, x):
self._x = x
def pdfRepr(self):
return self._x
# PDF operators (not an exhaustive list)
_pdfops = dict(
close_fill_stroke=b'b', fill_stroke=b'B', fill=b'f', closepath=b'h',
close_stroke=b's', stroke=b'S', endpath=b'n', begin_text=b'BT',
end_text=b'ET', curveto=b'c', rectangle=b're', lineto=b'l', moveto=b'm',
concat_matrix=b'cm', use_xobject=b'Do', setgray_stroke=b'G',
setgray_nonstroke=b'g', setrgb_stroke=b'RG', setrgb_nonstroke=b'rg',
setcolorspace_stroke=b'CS', setcolorspace_nonstroke=b'cs',
setcolor_stroke=b'SCN', setcolor_nonstroke=b'scn', setdash=b'd',
setlinejoin=b'j', setlinecap=b'J', setgstate=b'gs', gsave=b'q',
grestore=b'Q', textpos=b'Td', selectfont=b'Tf', textmatrix=b'Tm',
show=b'Tj', showkern=b'TJ', setlinewidth=b'w', clip=b'W', shading=b'sh')
Op = types.SimpleNamespace(**{name: Operator(value)
for name, value in _pdfops.items()})
def _paint_path(fill, stroke):
"""Return the PDF operator to paint a path in the following way:
fill: fill the path with the fill color
stroke: stroke the outline of the path with the line color"""
if stroke:
if fill:
return Op.fill_stroke
else:
return Op.stroke
else:
if fill:
return Op.fill
else:
return Op.endpath
Op.paint_path = _paint_path
class Stream(object):
"""PDF stream object.
This has no pdfRepr method. Instead, call begin(), then output the
contents of the stream by calling write(), and finally call end().
"""
__slots__ = ('id', 'len', 'pdfFile', 'file', 'compressobj', 'extra', 'pos')
def __init__(self, id, len, file, extra=None, png=None):
"""id: object id of stream; len: an unused Reference object for the
length of the stream, or None (to use a memory buffer); file:
a PdfFile; extra: a dictionary of extra key-value pairs to
include in the stream header; png: if the data is already
png compressed, the decode parameters"""
self.id = id # object id
self.len = len # id of length object
self.pdfFile = file
self.file = file.fh # file to which the stream is written
self.compressobj = None # compression object
if extra is None:
self.extra = dict()
else:
self.extra = extra.copy()
if png is not None:
self.extra.update({'Filter': Name('FlateDecode'),
'DecodeParms': png})
self.pdfFile.recordXref(self.id)
if rcParams['pdf.compression'] and not png:
self.compressobj = zlib.compressobj(rcParams['pdf.compression'])
if self.len is None:
self.file = BytesIO()
else:
self._writeHeader()
self.pos = self.file.tell()
def _writeHeader(self):
write = self.file.write
write(b"%d 0 obj\n" % self.id)
dict = self.extra
dict['Length'] = self.len
if rcParams['pdf.compression']:
dict['Filter'] = Name('FlateDecode')
write(pdfRepr(dict))
write(b"\nstream\n")
def end(self):
"""Finalize stream."""
self._flush()
if self.len is None:
contents = self.file.getvalue()
self.len = len(contents)
self.file = self.pdfFile.fh
self._writeHeader()
self.file.write(contents)
self.file.write(b"\nendstream\nendobj\n")
else:
length = self.file.tell() - self.pos
self.file.write(b"\nendstream\nendobj\n")
self.pdfFile.writeObject(self.len, length)
def write(self, data):
"""Write some data on the stream."""
if self.compressobj is None:
self.file.write(data)
else:
compressed = self.compressobj.compress(data)
self.file.write(compressed)
def _flush(self):
"""Flush the compression object."""
if self.compressobj is not None:
compressed = self.compressobj.flush()
self.file.write(compressed)
self.compressobj = None
class PdfFile(object):
"""PDF file object."""
def __init__(self, filename, metadata=None):
self.nextObject = 1 # next free object id
self.xrefTable = [[0, 65535, 'the zero object']]
self.passed_in_file_object = False
self.original_file_like = None
self.tell_base = 0
fh, opened = cbook.to_filehandle(filename, "wb", return_opened=True)
if not opened:
try:
self.tell_base = filename.tell()
except IOError:
fh = BytesIO()
self.original_file_like = filename
else:
fh = filename
self.passed_in_file_object = True
self._core14fontdir = os.path.join(
rcParams['datapath'], 'fonts', 'pdfcorefonts')
self.fh = fh
self.currentstream = None # stream object to write to, if any
fh.write(b"%PDF-1.4\n") # 1.4 is the first version to have alpha
# Output some eight-bit chars as a comment so various utilities
# recognize the file as binary by looking at the first few
# lines (see note in section 3.4.1 of the PDF reference).
fh.write(b"%\254\334 \253\272\n")
self.rootObject = self.reserveObject('root')
self.pagesObject = self.reserveObject('pages')
self.pageList = []
self.fontObject = self.reserveObject('fonts')
self.alphaStateObject = self.reserveObject('extended graphics states')
self.hatchObject = self.reserveObject('tiling patterns')
self.gouraudObject = self.reserveObject('Gouraud triangles')
self.XObjectObject = self.reserveObject('external objects')
self.resourceObject = self.reserveObject('resources')
root = {'Type': Name('Catalog'),
'Pages': self.pagesObject}
self.writeObject(self.rootObject, root)
# get source date from SOURCE_DATE_EPOCH, if set
# See https://reproducible-builds.org/specs/source-date-epoch/
source_date_epoch = os.getenv("SOURCE_DATE_EPOCH")
if source_date_epoch:
source_date = datetime.utcfromtimestamp(int(source_date_epoch))
source_date = source_date.replace(tzinfo=UTC)
else:
source_date = datetime.today()
self.infoDict = {
'Creator': 'matplotlib %s, http://matplotlib.org' % __version__,
'Producer': 'matplotlib pdf backend %s' % __version__,
'CreationDate': source_date
}
if metadata is not None:
self.infoDict.update(metadata)
self.infoDict = {k: v for (k, v) in self.infoDict.items()
if v is not None}
self.fontNames = {} # maps filenames to internal font names
self.nextFont = 1 # next free internal font name
self.dviFontInfo = {} # maps dvi font names to embedding information
# differently encoded Type-1 fonts may share the same descriptor
self.type1Descriptors = {}
self.used_characters = {}
self.alphaStates = {} # maps alpha values to graphics state objects
self.nextAlphaState = 1
# reproducible writeHatches needs an ordered dict:
self.hatchPatterns = collections.OrderedDict()
self.nextHatch = 1
self.gouraudTriangles = []
self._images = collections.OrderedDict() # reproducible writeImages
self.nextImage = 1
self.markers = collections.OrderedDict() # reproducible writeMarkers
self.multi_byte_charprocs = {}
self.paths = []
self.pageAnnotations = [] # A list of annotations for the
# current page
# The PDF spec recommends to include every procset
procsets = [Name(x)
for x in "PDF Text ImageB ImageC ImageI".split()]
# Write resource dictionary.
# Possibly TODO: more general ExtGState (graphics state dictionaries)
# ColorSpace Pattern Shading Properties
resources = {'Font': self.fontObject,
'XObject': self.XObjectObject,
'ExtGState': self.alphaStateObject,
'Pattern': self.hatchObject,
'Shading': self.gouraudObject,
'ProcSet': procsets}
self.writeObject(self.resourceObject, resources)
def newPage(self, width, height):
self.endStream()
self.width, self.height = width, height
contentObject = self.reserveObject('page contents')
thePage = {'Type': Name('Page'),
'Parent': self.pagesObject,
'Resources': self.resourceObject,
'MediaBox': [0, 0, 72 * width, 72 * height],
'Contents': contentObject,
'Group': {'Type': Name('Group'),
'S': Name('Transparency'),
'CS': Name('DeviceRGB')},
'Annots': self.pageAnnotations,
}
pageObject = self.reserveObject('page')
self.writeObject(pageObject, thePage)
self.pageList.append(pageObject)
self.beginStream(contentObject.id,
self.reserveObject('length of content stream'))
# Initialize the pdf graphics state to match the default mpl
# graphics context: currently only the join style needs to be set
self.output(GraphicsContextPdf.joinstyles['round'], Op.setlinejoin)
# Clear the list of annotations for the next page
self.pageAnnotations = []
def newTextnote(self, text, positionRect=[-100, -100, 0, 0]):
# Create a new annotation of type text
theNote = {'Type': Name('Annot'),
'Subtype': Name('Text'),
'Contents': text,
'Rect': positionRect,
}
annotObject = self.reserveObject('annotation')
self.writeObject(annotObject, theNote)
self.pageAnnotations.append(annotObject)
def finalize(self):
"Write out the various deferred objects and the pdf end matter."
self.endStream()
self.writeFonts()
self.writeObject(
self.alphaStateObject,
{val[0]: val[1] for val in self.alphaStates.values()})
self.writeHatches()
self.writeGouraudTriangles()
xobjects = {
name: ob for image, name, ob in self._images.values()}
for tup in self.markers.values():
xobjects[tup[0]] = tup[1]
for name, value in self.multi_byte_charprocs.items():
xobjects[name] = value
for name, path, trans, ob, join, cap, padding, filled, stroked \
in self.paths:
xobjects[name] = ob
self.writeObject(self.XObjectObject, xobjects)
self.writeImages()
self.writeMarkers()
self.writePathCollectionTemplates()
self.writeObject(self.pagesObject,
{'Type': Name('Pages'),
'Kids': self.pageList,
'Count': len(self.pageList)})
self.writeInfoDict()
# Finalize the file
self.writeXref()
self.writeTrailer()
def close(self):
"Flush all buffers and free all resources."
self.endStream()
if self.passed_in_file_object:
self.fh.flush()
else:
if self.original_file_like is not None:
self.original_file_like.write(self.fh.getvalue())
self.fh.close()
def write(self, data):
if self.currentstream is None:
self.fh.write(data)
else:
self.currentstream.write(data)
def output(self, *data):
self.write(fill([pdfRepr(x) for x in data]))
self.write(b'\n')
def beginStream(self, id, len, extra=None, png=None):
assert self.currentstream is None
self.currentstream = Stream(id, len, self, extra, png)
def endStream(self):
if self.currentstream is not None:
self.currentstream.end()
self.currentstream = None
def fontName(self, fontprop):
"""
Select a font based on fontprop and return a name suitable for
Op.selectfont. If fontprop is a string, it will be interpreted
as the filename of the font.
"""
if isinstance(fontprop, str):
filename = fontprop
elif rcParams['pdf.use14corefonts']:
filename = findfont(
fontprop, fontext='afm', directory=self._core14fontdir)
if filename is None:
filename = findfont(
"Helvetica", fontext='afm', directory=self._core14fontdir)
else:
filename = findfont(fontprop)
Fx = self.fontNames.get(filename)
if Fx is None:
Fx = Name('F%d' % self.nextFont)
self.fontNames[filename] = Fx
self.nextFont += 1
_log.debug('Assigning font %s = %r', Fx, filename)
return Fx
@cbook.deprecated("3.0")
@property
def texFontMap(self):
# lazy-load texFontMap, it takes a while to parse
# and usetex is a relatively rare use case
return dviread.PsfontsMap(dviread.find_tex_file('pdftex.map'))
def dviFontName(self, dvifont):
"""
Given a dvi font object, return a name suitable for Op.selectfont.
This registers the font information in self.dviFontInfo if not yet
registered.
"""
dvi_info = self.dviFontInfo.get(dvifont.texname)
if dvi_info is not None:
return dvi_info.pdfname
tex_font_map = dviread.PsfontsMap(dviread.find_tex_file('pdftex.map'))
psfont = tex_font_map[dvifont.texname]
if psfont.filename is None:
raise ValueError(
"No usable font file found for {} (TeX: {}); "
"the font may lack a Type-1 version"
.format(psfont.psname, dvifont.texname))
pdfname = Name('F%d' % self.nextFont)
self.nextFont += 1
_log.debug('Assigning font %s = %s (dvi)', pdfname, dvifont.texname)
self.dviFontInfo[dvifont.texname] = types.SimpleNamespace(
dvifont=dvifont,
pdfname=pdfname,
fontfile=psfont.filename,
basefont=psfont.psname,
encodingfile=psfont.encoding,
effects=psfont.effects)
return pdfname
def writeFonts(self):
fonts = {}
for dviname, info in sorted(self.dviFontInfo.items()):
Fx = info.pdfname
_log.debug('Embedding Type-1 font %s from dvi.', dviname)
fonts[Fx] = self._embedTeXFont(info)
for filename in sorted(self.fontNames):
Fx = self.fontNames[filename]
_log.debug('Embedding font %s.', filename)
if filename.endswith('.afm'):
# from pdf.use14corefonts
_log.debug('Writing AFM font.')
fonts[Fx] = self._write_afm_font(filename)
else:
# a normal TrueType font
_log.debug('Writing TrueType font.')
realpath, stat_key = cbook.get_realpath_and_stat(filename)
chars = self.used_characters.get(stat_key)
if chars is not None and len(chars[1]):
fonts[Fx] = self.embedTTF(realpath, chars[1])
self.writeObject(self.fontObject, fonts)
def _write_afm_font(self, filename):
with open(filename, 'rb') as fh:
font = AFM(fh)
fontname = font.get_fontname()
fontdict = {'Type': Name('Font'),
'Subtype': Name('Type1'),
'BaseFont': Name(fontname),
'Encoding': Name('WinAnsiEncoding')}
fontdictObject = self.reserveObject('font dictionary')
self.writeObject(fontdictObject, fontdict)
return fontdictObject
def _embedTeXFont(self, fontinfo):
_log.debug('Embedding TeX font %s - fontinfo=%s',
fontinfo.dvifont.texname, fontinfo.__dict__)
# Widths
widthsObject = self.reserveObject('font widths')
self.writeObject(widthsObject, fontinfo.dvifont.widths)
# Font dictionary
fontdictObject = self.reserveObject('font dictionary')
fontdict = {
'Type': Name('Font'),
'Subtype': Name('Type1'),
'FirstChar': 0,
'LastChar': len(fontinfo.dvifont.widths) - 1,
'Widths': widthsObject,
}
# Encoding (if needed)
if fontinfo.encodingfile is not None:
enc = dviread.Encoding(fontinfo.encodingfile)
differencesArray = [Name(ch) for ch in enc]
differencesArray = [0] + differencesArray
fontdict['Encoding'] = \
{'Type': Name('Encoding'),
'Differences': differencesArray}
# If no file is specified, stop short
if fontinfo.fontfile is None:
_log.warning(
"Because of TeX configuration (pdftex.map, see updmap option "
"pdftexDownloadBase14) the font %s is not embedded. This is "
"deprecated as of PDF 1.5 and it may cause the consumer "
"application to show something that was not intended.",
fontinfo.basefont)
fontdict['BaseFont'] = Name(fontinfo.basefont)
self.writeObject(fontdictObject, fontdict)
return fontdictObject
# We have a font file to embed - read it in and apply any effects
t1font = type1font.Type1Font(fontinfo.fontfile)
if fontinfo.effects:
t1font = t1font.transform(fontinfo.effects)
fontdict['BaseFont'] = Name(t1font.prop['FontName'])
# Font descriptors may be shared between differently encoded
# Type-1 fonts, so only create a new descriptor if there is no
# existing descriptor for this font.
effects = (fontinfo.effects.get('slant', 0.0),
fontinfo.effects.get('extend', 1.0))
fontdesc = self.type1Descriptors.get((fontinfo.fontfile, effects))
if fontdesc is None:
fontdesc = self.createType1Descriptor(t1font, fontinfo.fontfile)
self.type1Descriptors[(fontinfo.fontfile, effects)] = fontdesc
fontdict['FontDescriptor'] = fontdesc
self.writeObject(fontdictObject, fontdict)
return fontdictObject
def createType1Descriptor(self, t1font, fontfile):
# Create and write the font descriptor and the font file
# of a Type-1 font
fontdescObject = self.reserveObject('font descriptor')
fontfileObject = self.reserveObject('font file')
italic_angle = t1font.prop['ItalicAngle']
fixed_pitch = t1font.prop['isFixedPitch']
flags = 0
# fixed width
if fixed_pitch:
flags |= 1 << 0
# TODO: serif
if 0:
flags |= 1 << 1
# TODO: symbolic (most TeX fonts are)
if 1:
flags |= 1 << 2
# non-symbolic
else:
flags |= 1 << 5
# italic
if italic_angle:
flags |= 1 << 6
# TODO: all caps
if 0:
flags |= 1 << 16
# TODO: small caps
if 0:
flags |= 1 << 17
# TODO: force bold
if 0:
flags |= 1 << 18
ft2font = get_font(fontfile)
descriptor = {
'Type': Name('FontDescriptor'),
'FontName': Name(t1font.prop['FontName']),
'Flags': flags,
'FontBBox': ft2font.bbox,
'ItalicAngle': italic_angle,
'Ascent': ft2font.ascender,
'Descent': ft2font.descender,
'CapHeight': 1000, # TODO: find this out
'XHeight': 500, # TODO: this one too
'FontFile': fontfileObject,
'FontFamily': t1font.prop['FamilyName'],
'StemV': 50, # TODO
# (see also revision 3874; but not all TeX distros have AFM files!)
# 'FontWeight': a number where 400 = Regular, 700 = Bold
}
self.writeObject(fontdescObject, descriptor)
self.beginStream(fontfileObject.id, None,
{'Length1': len(t1font.parts[0]),
'Length2': len(t1font.parts[1]),
'Length3': 0})
self.currentstream.write(t1font.parts[0])
self.currentstream.write(t1font.parts[1])
self.endStream()
return fontdescObject
def _get_xobject_symbol_name(self, filename, symbol_name):
return "%s-%s" % (
os.path.splitext(os.path.basename(filename))[0],
symbol_name)
_identityToUnicodeCMap = b"""/CIDInit /ProcSet findresource begin
12 dict begin
begincmap
/CIDSystemInfo
<< /Registry (Adobe)
/Ordering (UCS)
/Supplement 0
>> def
/CMapName /Adobe-Identity-UCS def
/CMapType 2 def
1 begincodespacerange
<0000> <ffff>
endcodespacerange
%d beginbfrange
%s
endbfrange
endcmap
CMapName currentdict /CMap defineresource pop
end
end"""
def embedTTF(self, filename, characters):
"""Embed the TTF font from the named file into the document."""
font = get_font(filename)
fonttype = rcParams['pdf.fonttype']
def cvt(length, upe=font.units_per_EM, nearest=True):
"Convert font coordinates to PDF glyph coordinates"
value = length / upe * 1000
if nearest:
return np.round(value)
# Perhaps best to round away from zero for bounding
# boxes and the like
if value < 0:
return math.floor(value)
else:
return math.ceil(value)
def embedTTFType3(font, characters, descriptor):
"""The Type 3-specific part of embedding a Truetype font"""
widthsObject = self.reserveObject('font widths')
fontdescObject = self.reserveObject('font descriptor')
fontdictObject = self.reserveObject('font dictionary')
charprocsObject = self.reserveObject('character procs')
differencesArray = []
firstchar, lastchar = 0, 255
bbox = [cvt(x, nearest=False) for x in font.bbox]
fontdict = {
'Type': Name('Font'),
'BaseFont': ps_name,
'FirstChar': firstchar,
'LastChar': lastchar,
'FontDescriptor': fontdescObject,
'Subtype': Name('Type3'),
'Name': descriptor['FontName'],
'FontBBox': bbox,
'FontMatrix': [.001, 0, 0, .001, 0, 0],
'CharProcs': charprocsObject,
'Encoding': {
'Type': Name('Encoding'),
'Differences': differencesArray},
'Widths': widthsObject
}
# Make the "Widths" array
from encodings import cp1252
# The "decoding_map" was changed
# to a "decoding_table" as of Python 2.5.
if hasattr(cp1252, 'decoding_map'):
def decode_char(charcode):
return cp1252.decoding_map[charcode] or 0
else:
def decode_char(charcode):
return ord(cp1252.decoding_table[charcode])
def get_char_width(charcode):
s = decode_char(charcode)
width = font.load_char(
s, flags=LOAD_NO_SCALE | LOAD_NO_HINTING).horiAdvance
return cvt(width)
with warnings.catch_warnings():
# Ignore 'Required glyph missing from current font' warning
# from ft2font: here we're just building the widths table, but
# the missing glyphs may not even be used in the actual string.
warnings.filterwarnings("ignore")
widths = [get_char_width(charcode)
for charcode in range(firstchar, lastchar+1)]
descriptor['MaxWidth'] = max(widths)
# Make the "Differences" array, sort the ccodes < 255 from
# the multi-byte ccodes, and build the whole set of glyph ids
# that we need from this font.
glyph_ids = []
differences = []
multi_byte_chars = set()
for c in characters:
ccode = c
gind = font.get_char_index(ccode)
glyph_ids.append(gind)
glyph_name = font.get_glyph_name(gind)
if ccode <= 255:
differences.append((ccode, glyph_name))
else:
multi_byte_chars.add(glyph_name)
differences.sort()
last_c = -2
for c, name in differences:
if c != last_c + 1:
differencesArray.append(c)
differencesArray.append(Name(name))
last_c = c
# Make the charprocs array (using ttconv to generate the
# actual outlines)
try:
rawcharprocs = ttconv.get_pdf_charprocs(
os.fsencode(filename), glyph_ids)
except RuntimeError:
_log.warning("The PDF backend does not currently support the "
"selected font.")
raise
charprocs = {}
for charname in sorted(rawcharprocs):
stream = rawcharprocs[charname]
charprocDict = {'Length': len(stream)}
# The 2-byte characters are used as XObjects, so they
# need extra info in their dictionary
if charname in multi_byte_chars:
charprocDict['Type'] = Name('XObject')
charprocDict['Subtype'] = Name('Form')
charprocDict['BBox'] = bbox
# Each glyph includes bounding box information,
# but xpdf and ghostscript can't handle it in a
# Form XObject (they segfault!!!), so we remove it
# from the stream here. It's not needed anyway,
# since the Form XObject includes it in its BBox
# value.
stream = stream[stream.find(b"d1") + 2:]
charprocObject = self.reserveObject('charProc')
self.beginStream(charprocObject.id, None, charprocDict)
self.currentstream.write(stream)
self.endStream()
# Send the glyphs with ccode > 255 to the XObject dictionary,
# and the others to the font itself
if charname in multi_byte_chars:
name = self._get_xobject_symbol_name(filename, charname)
self.multi_byte_charprocs[name] = charprocObject
else:
charprocs[charname] = charprocObject
# Write everything out
self.writeObject(fontdictObject, fontdict)
self.writeObject(fontdescObject, descriptor)
self.writeObject(widthsObject, widths)
self.writeObject(charprocsObject, charprocs)
return fontdictObject
def embedTTFType42(font, characters, descriptor):
"""The Type 42-specific part of embedding a Truetype font"""
fontdescObject = self.reserveObject('font descriptor')
cidFontDictObject = self.reserveObject('CID font dictionary')
type0FontDictObject = self.reserveObject('Type 0 font dictionary')
cidToGidMapObject = self.reserveObject('CIDToGIDMap stream')
fontfileObject = self.reserveObject('font file stream')
wObject = self.reserveObject('Type 0 widths')
toUnicodeMapObject = self.reserveObject('ToUnicode map')
cidFontDict = {
'Type': Name('Font'),
'Subtype': Name('CIDFontType2'),
'BaseFont': ps_name,
'CIDSystemInfo': {
'Registry': 'Adobe',
'Ordering': 'Identity',
'Supplement': 0},
'FontDescriptor': fontdescObject,
'W': wObject,
'CIDToGIDMap': cidToGidMapObject
}
type0FontDict = {
'Type': Name('Font'),
'Subtype': Name('Type0'),
'BaseFont': ps_name,
'Encoding': Name('Identity-H'),
'DescendantFonts': [cidFontDictObject],
'ToUnicode': toUnicodeMapObject
}
# Make fontfile stream
descriptor['FontFile2'] = fontfileObject
length1Object = self.reserveObject('decoded length of a font')
self.beginStream(
fontfileObject.id,
self.reserveObject('length of font stream'),
{'Length1': length1Object})
with open(filename, 'rb') as fontfile:
length1 = 0
while True:
data = fontfile.read(4096)
if not data:
break
length1 += len(data)
self.currentstream.write(data)
self.endStream()
self.writeObject(length1Object, length1)
# Make the 'W' (Widths) array, CidToGidMap and ToUnicode CMap
# at the same time
cid_to_gid_map = ['\0'] * 65536
widths = []
max_ccode = 0
for c in characters:
ccode = c
gind = font.get_char_index(ccode)
glyph = font.load_char(ccode,
flags=LOAD_NO_SCALE | LOAD_NO_HINTING)
widths.append((ccode, cvt(glyph.horiAdvance)))
if ccode < 65536:
cid_to_gid_map[ccode] = chr(gind)
max_ccode = max(ccode, max_ccode)
widths.sort()
cid_to_gid_map = cid_to_gid_map[:max_ccode + 1]
last_ccode = -2
w = []
max_width = 0
unicode_groups = []
for ccode, width in widths:
if ccode != last_ccode + 1:
w.append(ccode)
w.append([width])
unicode_groups.append([ccode, ccode])
else:
w[-1].append(width)
unicode_groups[-1][1] = ccode
max_width = max(max_width, width)
last_ccode = ccode
unicode_bfrange = []
for start, end in unicode_groups:
unicode_bfrange.append(
b"<%04x> <%04x> [%s]" %
(start, end,
b" ".join(b"<%04x>" % x for x in range(start, end+1))))
unicode_cmap = (self._identityToUnicodeCMap %
(len(unicode_groups), b"\n".join(unicode_bfrange)))
# CIDToGIDMap stream
cid_to_gid_map = "".join(cid_to_gid_map).encode("utf-16be")
self.beginStream(cidToGidMapObject.id,
None,
{'Length': len(cid_to_gid_map)})
self.currentstream.write(cid_to_gid_map)
self.endStream()
# ToUnicode CMap
self.beginStream(toUnicodeMapObject.id,
None,
{'Length': unicode_cmap})
self.currentstream.write(unicode_cmap)
self.endStream()
descriptor['MaxWidth'] = max_width
# Write everything out
self.writeObject(cidFontDictObject, cidFontDict)
self.writeObject(type0FontDictObject, type0FontDict)
self.writeObject(fontdescObject, descriptor)
self.writeObject(wObject, w)
return type0FontDictObject
# Beginning of main embedTTF function...
ps_name = font.postscript_name.encode('ascii', 'replace')
ps_name = Name(ps_name)
pclt = font.get_sfnt_table('pclt') or {'capHeight': 0, 'xHeight': 0}
post = font.get_sfnt_table('post') or {'italicAngle': (0, 0)}
ff = font.face_flags
sf = font.style_flags
flags = 0
symbolic = False # ps_name.name in ('Cmsy10', 'Cmmi10', 'Cmex10')
if ff & FIXED_WIDTH:
flags |= 1 << 0
if 0: # TODO: serif
flags |= 1 << 1
if symbolic:
flags |= 1 << 2
else:
flags |= 1 << 5
if sf & ITALIC:
flags |= 1 << 6
if 0: # TODO: all caps
flags |= 1 << 16
if 0: # TODO: small caps
flags |= 1 << 17
if 0: # TODO: force bold
flags |= 1 << 18
descriptor = {
'Type': Name('FontDescriptor'),
'FontName': ps_name,
'Flags': flags,
'FontBBox': [cvt(x, nearest=False) for x in font.bbox],
'Ascent': cvt(font.ascender, nearest=False),
'Descent': cvt(font.descender, nearest=False),
'CapHeight': cvt(pclt['capHeight'], nearest=False),
'XHeight': cvt(pclt['xHeight']),
'ItalicAngle': post['italicAngle'][1], # ???
'StemV': 0 # ???
}
# The font subsetting to a Type 3 font does not work for
# OpenType (.otf) that embed a Postscript CFF font, so avoid that --
# save as a (non-subsetted) Type 42 font instead.
if is_opentype_cff_font(filename):
fonttype = 42
_log.warning("%r can not be subsetted into a Type 3 font. The "
"entire font will be embedded in the output.",
os.path.basename(filename))
if fonttype == 3:
return embedTTFType3(font, characters, descriptor)
elif fonttype == 42:
return embedTTFType42(font, characters, descriptor)
def alphaState(self, alpha):
"""Return name of an ExtGState that sets alpha to the given value."""
state = self.alphaStates.get(alpha, None)
if state is not None:
return state[0]
name = Name('A%d' % self.nextAlphaState)
self.nextAlphaState += 1
self.alphaStates[alpha] = \
(name, {'Type': Name('ExtGState'),
'CA': alpha[0], 'ca': alpha[1]})
return name
def hatchPattern(self, hatch_style):
# The colors may come in as numpy arrays, which aren't hashable
if hatch_style is not None:
edge, face, hatch = hatch_style
if edge is not None:
edge = tuple(edge)
if face is not None:
face = tuple(face)
hatch_style = (edge, face, hatch)
pattern = self.hatchPatterns.get(hatch_style, None)
if pattern is not None:
return pattern
name = Name('H%d' % self.nextHatch)
self.nextHatch += 1
self.hatchPatterns[hatch_style] = name
return name
def writeHatches(self):
hatchDict = dict()
sidelen = 72.0
for hatch_style, name in self.hatchPatterns.items():
ob = self.reserveObject('hatch pattern')
hatchDict[name] = ob
res = {'Procsets':
[Name(x) for x in "PDF Text ImageB ImageC ImageI".split()]}
self.beginStream(
ob.id, None,
{'Type': Name('Pattern'),
'PatternType': 1, 'PaintType': 1, 'TilingType': 1,
'BBox': [0, 0, sidelen, sidelen],
'XStep': sidelen, 'YStep': sidelen,
'Resources': res,
# Change origin to match Agg at top-left.
'Matrix': [1, 0, 0, 1, 0, self.height * 72]})
stroke_rgb, fill_rgb, path = hatch_style
self.output(stroke_rgb[0], stroke_rgb[1], stroke_rgb[2],
Op.setrgb_stroke)
if fill_rgb is not None:
self.output(fill_rgb[0], fill_rgb[1], fill_rgb[2],
Op.setrgb_nonstroke,
0, 0, sidelen, sidelen, Op.rectangle,
Op.fill)
self.output(rcParams['hatch.linewidth'], Op.setlinewidth)
self.output(*self.pathOperations(
Path.hatch(path),
Affine2D().scale(sidelen),
simplify=False))
self.output(Op.fill_stroke)
self.endStream()
self.writeObject(self.hatchObject, hatchDict)
def addGouraudTriangles(self, points, colors):
name = Name('GT%d' % len(self.gouraudTriangles))
self.gouraudTriangles.append((name, points, colors))
return name
def writeGouraudTriangles(self):
gouraudDict = dict()
for name, points, colors in self.gouraudTriangles:
ob = self.reserveObject('Gouraud triangle')
gouraudDict[name] = ob
shape = points.shape
flat_points = points.reshape((shape[0] * shape[1], 2))
flat_colors = colors.reshape((shape[0] * shape[1], 4))
points_min = np.min(flat_points, axis=0) - (1 << 8)
points_max = np.max(flat_points, axis=0) + (1 << 8)
factor = 0xffffffff / (points_max - points_min)
self.beginStream(
ob.id, None,
{'ShadingType': 4,
'BitsPerCoordinate': 32,
'BitsPerComponent': 8,
'BitsPerFlag': 8,
'ColorSpace': Name('DeviceRGB'),
'AntiAlias': True,
'Decode': [points_min[0], points_max[0],
points_min[1], points_max[1],
0, 1, 0, 1, 0, 1]
})
streamarr = np.empty(
(shape[0] * shape[1],),
dtype=[('flags', 'u1'),
('points', '>u4', (2,)),
('colors', 'u1', (3,))])
streamarr['flags'] = 0
streamarr['points'] = (flat_points - points_min) * factor
streamarr['colors'] = flat_colors[:, :3] * 255.0
self.write(streamarr.tostring())
self.endStream()
self.writeObject(self.gouraudObject, gouraudDict)
def imageObject(self, image):
"""Return name of an image XObject representing the given image."""
entry = self._images.get(id(image), None)
if entry is not None:
return entry[1]
name = Name('I%d' % self.nextImage)
ob = self.reserveObject('image %d' % self.nextImage)
self.nextImage += 1
self._images[id(image)] = (image, name, ob)
return name
def _unpack(self, im):
"""
Unpack the image object im into height, width, data, alpha,
where data and alpha are HxWx3 (RGB) or HxWx1 (grayscale or alpha)
arrays, except alpha is None if the image is fully opaque.
"""
h, w = im.shape[:2]
im = im[::-1]
if im.ndim == 2:
return h, w, im, None
else:
rgb = im[:, :, :3]
rgb = np.array(rgb, order='C')
# PDF needs a separate alpha image
if im.shape[2] == 4:
alpha = im[:, :, 3][..., None]
if np.all(alpha == 255):
alpha = None
else:
alpha = np.array(alpha, order='C')
else:
alpha = None
return h, w, rgb, alpha
def _writePng(self, data):
"""
Write the image *data* into the pdf file using png
predictors with Flate compression.
"""
buffer = BytesIO()
_png.write_png(data, buffer)
buffer.seek(8)
while True:
length, type = struct.unpack(b'!L4s', buffer.read(8))
if type == b'IDAT':
data = buffer.read(length)
if len(data) != length:
raise RuntimeError("truncated data")
self.currentstream.write(data)
elif type == b'IEND':
break
else:
buffer.seek(length, 1)
buffer.seek(4, 1) # skip CRC
def _writeImg(self, data, height, width, grayscale, id, smask=None):
"""
Write the image *data* of size *height* x *width*, as grayscale
if *grayscale* is true and RGB otherwise, as pdf object *id*
and with the soft mask (alpha channel) *smask*, which should be
either None or a *height* x *width* x 1 array.
"""
obj = {'Type': Name('XObject'),
'Subtype': Name('Image'),
'Width': width,
'Height': height,
'ColorSpace': Name('DeviceGray' if grayscale
else 'DeviceRGB'),
'BitsPerComponent': 8}
if smask:
obj['SMask'] = smask
if rcParams['pdf.compression']:
png = {'Predictor': 10,
'Colors': 1 if grayscale else 3,
'Columns': width}
else:
png = None
self.beginStream(
id,
self.reserveObject('length of image stream'),
obj,
png=png
)
if png:
self._writePng(data)
else:
self.currentstream.write(data.tostring())
self.endStream()
def writeImages(self):
for img, name, ob in self._images.values():
height, width, data, adata = self._unpack(img)
if adata is not None:
smaskObject = self.reserveObject("smask")
self._writeImg(adata, height, width, True, smaskObject.id)
else:
smaskObject = None
self._writeImg(data, height, width, False,
ob.id, smaskObject)
def markerObject(self, path, trans, fill, stroke, lw, joinstyle,
capstyle):
"""Return name of a marker XObject representing the given path."""
# self.markers used by markerObject, writeMarkers, close:
# mapping from (path operations, fill?, stroke?) to
# [name, object reference, bounding box, linewidth]
# This enables different draw_markers calls to share the XObject
# if the gc is sufficiently similar: colors etc can vary, but
# the choices of whether to fill and whether to stroke cannot.
# We need a bounding box enclosing all of the XObject path,
# but since line width may vary, we store the maximum of all
# occurring line widths in self.markers.
# close() is somewhat tightly coupled in that it expects the
# first two components of each value in self.markers to be the
# name and object reference.
pathops = self.pathOperations(path, trans, simplify=False)
key = (tuple(pathops), bool(fill), bool(stroke), joinstyle, capstyle)
result = self.markers.get(key)
if result is None:
name = Name('M%d' % len(self.markers))
ob = self.reserveObject('marker %d' % len(self.markers))
bbox = path.get_extents(trans)
self.markers[key] = [name, ob, bbox, lw]
else:
if result[-1] < lw:
result[-1] = lw
name = result[0]
return name
def writeMarkers(self):
for ((pathops, fill, stroke, joinstyle, capstyle),
(name, ob, bbox, lw)) in self.markers.items():
bbox = bbox.padded(lw * 0.5)
self.beginStream(
ob.id, None,
{'Type': Name('XObject'), 'Subtype': Name('Form'),
'BBox': list(bbox.extents)})
self.output(GraphicsContextPdf.joinstyles[joinstyle],
Op.setlinejoin)
self.output(GraphicsContextPdf.capstyles[capstyle], Op.setlinecap)
self.output(*pathops)
self.output(Op.paint_path(fill, stroke))
self.endStream()
def pathCollectionObject(self, gc, path, trans, padding, filled, stroked):
name = Name('P%d' % len(self.paths))
ob = self.reserveObject('path %d' % len(self.paths))
self.paths.append(
(name, path, trans, ob, gc.get_joinstyle(), gc.get_capstyle(),
padding, filled, stroked))
return name
def writePathCollectionTemplates(self):
for (name, path, trans, ob, joinstyle, capstyle, padding, filled,
stroked) in self.paths:
pathops = self.pathOperations(path, trans, simplify=False)
bbox = path.get_extents(trans)
if not np.all(np.isfinite(bbox.extents)):
extents = [0, 0, 0, 0]
else:
bbox = bbox.padded(padding)
extents = list(bbox.extents)
self.beginStream(
ob.id, None,
{'Type': Name('XObject'), 'Subtype': Name('Form'),
'BBox': extents})
self.output(GraphicsContextPdf.joinstyles[joinstyle],
Op.setlinejoin)
self.output(GraphicsContextPdf.capstyles[capstyle], Op.setlinecap)
self.output(*pathops)
self.output(Op.paint_path(filled, stroked))
self.endStream()
@staticmethod
def pathOperations(path, transform, clip=None, simplify=None, sketch=None):
return [Verbatim(_path.convert_to_string(
path, transform, clip, simplify, sketch,
6,
[Op.moveto.op, Op.lineto.op, b'', Op.curveto.op, Op.closepath.op],
True))]
def writePath(self, path, transform, clip=False, sketch=None):
if clip:
clip = (0.0, 0.0, self.width * 72, self.height * 72)
simplify = path.should_simplify
else:
clip = None
simplify = False
cmds = self.pathOperations(path, transform, clip, simplify=simplify,
sketch=sketch)
self.output(*cmds)
def reserveObject(self, name=''):
"""Reserve an ID for an indirect object.
The name is used for debugging in case we forget to print out
the object with writeObject.
"""
id = self.nextObject
self.nextObject += 1
self.xrefTable.append([None, 0, name])
return Reference(id)
def recordXref(self, id):
self.xrefTable[id][0] = self.fh.tell() - self.tell_base
def writeObject(self, object, contents):
self.recordXref(object.id)
object.write(contents, self)
def writeXref(self):
"""Write out the xref table."""
self.startxref = self.fh.tell() - self.tell_base
self.write(b"xref\n0 %d\n" % self.nextObject)
for i, (offset, generation, name) in enumerate(self.xrefTable):
if offset is None:
raise AssertionError(
'No offset for object %d (%s)' % (i, name))
else:
key = b"f" if name == 'the zero object' else b"n"
text = b"%010d %05d %b \n" % (offset, generation, key)
self.write(text)
def writeInfoDict(self):
"""Write out the info dictionary, checking it for good form"""
def is_string_like(x):
return isinstance(x, str)
def is_date(x):
return isinstance(x, datetime)
check_trapped = (lambda x: isinstance(x, Name) and
x.name in ('True', 'False', 'Unknown'))
keywords = {'Title': is_string_like,
'Author': is_string_like,
'Subject': is_string_like,
'Keywords': is_string_like,
'Creator': is_string_like,
'Producer': is_string_like,
'CreationDate': is_date,
'ModDate': is_date,
'Trapped': check_trapped}
for k in self.infoDict:
if k not in keywords:
cbook._warn_external('Unknown infodict keyword: %s' % k)
else:
if not keywords[k](self.infoDict[k]):
cbook._warn_external(
'Bad value for infodict keyword %s' % k)
self.infoObject = self.reserveObject('info')
self.writeObject(self.infoObject, self.infoDict)
def writeTrailer(self):
"""Write out the PDF trailer."""
self.write(b"trailer\n")
self.write(pdfRepr(
{'Size': self.nextObject,
'Root': self.rootObject,
'Info': self.infoObject}))
# Could add 'ID'
self.write(b"\nstartxref\n%d\n%%%%EOF\n" % self.startxref)
class RendererPdf(_backend_pdf_ps.RendererPDFPSBase):
@property
@cbook.deprecated("3.1")
def afm_font_cache(self, _cache=cbook.maxdict(50)):
return _cache
_afm_font_dir = pathlib.Path(rcParams["datapath"], "fonts", "pdfcorefonts")
_use_afm_rc_name = "pdf.use14corefonts"
def __init__(self, file, image_dpi, height, width):
RendererBase.__init__(self)
self.height = height
self.width = width
self.file = file
self.gc = self.new_gc()
self.mathtext_parser = MathTextParser("Pdf")
self.image_dpi = image_dpi
def finalize(self):
self.file.output(*self.gc.finalize())
def check_gc(self, gc, fillcolor=None):
orig_fill = getattr(gc, '_fillcolor', (0., 0., 0.))
gc._fillcolor = fillcolor
orig_alphas = getattr(gc, '_effective_alphas', (1.0, 1.0))
if gc.get_rgb() is None:
# It should not matter what color here since linewidth should be
# 0 unless affected by global settings in rcParams, hence setting
# zero alpha just in case.
gc.set_foreground((0, 0, 0, 0), isRGBA=True)
if gc._forced_alpha:
gc._effective_alphas = (gc._alpha, gc._alpha)
elif fillcolor is None or len(fillcolor) < 4:
gc._effective_alphas = (gc._rgb[3], 1.0)
else:
gc._effective_alphas = (gc._rgb[3], fillcolor[3])
delta = self.gc.delta(gc)
if delta:
self.file.output(*delta)
# Restore gc to avoid unwanted side effects
gc._fillcolor = orig_fill
gc._effective_alphas = orig_alphas
def track_characters(self, font, s):
"""Keeps track of which characters are required from each font."""
if isinstance(font, str):
fname = font
else:
fname = font.fname
realpath, stat_key = cbook.get_realpath_and_stat(fname)
used_characters = self.file.used_characters.setdefault(
stat_key, (realpath, set()))
used_characters[1].update(map(ord, s))
def merge_used_characters(self, other):
for stat_key, (realpath, charset) in other.items():
used_characters = self.file.used_characters.setdefault(
stat_key, (realpath, set()))
used_characters[1].update(charset)
def get_image_magnification(self):
return self.image_dpi/72.0
def draw_image(self, gc, x, y, im, transform=None):
# docstring inherited
h, w = im.shape[:2]
if w == 0 or h == 0:
return
if transform is None:
# If there's no transform, alpha has already been applied
gc.set_alpha(1.0)
self.check_gc(gc)
w = 72.0 * w / self.image_dpi
h = 72.0 * h / self.image_dpi
imob = self.file.imageObject(im)
if transform is None:
self.file.output(Op.gsave,
w, 0, 0, h, x, y, Op.concat_matrix,
imob, Op.use_xobject, Op.grestore)
else:
tr1, tr2, tr3, tr4, tr5, tr6 = transform.frozen().to_values()
self.file.output(Op.gsave,
1, 0, 0, 1, x, y, Op.concat_matrix,
tr1, tr2, tr3, tr4, tr5, tr6, Op.concat_matrix,
imob, Op.use_xobject, Op.grestore)
def draw_path(self, gc, path, transform, rgbFace=None):
# docstring inherited
self.check_gc(gc, rgbFace)
self.file.writePath(
path, transform,
rgbFace is None and gc.get_hatch_path() is None,
gc.get_sketch_params())
self.file.output(self.gc.paint())
def draw_path_collection(self, gc, master_transform, paths, all_transforms,
offsets, offsetTrans, facecolors, edgecolors,
linewidths, linestyles, antialiaseds, urls,
offset_position):
# We can only reuse the objects if the presence of fill and
# stroke (and the amount of alpha for each) is the same for
# all of them
can_do_optimization = True
facecolors = np.asarray(facecolors)
edgecolors = np.asarray(edgecolors)
if not len(facecolors):
filled = False
can_do_optimization = not gc.get_hatch()
else:
if np.all(facecolors[:, 3] == facecolors[0, 3]):
filled = facecolors[0, 3] != 0.0
else:
can_do_optimization = False
if not len(edgecolors):
stroked = False
else:
if np.all(np.asarray(linewidths) == 0.0):
stroked = False
elif np.all(edgecolors[:, 3] == edgecolors[0, 3]):
stroked = edgecolors[0, 3] != 0.0
else:
can_do_optimization = False
# Is the optimization worth it? Rough calculation:
# cost of emitting a path in-line is len_path * uses_per_path
# cost of XObject is len_path + 5 for the definition,
# uses_per_path for the uses
len_path = len(paths[0].vertices) if len(paths) > 0 else 0
uses_per_path = self._iter_collection_uses_per_path(
paths, all_transforms, offsets, facecolors, edgecolors)
should_do_optimization = \
len_path + uses_per_path + 5 < len_path * uses_per_path
if (not can_do_optimization) or (not should_do_optimization):
return RendererBase.draw_path_collection(
self, gc, master_transform, paths, all_transforms,
offsets, offsetTrans, facecolors, edgecolors,
linewidths, linestyles, antialiaseds, urls,
offset_position)
padding = np.max(linewidths)
path_codes = []
for i, (path, transform) in enumerate(self._iter_collection_raw_paths(
master_transform, paths, all_transforms)):
name = self.file.pathCollectionObject(
gc, path, transform, padding, filled, stroked)
path_codes.append(name)
output = self.file.output
output(*self.gc.push())
lastx, lasty = 0, 0
for xo, yo, path_id, gc0, rgbFace in self._iter_collection(
gc, master_transform, all_transforms, path_codes, offsets,
offsetTrans, facecolors, edgecolors, linewidths, linestyles,
antialiaseds, urls, offset_position):
self.check_gc(gc0, rgbFace)
dx, dy = xo - lastx, yo - lasty
output(1, 0, 0, 1, dx, dy, Op.concat_matrix, path_id,
Op.use_xobject)
lastx, lasty = xo, yo
output(*self.gc.pop())
def draw_markers(self, gc, marker_path, marker_trans, path, trans,
rgbFace=None):
# docstring inherited
# Same logic as in draw_path_collection
len_marker_path = len(marker_path)
uses = len(path)
if len_marker_path * uses < len_marker_path + uses + 5:
RendererBase.draw_markers(self, gc, marker_path, marker_trans,
path, trans, rgbFace)
return
self.check_gc(gc, rgbFace)
fill = gc.fill(rgbFace)
stroke = gc.stroke()
output = self.file.output
marker = self.file.markerObject(
marker_path, marker_trans, fill, stroke, self.gc._linewidth,
gc.get_joinstyle(), gc.get_capstyle())
output(Op.gsave)
lastx, lasty = 0, 0
for vertices, code in path.iter_segments(
trans,
clip=(0, 0, self.file.width*72, self.file.height*72),
simplify=False):
if len(vertices):
x, y = vertices[-2:]
if not (0 <= x <= self.file.width * 72
and 0 <= y <= self.file.height * 72):
continue
dx, dy = x - lastx, y - lasty
output(1, 0, 0, 1, dx, dy, Op.concat_matrix,
marker, Op.use_xobject)
lastx, lasty = x, y
output(Op.grestore)
def draw_gouraud_triangle(self, gc, points, colors, trans):
self.draw_gouraud_triangles(gc, points.reshape((1, 3, 2)),
colors.reshape((1, 3, 4)), trans)
def draw_gouraud_triangles(self, gc, points, colors, trans):
assert len(points) == len(colors)
assert points.ndim == 3
assert points.shape[1] == 3
assert points.shape[2] == 2
assert colors.ndim == 3
assert colors.shape[1] == 3
assert colors.shape[2] == 4
shape = points.shape
points = points.reshape((shape[0] * shape[1], 2))
tpoints = trans.transform(points)
tpoints = tpoints.reshape(shape)
name = self.file.addGouraudTriangles(tpoints, colors)
self.check_gc(gc)
self.file.output(name, Op.shading)
def _setup_textpos(self, x, y, angle, oldx=0, oldy=0, oldangle=0):
if angle == oldangle == 0:
self.file.output(x - oldx, y - oldy, Op.textpos)
else:
angle = math.radians(angle)
self.file.output(math.cos(angle), math.sin(angle),
-math.sin(angle), math.cos(angle),
x, y, Op.textmatrix)
self.file.output(0, 0, Op.textpos)
def draw_mathtext(self, gc, x, y, s, prop, angle):
# TODO: fix positioning and encoding
width, height, descent, glyphs, rects, used_characters = \
self.mathtext_parser.parse(s, 72, prop)
self.merge_used_characters(used_characters)
# When using Type 3 fonts, we can't use character codes higher
# than 255, so we use the "Do" command to render those
# instead.
global_fonttype = rcParams['pdf.fonttype']
# Set up a global transformation matrix for the whole math expression
a = math.radians(angle)
self.file.output(Op.gsave)
self.file.output(math.cos(a), math.sin(a),
-math.sin(a), math.cos(a),
x, y, Op.concat_matrix)
self.check_gc(gc, gc._rgb)
self.file.output(Op.begin_text)
prev_font = None, None
oldx, oldy = 0, 0
for ox, oy, fontname, fontsize, num, symbol_name in glyphs:
if is_opentype_cff_font(fontname):
fonttype = 42
else:
fonttype = global_fonttype
if fonttype == 42 or num <= 255:
self._setup_textpos(ox, oy, 0, oldx, oldy)
oldx, oldy = ox, oy
if (fontname, fontsize) != prev_font:
self.file.output(self.file.fontName(fontname), fontsize,
Op.selectfont)
prev_font = fontname, fontsize
self.file.output(self.encode_string(chr(num), fonttype),
Op.show)
self.file.output(Op.end_text)
# If using Type 3 fonts, render all of the multi-byte characters
# as XObjects using the 'Do' command.
if global_fonttype == 3:
for ox, oy, fontname, fontsize, num, symbol_name in glyphs:
if is_opentype_cff_font(fontname):
fonttype = 42
else:
fonttype = global_fonttype
if fonttype == 3 and num > 255:
self.file.fontName(fontname)
self.file.output(Op.gsave,
0.001 * fontsize, 0,
0, 0.001 * fontsize,
ox, oy, Op.concat_matrix)
name = self.file._get_xobject_symbol_name(
fontname, symbol_name)
self.file.output(Name(name), Op.use_xobject)
self.file.output(Op.grestore)
# Draw any horizontal lines in the math layout
for ox, oy, width, height in rects:
self.file.output(Op.gsave, ox, oy, width, height,
Op.rectangle, Op.fill, Op.grestore)
# Pop off the global transformation
self.file.output(Op.grestore)
def draw_tex(self, gc, x, y, s, prop, angle, ismath='TeX!', mtext=None):
# docstring inherited
texmanager = self.get_texmanager()
fontsize = prop.get_size_in_points()
dvifile = texmanager.make_dvi(s, fontsize)
with dviread.Dvi(dvifile, 72) as dvi:
page, = dvi
# Gather font information and do some setup for combining
# characters into strings. The variable seq will contain a
# sequence of font and text entries. A font entry is a list
# ['font', name, size] where name is a Name object for the
# font. A text entry is ['text', x, y, glyphs, x+w] where x
# and y are the starting coordinates, w is the width, and
# glyphs is a list; in this phase it will always contain just
# one one-character string, but later it may have longer
# strings interspersed with kern amounts.
oldfont, seq = None, []
for x1, y1, dvifont, glyph, width in page.text:
if dvifont != oldfont:
pdfname = self.file.dviFontName(dvifont)
seq += [['font', pdfname, dvifont.size]]
oldfont = dvifont
seq += [['text', x1, y1, [bytes([glyph])], x1+width]]
# Find consecutive text strings with constant y coordinate and
# combine into a sequence of strings and kerns, or just one
# string (if any kerns would be less than 0.1 points).
i, curx, fontsize = 0, 0, None
while i < len(seq)-1:
elt, nxt = seq[i:i+2]
if elt[0] == 'font':
fontsize = elt[2]
elif elt[0] == nxt[0] == 'text' and elt[2] == nxt[2]:
offset = elt[4] - nxt[1]
if abs(offset) < 0.1:
elt[3][-1] += nxt[3][0]
elt[4] += nxt[4]-nxt[1]
else:
elt[3] += [offset*1000.0/fontsize, nxt[3][0]]
elt[4] = nxt[4]
del seq[i+1]
continue
i += 1
# Create a transform to map the dvi contents to the canvas.
mytrans = Affine2D().rotate_deg(angle).translate(x, y)
# Output the text.
self.check_gc(gc, gc._rgb)
self.file.output(Op.begin_text)
curx, cury, oldx, oldy = 0, 0, 0, 0
for elt in seq:
if elt[0] == 'font':
self.file.output(elt[1], elt[2], Op.selectfont)
elif elt[0] == 'text':
curx, cury = mytrans.transform_point((elt[1], elt[2]))
self._setup_textpos(curx, cury, angle, oldx, oldy)
oldx, oldy = curx, cury
if len(elt[3]) == 1:
self.file.output(elt[3][0], Op.show)
else:
self.file.output(elt[3], Op.showkern)
else:
assert False
self.file.output(Op.end_text)
# Then output the boxes (e.g., variable-length lines of square
# roots).
boxgc = self.new_gc()
boxgc.copy_properties(gc)
boxgc.set_linewidth(0)
pathops = [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO,
Path.CLOSEPOLY]
for x1, y1, h, w in page.boxes:
path = Path([[x1, y1], [x1+w, y1], [x1+w, y1+h], [x1, y1+h],
[0, 0]], pathops)
self.draw_path(boxgc, path, mytrans, gc._rgb)
def encode_string(self, s, fonttype):
if fonttype in (1, 3):
return s.encode('cp1252', 'replace')
return s.encode('utf-16be', 'replace')
def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
# docstring inherited
# TODO: combine consecutive texts into one BT/ET delimited section
# This function is rather complex, since there is no way to
# access characters of a Type 3 font with codes > 255. (Type
# 3 fonts can not have a CIDMap). Therefore, we break the
# string into chunks, where each chunk contains exclusively
# 1-byte or exclusively 2-byte characters, and output each
# chunk a separate command. 1-byte characters use the regular
# text show command (Tj), whereas 2-byte characters use the
# use XObject command (Do). If using Type 42 fonts, all of
# this complication is avoided, but of course, those fonts can
# not be subsetted.
self.check_gc(gc, gc._rgb)
if ismath:
return self.draw_mathtext(gc, x, y, s, prop, angle)
fontsize = prop.get_size_in_points()
if rcParams['pdf.use14corefonts']:
font = self._get_font_afm(prop)
fonttype = 1
else:
font = self._get_font_ttf(prop)
self.track_characters(font, s)
font.set_text(s, 0.0, flags=LOAD_NO_HINTING)
fonttype = rcParams['pdf.fonttype']
# We can't subset all OpenType fonts, so switch to Type 42
# in that case.
if is_opentype_cff_font(font.fname):
fonttype = 42
def check_simple_method(s):
"""
Determine if we should use the simple or woven method to output
this text, and chunks the string into 1-byte and 2-byte sections if
necessary.
"""
use_simple_method = True
chunks = []
if not rcParams['pdf.use14corefonts']:
if fonttype == 3 and not isinstance(s, bytes) and len(s) != 0:
# Break the string into chunks where each chunk is either
# a string of chars <= 255, or a single character > 255.
s = str(s)
for c in s:
if ord(c) <= 255:
char_type = 1
else:
char_type = 2
if len(chunks) and chunks[-1][0] == char_type:
chunks[-1][1].append(c)
else:
chunks.append((char_type, [c]))
use_simple_method = (len(chunks) == 1 and
chunks[-1][0] == 1)
return use_simple_method, chunks
def draw_text_simple():
"""Outputs text using the simple method."""
self.file.output(Op.begin_text,
self.file.fontName(prop),
fontsize,
Op.selectfont)
self._setup_textpos(x, y, angle)
self.file.output(self.encode_string(s, fonttype), Op.show,
Op.end_text)
def draw_text_woven(chunks):
"""
Outputs text using the woven method, alternating between chunks of
1-byte and 2-byte characters. Only used for Type 3 fonts.
"""
chunks = [(a, ''.join(b)) for a, b in chunks]
# Do the rotation and global translation as a single matrix
# concatenation up front
self.file.output(Op.gsave)
a = math.radians(angle)
self.file.output(math.cos(a), math.sin(a),
-math.sin(a), math.cos(a),
x, y, Op.concat_matrix)
# Output all the 1-byte characters in a BT/ET group, then
# output all the 2-byte characters.
for mode in (1, 2):
newx = oldx = 0
# Output a 1-byte character chunk
if mode == 1:
self.file.output(Op.begin_text,
self.file.fontName(prop),
fontsize,
Op.selectfont)
for chunk_type, chunk in chunks:
if mode == 1 and chunk_type == 1:
self._setup_textpos(newx, 0, 0, oldx, 0, 0)
self.file.output(self.encode_string(chunk, fonttype),
Op.show)
oldx = newx
lastgind = None
for c in chunk:
ccode = ord(c)
gind = font.get_char_index(ccode)
if gind is not None:
if mode == 2 and chunk_type == 2:
glyph_name = font.get_glyph_name(gind)
self.file.output(Op.gsave)
self.file.output(0.001 * fontsize, 0,
0, 0.001 * fontsize,
newx, 0, Op.concat_matrix)
name = self.file._get_xobject_symbol_name(
font.fname, glyph_name)
self.file.output(Name(name), Op.use_xobject)
self.file.output(Op.grestore)
# Move the pointer based on the character width
# and kerning
glyph = font.load_char(ccode,
flags=LOAD_NO_HINTING)
if lastgind is not None:
kern = font.get_kerning(
lastgind, gind, KERNING_UNFITTED)
else:
kern = 0
lastgind = gind
newx += kern/64.0 + glyph.linearHoriAdvance/65536.0
if mode == 1:
self.file.output(Op.end_text)
self.file.output(Op.grestore)
use_simple_method, chunks = check_simple_method(s)
if use_simple_method:
return draw_text_simple()
else:
return draw_text_woven(chunks)
def new_gc(self):
# docstring inherited
return GraphicsContextPdf(self.file)
class GraphicsContextPdf(GraphicsContextBase):
def __init__(self, file):
GraphicsContextBase.__init__(self)
self._fillcolor = (0.0, 0.0, 0.0)
self._effective_alphas = (1.0, 1.0)
self.file = file
self.parent = None
def __repr__(self):
d = dict(self.__dict__)
del d['file']
del d['parent']
return repr(d)
def stroke(self):
"""
Predicate: does the path need to be stroked (its outline drawn)?
This tests for the various conditions that disable stroking
the path, in which case it would presumably be filled.
"""
# _linewidth > 0: in pdf a line of width 0 is drawn at minimum
# possible device width, but e.g., agg doesn't draw at all
return (self._linewidth > 0 and self._alpha > 0 and
(len(self._rgb) <= 3 or self._rgb[3] != 0.0))
def fill(self, *args):
"""
Predicate: does the path need to be filled?
An optional argument can be used to specify an alternative
_fillcolor, as needed by RendererPdf.draw_markers.
"""
if len(args):
_fillcolor = args[0]
else:
_fillcolor = self._fillcolor
return (self._hatch or
(_fillcolor is not None and
(len(_fillcolor) <= 3 or _fillcolor[3] != 0.0)))
def paint(self):
"""
Return the appropriate pdf operator to cause the path to be
stroked, filled, or both.
"""
return Op.paint_path(self.fill(), self.stroke())
capstyles = {'butt': 0, 'round': 1, 'projecting': 2}
joinstyles = {'miter': 0, 'round': 1, 'bevel': 2}
def capstyle_cmd(self, style):
return [self.capstyles[style], Op.setlinecap]
def joinstyle_cmd(self, style):
return [self.joinstyles[style], Op.setlinejoin]
def linewidth_cmd(self, width):
return [width, Op.setlinewidth]
def dash_cmd(self, dashes):
offset, dash = dashes
if dash is None:
dash = []
offset = 0
return [list(dash), offset, Op.setdash]
def alpha_cmd(self, alpha, forced, effective_alphas):
name = self.file.alphaState(effective_alphas)
return [name, Op.setgstate]
def hatch_cmd(self, hatch, hatch_color):
if not hatch:
if self._fillcolor is not None:
return self.fillcolor_cmd(self._fillcolor)
else:
return [Name('DeviceRGB'), Op.setcolorspace_nonstroke]
else:
hatch_style = (hatch_color, self._fillcolor, hatch)
name = self.file.hatchPattern(hatch_style)
return [Name('Pattern'), Op.setcolorspace_nonstroke,
name, Op.setcolor_nonstroke]
def rgb_cmd(self, rgb):
if rcParams['pdf.inheritcolor']:
return []
if rgb[0] == rgb[1] == rgb[2]:
return [rgb[0], Op.setgray_stroke]
else:
return [*rgb[:3], Op.setrgb_stroke]
def fillcolor_cmd(self, rgb):
if rgb is None or rcParams['pdf.inheritcolor']:
return []
elif rgb[0] == rgb[1] == rgb[2]:
return [rgb[0], Op.setgray_nonstroke]
else:
return [*rgb[:3], Op.setrgb_nonstroke]
def push(self):
parent = GraphicsContextPdf(self.file)
parent.copy_properties(self)
parent.parent = self.parent
self.parent = parent
return [Op.gsave]
def pop(self):
assert self.parent is not None
self.copy_properties(self.parent)
self.parent = self.parent.parent
return [Op.grestore]
def clip_cmd(self, cliprect, clippath):
"""Set clip rectangle. Calls self.pop() and self.push()."""
cmds = []
# Pop graphics state until we hit the right one or the stack is empty
while ((self._cliprect, self._clippath) != (cliprect, clippath)
and self.parent is not None):
cmds.extend(self.pop())
# Unless we hit the right one, set the clip polygon
if ((self._cliprect, self._clippath) != (cliprect, clippath) or
self.parent is None):
cmds.extend(self.push())
if self._cliprect != cliprect:
cmds.extend([cliprect, Op.rectangle, Op.clip, Op.endpath])
if self._clippath != clippath:
path, affine = clippath.get_transformed_path_and_affine()
cmds.extend(
PdfFile.pathOperations(path, affine, simplify=False) +
[Op.clip, Op.endpath])
return cmds
commands = (
# must come first since may pop
(('_cliprect', '_clippath'), clip_cmd),
(('_alpha', '_forced_alpha', '_effective_alphas'), alpha_cmd),
(('_capstyle',), capstyle_cmd),
(('_fillcolor',), fillcolor_cmd),
(('_joinstyle',), joinstyle_cmd),
(('_linewidth',), linewidth_cmd),
(('_dashes',), dash_cmd),
(('_rgb',), rgb_cmd),
# must come after fillcolor and rgb
(('_hatch', '_hatch_color'), hatch_cmd),
)
def delta(self, other):
"""
Copy properties of other into self and return PDF commands
needed to transform self into other.
"""
cmds = []
fill_performed = False
for params, cmd in self.commands:
different = False
for p in params:
ours = getattr(self, p)
theirs = getattr(other, p)
try:
if ours is None or theirs is None:
different = ours is not theirs
else:
different = bool(ours != theirs)
except ValueError:
ours = np.asarray(ours)
theirs = np.asarray(theirs)
different = (ours.shape != theirs.shape or
np.any(ours != theirs))
if different:
break
# Need to update hatching if we also updated fillcolor
if params == ('_hatch', '_hatch_color') and fill_performed:
different = True
if different:
if params == ('_fillcolor',):
fill_performed = True
theirs = [getattr(other, p) for p in params]
cmds.extend(cmd(self, *theirs))
for p in params:
setattr(self, p, getattr(other, p))
return cmds
def copy_properties(self, other):
"""
Copy properties of other into self.
"""
GraphicsContextBase.copy_properties(self, other)
fillcolor = getattr(other, '_fillcolor', self._fillcolor)
effective_alphas = getattr(other, '_effective_alphas',
self._effective_alphas)
self._fillcolor = fillcolor
self._effective_alphas = effective_alphas
def finalize(self):
"""
Make sure every pushed graphics state is popped.
"""
cmds = []
while self.parent is not None:
cmds.extend(self.pop())
return cmds
########################################################################
#
# The following functions and classes are for pylab and implement
# window/figure managers, etc...
#
########################################################################
class PdfPages(object):
"""
A multi-page PDF file.
Examples
--------
>>> import matplotlib.pyplot as plt
>>> # Initialize:
>>> with PdfPages('foo.pdf') as pdf:
... # As many times as you like, create a figure fig and save it:
... fig = plt.figure()
... pdf.savefig(fig)
... # When no figure is specified the current figure is saved
... pdf.savefig()
Notes
-----
In reality :class:`PdfPages` is a thin wrapper around :class:`PdfFile`, in
order to avoid confusion when using :func:`~matplotlib.pyplot.savefig` and
forgetting the format argument.
"""
__slots__ = ('_file', 'keep_empty')
def __init__(self, filename, keep_empty=True, metadata=None):
"""
Create a new PdfPages object.
Parameters
----------
filename : str
Plots using :meth:`PdfPages.savefig` will be written to a file at
this location. The file is opened at once and any older file with
the same name is overwritten.
keep_empty : bool, optional
If set to False, then empty pdf files will be deleted automatically
when closed.
metadata : dictionary, optional
Information dictionary object (see PDF reference section 10.2.1
'Document Information Dictionary'), e.g.:
`{'Creator': 'My software', 'Author': 'Me',
'Title': 'Awesome fig'}`
The standard keys are `'Title'`, `'Author'`, `'Subject'`,
`'Keywords'`, `'Creator'`, `'Producer'`, `'CreationDate'`,
`'ModDate'`, and `'Trapped'`. Values have been predefined
for `'Creator'`, `'Producer'` and `'CreationDate'`. They
can be removed by setting them to `None`.
"""
self._file = PdfFile(filename, metadata=metadata)
self.keep_empty = keep_empty
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
def close(self):
"""
Finalize this object, making the underlying file a complete
PDF file.
"""
self._file.finalize()
self._file.close()
if (self.get_pagecount() == 0 and not self.keep_empty and
not self._file.passed_in_file_object):
os.remove(self._file.fh.name)
self._file = None
def infodict(self):
"""
Return a modifiable information dictionary object
(see PDF reference section 10.2.1 'Document Information
Dictionary').
"""
return self._file.infoDict
def savefig(self, figure=None, **kwargs):
"""
Saves a :class:`~matplotlib.figure.Figure` to this file as a new page.
Any other keyword arguments are passed to
:meth:`~matplotlib.figure.Figure.savefig`.
Parameters
----------
figure : :class:`~matplotlib.figure.Figure` or int, optional
Specifies what figure is saved to file. If not specified, the
active figure is saved. If a :class:`~matplotlib.figure.Figure`
instance is provided, this figure is saved. If an int is specified,
the figure instance to save is looked up by number.
"""
if not isinstance(figure, Figure):
if figure is None:
manager = Gcf.get_active()
else:
manager = Gcf.get_fig_manager(figure)
if manager is None:
raise ValueError("No figure {}".format(figure))
figure = manager.canvas.figure
# Force use of pdf backend, as PdfPages is tightly coupled with it.
try:
orig_canvas = figure.canvas
figure.canvas = FigureCanvasPdf(figure)
figure.savefig(self, format="pdf", **kwargs)
finally:
figure.canvas = orig_canvas
def get_pagecount(self):
"""
Returns the current number of pages in the multipage pdf file.
"""
return len(self._file.pageList)
def attach_note(self, text, positionRect=[-100, -100, 0, 0]):
"""
Add a new text note to the page to be saved next. The optional
positionRect specifies the position of the new note on the
page. It is outside the page per default to make sure it is
invisible on printouts.
"""
self._file.newTextnote(text, positionRect)
class FigureCanvasPdf(FigureCanvasBase):
"""
The canvas the figure renders into. Calls the draw and print fig
methods, creates the renderers, etc...
Attributes
----------
figure : `matplotlib.figure.Figure`
A high-level Figure instance
"""
fixed_dpi = 72
def draw(self):
pass
filetypes = {'pdf': 'Portable Document Format'}
def get_default_filetype(self):
return 'pdf'
def print_pdf(self, filename, *,
dpi=72, # dpi to use for images
bbox_inches_restore=None, metadata=None,
**kwargs):
self.figure.set_dpi(72) # there are 72 pdf points to an inch
width, height = self.figure.get_size_inches()
if isinstance(filename, PdfPages):
file = filename._file
else:
file = PdfFile(filename, metadata=metadata)
try:
file.newPage(width, height)
renderer = MixedModeRenderer(
self.figure, width, height, dpi,
RendererPdf(file, dpi, height, width),
bbox_inches_restore=bbox_inches_restore)
self.figure.draw(renderer)
renderer.finalize()
if not isinstance(filename, PdfPages):
file.finalize()
finally:
if isinstance(filename, PdfPages): # finish off this page
file.endStream()
else: # we opened the file above; now finish it off
file.close()
FigureManagerPdf = FigureManagerBase
@_Backend.export
class _BackendPdf(_Backend):
FigureCanvas = FigureCanvasPdf
|
b79e211202f122e4034f5d0286da010500a7fd5341ec680e1798452efccf4788
|
import functools
import os
import re
import signal
import sys
import traceback
import matplotlib
from matplotlib import backend_tools, cbook
from matplotlib._pylab_helpers import Gcf
from matplotlib.backend_bases import (
_Backend, FigureCanvasBase, FigureManagerBase, NavigationToolbar2,
TimerBase, cursors, ToolContainerBase, StatusbarBase, MouseButton)
import matplotlib.backends.qt_editor.figureoptions as figureoptions
from matplotlib.backends.qt_editor.formsubplottool import UiSubplotTool
from matplotlib.backend_managers import ToolManager
from .qt_compat import (
QtCore, QtGui, QtWidgets, _getSaveFileName, is_pyqt5, __version__, QT_API)
backend_version = __version__
# SPECIAL_KEYS are keys that do *not* return their unicode name
# instead they have manually specified names
SPECIAL_KEYS = {QtCore.Qt.Key_Control: 'control',
QtCore.Qt.Key_Shift: 'shift',
QtCore.Qt.Key_Alt: 'alt',
QtCore.Qt.Key_Meta: 'super',
QtCore.Qt.Key_Return: 'enter',
QtCore.Qt.Key_Left: 'left',
QtCore.Qt.Key_Up: 'up',
QtCore.Qt.Key_Right: 'right',
QtCore.Qt.Key_Down: 'down',
QtCore.Qt.Key_Escape: 'escape',
QtCore.Qt.Key_F1: 'f1',
QtCore.Qt.Key_F2: 'f2',
QtCore.Qt.Key_F3: 'f3',
QtCore.Qt.Key_F4: 'f4',
QtCore.Qt.Key_F5: 'f5',
QtCore.Qt.Key_F6: 'f6',
QtCore.Qt.Key_F7: 'f7',
QtCore.Qt.Key_F8: 'f8',
QtCore.Qt.Key_F9: 'f9',
QtCore.Qt.Key_F10: 'f10',
QtCore.Qt.Key_F11: 'f11',
QtCore.Qt.Key_F12: 'f12',
QtCore.Qt.Key_Home: 'home',
QtCore.Qt.Key_End: 'end',
QtCore.Qt.Key_PageUp: 'pageup',
QtCore.Qt.Key_PageDown: 'pagedown',
QtCore.Qt.Key_Tab: 'tab',
QtCore.Qt.Key_Backspace: 'backspace',
QtCore.Qt.Key_Enter: 'enter',
QtCore.Qt.Key_Insert: 'insert',
QtCore.Qt.Key_Delete: 'delete',
QtCore.Qt.Key_Pause: 'pause',
QtCore.Qt.Key_SysReq: 'sysreq',
QtCore.Qt.Key_Clear: 'clear', }
# define which modifier keys are collected on keyboard events.
# elements are (mpl names, Modifier Flag, Qt Key) tuples
SUPER = 0
ALT = 1
CTRL = 2
SHIFT = 3
MODIFIER_KEYS = [('super', QtCore.Qt.MetaModifier, QtCore.Qt.Key_Meta),
('alt', QtCore.Qt.AltModifier, QtCore.Qt.Key_Alt),
('ctrl', QtCore.Qt.ControlModifier, QtCore.Qt.Key_Control),
('shift', QtCore.Qt.ShiftModifier, QtCore.Qt.Key_Shift),
]
if sys.platform == 'darwin':
# in OSX, the control and super (aka cmd/apple) keys are switched, so
# switch them back.
SPECIAL_KEYS.update({QtCore.Qt.Key_Control: 'cmd', # cmd/apple key
QtCore.Qt.Key_Meta: 'control',
})
MODIFIER_KEYS[0] = ('cmd', QtCore.Qt.ControlModifier,
QtCore.Qt.Key_Control)
MODIFIER_KEYS[2] = ('ctrl', QtCore.Qt.MetaModifier,
QtCore.Qt.Key_Meta)
cursord = {
cursors.MOVE: QtCore.Qt.SizeAllCursor,
cursors.HAND: QtCore.Qt.PointingHandCursor,
cursors.POINTER: QtCore.Qt.ArrowCursor,
cursors.SELECT_REGION: QtCore.Qt.CrossCursor,
cursors.WAIT: QtCore.Qt.WaitCursor,
}
# make place holder
qApp = None
def _create_qApp():
"""
Only one qApp can exist at a time, so check before creating one.
"""
global qApp
if qApp is None:
app = QtWidgets.QApplication.instance()
if app is None:
# check for DISPLAY env variable on X11 build of Qt
if is_pyqt5():
try:
from PyQt5 import QtX11Extras
is_x11_build = True
except ImportError:
is_x11_build = False
else:
is_x11_build = hasattr(QtGui, "QX11Info")
if is_x11_build:
display = os.environ.get('DISPLAY')
if display is None or not re.search(r':\d', display):
raise RuntimeError('Invalid DISPLAY variable')
qApp = QtWidgets.QApplication([b"matplotlib"])
qApp.lastWindowClosed.connect(qApp.quit)
else:
qApp = app
if is_pyqt5():
try:
qApp.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps)
qApp.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)
except AttributeError:
pass
def _allow_super_init(__init__):
"""
Decorator for ``__init__`` to allow ``super().__init__`` on PyQt4/PySide2.
"""
if QT_API == "PyQt5":
return __init__
else:
# To work around lack of cooperative inheritance in PyQt4, PySide,
# and PySide2, when calling FigureCanvasQT.__init__, we temporarily
# patch QWidget.__init__ by a cooperative version, that first calls
# QWidget.__init__ with no additional arguments, and then finds the
# next class in the MRO with an __init__ that does support cooperative
# inheritance (i.e., not defined by the PyQt4, PySide, PySide2, sip
# or Shiboken packages), and manually call its `__init__`, once again
# passing the additional arguments.
qwidget_init = QtWidgets.QWidget.__init__
def cooperative_qwidget_init(self, *args, **kwargs):
qwidget_init(self)
mro = type(self).__mro__
next_coop_init = next(
cls for cls in mro[mro.index(QtWidgets.QWidget) + 1:]
if cls.__module__.split(".")[0] not in [
"PyQt4", "sip", "PySide", "PySide2", "Shiboken"])
next_coop_init.__init__(self, *args, **kwargs)
@functools.wraps(__init__)
def wrapper(self, *args, **kwargs):
with cbook._setattr_cm(QtWidgets.QWidget,
__init__=cooperative_qwidget_init):
__init__(self, *args, **kwargs)
return wrapper
class TimerQT(TimerBase):
'''
Subclass of :class:`backend_bases.TimerBase` that uses Qt timer events.
Attributes
----------
interval : int
The time between timer events in milliseconds. Default is 1000 ms.
single_shot : bool
Boolean flag indicating whether this timer should
operate as single shot (run once and then stop). Defaults to False.
callbacks : list
Stores list of (func, args) tuples that will be called upon timer
events. This list can be manipulated directly, or the functions
`add_callback` and `remove_callback` can be used.
'''
def __init__(self, *args, **kwargs):
TimerBase.__init__(self, *args, **kwargs)
# Create a new timer and connect the timeout() signal to the
# _on_timer method.
self._timer = QtCore.QTimer()
self._timer.timeout.connect(self._on_timer)
self._timer_set_interval()
def _timer_set_single_shot(self):
self._timer.setSingleShot(self._single)
def _timer_set_interval(self):
self._timer.setInterval(self._interval)
def _timer_start(self):
self._timer.start()
def _timer_stop(self):
self._timer.stop()
class FigureCanvasQT(QtWidgets.QWidget, FigureCanvasBase):
# map Qt button codes to MouseEvent's ones:
buttond = {QtCore.Qt.LeftButton: MouseButton.LEFT,
QtCore.Qt.MidButton: MouseButton.MIDDLE,
QtCore.Qt.RightButton: MouseButton.RIGHT,
QtCore.Qt.XButton1: MouseButton.BACK,
QtCore.Qt.XButton2: MouseButton.FORWARD,
}
@_allow_super_init
def __init__(self, figure):
_create_qApp()
super().__init__(figure=figure)
self.figure = figure
# We don't want to scale up the figure DPI more than once.
# Note, we don't handle a signal for changing DPI yet.
figure._original_dpi = figure.dpi
self._update_figure_dpi()
# In cases with mixed resolution displays, we need to be careful if the
# dpi_ratio changes - in this case we need to resize the canvas
# accordingly. We could watch for screenChanged events from Qt, but
# the issue is that we can't guarantee this will be emitted *before*
# the first paintEvent for the canvas, so instead we keep track of the
# dpi_ratio value here and in paintEvent we resize the canvas if
# needed.
self._dpi_ratio_prev = None
self._draw_pending = False
self._is_drawing = False
self._draw_rect_callback = lambda painter: None
self.setAttribute(QtCore.Qt.WA_OpaquePaintEvent)
self.setMouseTracking(True)
self.resize(*self.get_width_height())
# Key auto-repeat enabled by default
self._keyautorepeat = True
palette = QtGui.QPalette(QtCore.Qt.white)
self.setPalette(palette)
def _update_figure_dpi(self):
dpi = self._dpi_ratio * self.figure._original_dpi
self.figure._set_dpi(dpi, forward=False)
@property
def _dpi_ratio(self):
# Not available on Qt4 or some older Qt5.
try:
# self.devicePixelRatio() returns 0 in rare cases
return self.devicePixelRatio() or 1
except AttributeError:
return 1
def _update_dpi(self):
# As described in __init__ above, we need to be careful in cases with
# mixed resolution displays if dpi_ratio is changing between painting
# events.
# Return whether we triggered a resizeEvent (and thus a paintEvent)
# from within this function.
if self._dpi_ratio != self._dpi_ratio_prev:
# We need to update the figure DPI.
self._update_figure_dpi()
self._dpi_ratio_prev = self._dpi_ratio
# The easiest way to resize the canvas is to emit a resizeEvent
# since we implement all the logic for resizing the canvas for
# that event.
event = QtGui.QResizeEvent(self.size(), self.size())
self.resizeEvent(event)
# resizeEvent triggers a paintEvent itself, so we exit this one
# (after making sure that the event is immediately handled).
return True
return False
def get_width_height(self):
w, h = FigureCanvasBase.get_width_height(self)
return int(w / self._dpi_ratio), int(h / self._dpi_ratio)
def enterEvent(self, event):
try:
x, y = self.mouseEventCoords(event.pos())
except AttributeError:
# the event from PyQt4 does not include the position
x = y = None
FigureCanvasBase.enter_notify_event(self, guiEvent=event, xy=(x, y))
def leaveEvent(self, event):
QtWidgets.QApplication.restoreOverrideCursor()
FigureCanvasBase.leave_notify_event(self, guiEvent=event)
def mouseEventCoords(self, pos):
"""Calculate mouse coordinates in physical pixels
Qt5 use logical pixels, but the figure is scaled to physical
pixels for rendering. Transform to physical pixels so that
all of the down-stream transforms work as expected.
Also, the origin is different and needs to be corrected.
"""
dpi_ratio = self._dpi_ratio
x = pos.x()
# flip y so y=0 is bottom of canvas
y = self.figure.bbox.height / dpi_ratio - pos.y()
return x * dpi_ratio, y * dpi_ratio
def mousePressEvent(self, event):
x, y = self.mouseEventCoords(event.pos())
button = self.buttond.get(event.button())
if button is not None:
FigureCanvasBase.button_press_event(self, x, y, button,
guiEvent=event)
def mouseDoubleClickEvent(self, event):
x, y = self.mouseEventCoords(event.pos())
button = self.buttond.get(event.button())
if button is not None:
FigureCanvasBase.button_press_event(self, x, y,
button, dblclick=True,
guiEvent=event)
def mouseMoveEvent(self, event):
x, y = self.mouseEventCoords(event)
FigureCanvasBase.motion_notify_event(self, x, y, guiEvent=event)
def mouseReleaseEvent(self, event):
x, y = self.mouseEventCoords(event)
button = self.buttond.get(event.button())
if button is not None:
FigureCanvasBase.button_release_event(self, x, y, button,
guiEvent=event)
if is_pyqt5():
def wheelEvent(self, event):
x, y = self.mouseEventCoords(event)
# from QWheelEvent::delta doc
if event.pixelDelta().x() == 0 and event.pixelDelta().y() == 0:
steps = event.angleDelta().y() / 120
else:
steps = event.pixelDelta().y()
if steps:
FigureCanvasBase.scroll_event(
self, x, y, steps, guiEvent=event)
else:
def wheelEvent(self, event):
x = event.x()
# flipy so y=0 is bottom of canvas
y = self.figure.bbox.height - event.y()
# from QWheelEvent::delta doc
steps = event.delta() / 120
if event.orientation() == QtCore.Qt.Vertical:
FigureCanvasBase.scroll_event(
self, x, y, steps, guiEvent=event)
def keyPressEvent(self, event):
key = self._get_key(event)
if key is not None:
FigureCanvasBase.key_press_event(self, key, guiEvent=event)
def keyReleaseEvent(self, event):
key = self._get_key(event)
if key is not None:
FigureCanvasBase.key_release_event(self, key, guiEvent=event)
@cbook.deprecated("3.0", alternative="event.guiEvent.isAutoRepeat")
@property
def keyAutoRepeat(self):
"""
If True, enable auto-repeat for key events.
"""
return self._keyautorepeat
@keyAutoRepeat.setter
def keyAutoRepeat(self, val):
self._keyautorepeat = bool(val)
def resizeEvent(self, event):
# _dpi_ratio_prev will be set the first time the canvas is painted, and
# the rendered buffer is useless before anyways.
if self._dpi_ratio_prev is None:
return
w = event.size().width() * self._dpi_ratio
h = event.size().height() * self._dpi_ratio
dpival = self.figure.dpi
winch = w / dpival
hinch = h / dpival
self.figure.set_size_inches(winch, hinch, forward=False)
# pass back into Qt to let it finish
QtWidgets.QWidget.resizeEvent(self, event)
# emit our resize events
FigureCanvasBase.resize_event(self)
def sizeHint(self):
w, h = self.get_width_height()
return QtCore.QSize(w, h)
def minumumSizeHint(self):
return QtCore.QSize(10, 10)
def _get_key(self, event):
if not self._keyautorepeat and event.isAutoRepeat():
return None
event_key = event.key()
event_mods = int(event.modifiers()) # actually a bitmask
# get names of the pressed modifier keys
# bit twiddling to pick out modifier keys from event_mods bitmask,
# if event_key is a MODIFIER, it should not be duplicated in mods
mods = [name for name, mod_key, qt_key in MODIFIER_KEYS
if event_key != qt_key and (event_mods & mod_key) == mod_key]
try:
# for certain keys (enter, left, backspace, etc) use a word for the
# key, rather than unicode
key = SPECIAL_KEYS[event_key]
except KeyError:
# unicode defines code points up to 0x0010ffff
# QT will use Key_Codes larger than that for keyboard keys that are
# are not unicode characters (like multimedia keys)
# skip these
# if you really want them, you should add them to SPECIAL_KEYS
MAX_UNICODE = 0x10ffff
if event_key > MAX_UNICODE:
return None
key = chr(event_key)
# qt delivers capitalized letters. fix capitalization
# note that capslock is ignored
if 'shift' in mods:
mods.remove('shift')
else:
key = key.lower()
mods.reverse()
return '+'.join(mods + [key])
def new_timer(self, *args, **kwargs):
# docstring inherited
return TimerQT(*args, **kwargs)
def flush_events(self):
# docstring inherited
qApp.processEvents()
def start_event_loop(self, timeout=0):
# docstring inherited
if hasattr(self, "_event_loop") and self._event_loop.isRunning():
raise RuntimeError("Event loop already running")
self._event_loop = event_loop = QtCore.QEventLoop()
if timeout:
timer = QtCore.QTimer.singleShot(timeout * 1000, event_loop.quit)
event_loop.exec_()
def stop_event_loop(self, event=None):
# docstring inherited
if hasattr(self, "_event_loop"):
self._event_loop.quit()
def draw(self):
"""Render the figure, and queue a request for a Qt draw.
"""
# The renderer draw is done here; delaying causes problems with code
# that uses the result of the draw() to update plot elements.
if self._is_drawing:
return
with cbook._setattr_cm(self, _is_drawing=True):
super().draw()
self.update()
def draw_idle(self):
"""Queue redraw of the Agg buffer and request Qt paintEvent.
"""
# The Agg draw needs to be handled by the same thread matplotlib
# modifies the scene graph from. Post Agg draw request to the
# current event loop in order to ensure thread affinity and to
# accumulate multiple draw requests from event handling.
# TODO: queued signal connection might be safer than singleShot
if not (self._draw_pending or self._is_drawing):
self._draw_pending = True
QtCore.QTimer.singleShot(0, self._draw_idle)
def _draw_idle(self):
if self.height() < 0 or self.width() < 0:
self._draw_pending = False
if not self._draw_pending:
return
try:
self.draw()
except Exception:
# Uncaught exceptions are fatal for PyQt5, so catch them instead.
traceback.print_exc()
finally:
self._draw_pending = False
def drawRectangle(self, rect):
# Draw the zoom rectangle to the QPainter. _draw_rect_callback needs
# to be called at the end of paintEvent.
if rect is not None:
def _draw_rect_callback(painter):
pen = QtGui.QPen(QtCore.Qt.black, 1 / self._dpi_ratio,
QtCore.Qt.DotLine)
painter.setPen(pen)
painter.drawRect(*(pt / self._dpi_ratio for pt in rect))
else:
def _draw_rect_callback(painter):
return
self._draw_rect_callback = _draw_rect_callback
self.update()
class MainWindow(QtWidgets.QMainWindow):
closing = QtCore.Signal()
def closeEvent(self, event):
self.closing.emit()
QtWidgets.QMainWindow.closeEvent(self, event)
class FigureManagerQT(FigureManagerBase):
"""
Attributes
----------
canvas : `FigureCanvas`
The FigureCanvas instance
num : int or str
The Figure number
toolbar : qt.QToolBar
The qt.QToolBar
window : qt.QMainWindow
The qt.QMainWindow
"""
def __init__(self, canvas, num):
FigureManagerBase.__init__(self, canvas, num)
self.canvas = canvas
self.window = MainWindow()
self.window.closing.connect(canvas.close_event)
self.window.closing.connect(self._widgetclosed)
self.window.setWindowTitle("Figure %d" % num)
image = os.path.join(matplotlib.rcParams['datapath'],
'images', 'matplotlib.svg')
self.window.setWindowIcon(QtGui.QIcon(image))
# Give the keyboard focus to the figure instead of the
# manager; StrongFocus accepts both tab and click to focus and
# will enable the canvas to process event w/o clicking.
# ClickFocus only takes the focus is the window has been
# clicked
# on. http://qt-project.org/doc/qt-4.8/qt.html#FocusPolicy-enum or
# http://doc.qt.digia.com/qt/qt.html#FocusPolicy-enum
self.canvas.setFocusPolicy(QtCore.Qt.StrongFocus)
self.canvas.setFocus()
self.window._destroying = False
self.toolmanager = self._get_toolmanager()
self.toolbar = self._get_toolbar(self.canvas, self.window)
self.statusbar = None
if self.toolmanager:
backend_tools.add_tools_to_manager(self.toolmanager)
if self.toolbar:
backend_tools.add_tools_to_container(self.toolbar)
self.statusbar = StatusbarQt(self.window, self.toolmanager)
if self.toolbar is not None:
self.window.addToolBar(self.toolbar)
if not self.toolmanager:
# add text label to status bar
statusbar_label = QtWidgets.QLabel()
self.window.statusBar().addWidget(statusbar_label)
self.toolbar.message.connect(statusbar_label.setText)
tbs_height = self.toolbar.sizeHint().height()
else:
tbs_height = 0
# resize the main window so it will display the canvas with the
# requested size:
cs = canvas.sizeHint()
sbs = self.window.statusBar().sizeHint()
height = cs.height() + tbs_height + sbs.height()
self.window.resize(cs.width(), height)
self.window.setCentralWidget(self.canvas)
if matplotlib.is_interactive():
self.window.show()
self.canvas.draw_idle()
self.window.raise_()
def full_screen_toggle(self):
if self.window.isFullScreen():
self.window.showNormal()
else:
self.window.showFullScreen()
def _widgetclosed(self):
if self.window._destroying:
return
self.window._destroying = True
try:
Gcf.destroy(self.num)
except AttributeError:
pass
# It seems that when the python session is killed,
# Gcf can get destroyed before the Gcf.destroy
# line is run, leading to a useless AttributeError.
def _get_toolbar(self, canvas, parent):
# must be inited after the window, drawingArea and figure
# attrs are set
if matplotlib.rcParams['toolbar'] == 'toolbar2':
toolbar = NavigationToolbar2QT(canvas, parent, False)
elif matplotlib.rcParams['toolbar'] == 'toolmanager':
toolbar = ToolbarQt(self.toolmanager, self.window)
else:
toolbar = None
return toolbar
def _get_toolmanager(self):
if matplotlib.rcParams['toolbar'] == 'toolmanager':
toolmanager = ToolManager(self.canvas.figure)
else:
toolmanager = None
return toolmanager
def resize(self, width, height):
# these are Qt methods so they return sizes in 'virtual' pixels
# so we do not need to worry about dpi scaling here.
extra_width = self.window.width() - self.canvas.width()
extra_height = self.window.height() - self.canvas.height()
self.window.resize(width+extra_width, height+extra_height)
def show(self):
self.window.show()
self.window.activateWindow()
self.window.raise_()
def destroy(self, *args):
# check for qApp first, as PySide deletes it in its atexit handler
if QtWidgets.QApplication.instance() is None:
return
if self.window._destroying:
return
self.window._destroying = True
if self.toolbar:
self.toolbar.destroy()
self.window.close()
def get_window_title(self):
return self.window.windowTitle()
def set_window_title(self, title):
self.window.setWindowTitle(title)
class NavigationToolbar2QT(NavigationToolbar2, QtWidgets.QToolBar):
message = QtCore.Signal(str)
def __init__(self, canvas, parent, coordinates=True):
""" coordinates: should we show the coordinates on the right? """
self.canvas = canvas
self.parent = parent
self.coordinates = coordinates
self._actions = {}
"""A mapping of toolitem method names to their QActions"""
QtWidgets.QToolBar.__init__(self, parent)
NavigationToolbar2.__init__(self, canvas)
def _icon(self, name):
if is_pyqt5():
name = name.replace('.png', '_large.png')
pm = QtGui.QPixmap(os.path.join(self.basedir, name))
if hasattr(pm, 'setDevicePixelRatio'):
pm.setDevicePixelRatio(self.canvas._dpi_ratio)
return QtGui.QIcon(pm)
def _init_toolbar(self):
self.basedir = os.path.join(matplotlib.rcParams['datapath'], 'images')
for text, tooltip_text, image_file, callback in self.toolitems:
if text is None:
self.addSeparator()
else:
a = self.addAction(self._icon(image_file + '.png'),
text, getattr(self, callback))
self._actions[callback] = a
if callback in ['zoom', 'pan']:
a.setCheckable(True)
if tooltip_text is not None:
a.setToolTip(tooltip_text)
if text == 'Subplots':
a = self.addAction(self._icon("qt4_editor_options.png"),
'Customize', self.edit_parameters)
a.setToolTip('Edit axis, curve and image parameters')
# Add the x,y location widget at the right side of the toolbar
# The stretch factor is 1 which means any resizing of the toolbar
# will resize this label instead of the buttons.
if self.coordinates:
self.locLabel = QtWidgets.QLabel("", self)
self.locLabel.setAlignment(
QtCore.Qt.AlignRight | QtCore.Qt.AlignTop)
self.locLabel.setSizePolicy(
QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding,
QtWidgets.QSizePolicy.Ignored))
labelAction = self.addWidget(self.locLabel)
labelAction.setVisible(True)
# Esthetic adjustments - we need to set these explicitly in PyQt5
# otherwise the layout looks different - but we don't want to set it if
# not using HiDPI icons otherwise they look worse than before.
if is_pyqt5():
self.setIconSize(QtCore.QSize(24, 24))
self.layout().setSpacing(12)
@cbook.deprecated("3.1")
@property
def buttons(self):
return {}
@cbook.deprecated("3.1")
@property
def adj_window(self):
return None
if is_pyqt5():
# For some reason, self.setMinimumHeight doesn't seem to carry over to
# the actual sizeHint, so override it instead in order to make the
# aesthetic adjustments noted above.
def sizeHint(self):
size = super().sizeHint()
size.setHeight(max(48, size.height()))
return size
def edit_parameters(self):
axes = self.canvas.figure.get_axes()
if not axes:
QtWidgets.QMessageBox.warning(
self.parent, "Error", "There are no axes to edit.")
return
elif len(axes) == 1:
ax, = axes
else:
titles = [
ax.get_label() or
ax.get_title() or
" - ".join(filter(None, [ax.get_xlabel(), ax.get_ylabel()])) or
f"<anonymous {type(ax).__name__}>"
for ax in axes]
duplicate_titles = [
title for title in titles if titles.count(title) > 1]
for i, ax in enumerate(axes):
if titles[i] in duplicate_titles:
titles[i] += f" (id: {id(ax):#x})" # Deduplicate titles.
item, ok = QtWidgets.QInputDialog.getItem(
self.parent, 'Customize', 'Select axes:', titles, 0, False)
if not ok:
return
ax = axes[titles.index(item)]
figureoptions.figure_edit(ax, self)
def _update_buttons_checked(self):
# sync button checkstates to match active mode
self._actions['pan'].setChecked(self._active == 'PAN')
self._actions['zoom'].setChecked(self._active == 'ZOOM')
def pan(self, *args):
super().pan(*args)
self._update_buttons_checked()
def zoom(self, *args):
super().zoom(*args)
self._update_buttons_checked()
def set_message(self, s):
self.message.emit(s)
if self.coordinates:
self.locLabel.setText(s)
def set_cursor(self, cursor):
self.canvas.setCursor(cursord[cursor])
def draw_rubberband(self, event, x0, y0, x1, y1):
height = self.canvas.figure.bbox.height
y1 = height - y1
y0 = height - y0
rect = [int(val) for val in (x0, y0, x1 - x0, y1 - y0)]
self.canvas.drawRectangle(rect)
def remove_rubberband(self):
self.canvas.drawRectangle(None)
def configure_subplots(self):
image = os.path.join(matplotlib.rcParams['datapath'],
'images', 'matplotlib.png')
dia = SubplotToolQt(self.canvas.figure, self.canvas.parent())
dia.setWindowIcon(QtGui.QIcon(image))
dia.exec_()
def save_figure(self, *args):
filetypes = self.canvas.get_supported_filetypes_grouped()
sorted_filetypes = sorted(filetypes.items())
default_filetype = self.canvas.get_default_filetype()
startpath = os.path.expanduser(
matplotlib.rcParams['savefig.directory'])
start = os.path.join(startpath, self.canvas.get_default_filename())
filters = []
selectedFilter = None
for name, exts in sorted_filetypes:
exts_list = " ".join(['*.%s' % ext for ext in exts])
filter = '%s (%s)' % (name, exts_list)
if default_filetype in exts:
selectedFilter = filter
filters.append(filter)
filters = ';;'.join(filters)
fname, filter = _getSaveFileName(self.canvas.parent(),
"Choose a filename to save to",
start, filters, selectedFilter)
if fname:
# Save dir for next time, unless empty str (i.e., use cwd).
if startpath != "":
matplotlib.rcParams['savefig.directory'] = (
os.path.dirname(fname))
try:
self.canvas.figure.savefig(fname)
except Exception as e:
QtWidgets.QMessageBox.critical(
self, "Error saving file", str(e),
QtWidgets.QMessageBox.Ok, QtWidgets.QMessageBox.NoButton)
def set_history_buttons(self):
can_backward = self._nav_stack._pos > 0
can_forward = self._nav_stack._pos < len(self._nav_stack._elements) - 1
self._actions['back'].setEnabled(can_backward)
self._actions['forward'].setEnabled(can_forward)
class SubplotToolQt(UiSubplotTool):
def __init__(self, targetfig, parent):
UiSubplotTool.__init__(self, None)
self._figure = targetfig
for lower, higher in [("bottom", "top"), ("left", "right")]:
self._widgets[lower].valueChanged.connect(
lambda val: self._widgets[higher].setMinimum(val + .001))
self._widgets[higher].valueChanged.connect(
lambda val: self._widgets[lower].setMaximum(val - .001))
self._attrs = ["top", "bottom", "left", "right", "hspace", "wspace"]
self._defaults = {attr: vars(self._figure.subplotpars)[attr]
for attr in self._attrs}
# Set values after setting the range callbacks, but before setting up
# the redraw callbacks.
self._reset()
for attr in self._attrs:
self._widgets[attr].valueChanged.connect(self._on_value_changed)
for action, method in [("Export values", self._export_values),
("Tight layout", self._tight_layout),
("Reset", self._reset),
("Close", self.close)]:
self._widgets[action].clicked.connect(method)
def _export_values(self):
# Explicitly round to 3 decimals (which is also the spinbox precision)
# to avoid numbers of the form 0.100...001.
dialog = QtWidgets.QDialog()
layout = QtWidgets.QVBoxLayout()
dialog.setLayout(layout)
text = QtWidgets.QPlainTextEdit()
text.setReadOnly(True)
layout.addWidget(text)
text.setPlainText(
",\n".join("{}={:.3}".format(attr, self._widgets[attr].value())
for attr in self._attrs))
# Adjust the height of the text widget to fit the whole text, plus
# some padding.
size = text.maximumSize()
size.setHeight(
QtGui.QFontMetrics(text.document().defaultFont())
.size(0, text.toPlainText()).height() + 20)
text.setMaximumSize(size)
dialog.exec_()
def _on_value_changed(self):
self._figure.subplots_adjust(**{attr: self._widgets[attr].value()
for attr in self._attrs})
self._figure.canvas.draw_idle()
def _tight_layout(self):
self._figure.tight_layout()
for attr in self._attrs:
widget = self._widgets[attr]
widget.blockSignals(True)
widget.setValue(vars(self._figure.subplotpars)[attr])
widget.blockSignals(False)
self._figure.canvas.draw_idle()
def _reset(self):
for attr, value in self._defaults.items():
self._widgets[attr].setValue(value)
class ToolbarQt(ToolContainerBase, QtWidgets.QToolBar):
def __init__(self, toolmanager, parent):
ToolContainerBase.__init__(self, toolmanager)
QtWidgets.QToolBar.__init__(self, parent)
self._toolitems = {}
self._groups = {}
@property
def _icon_extension(self):
if is_pyqt5():
return '_large.png'
return '.png'
def add_toolitem(
self, name, group, position, image_file, description, toggle):
button = QtWidgets.QToolButton(self)
button.setIcon(self._icon(image_file))
button.setText(name)
if description:
button.setToolTip(description)
def handler():
self.trigger_tool(name)
if toggle:
button.setCheckable(True)
button.toggled.connect(handler)
else:
button.clicked.connect(handler)
self._toolitems.setdefault(name, [])
self._add_to_group(group, name, button, position)
self._toolitems[name].append((button, handler))
def _add_to_group(self, group, name, button, position):
gr = self._groups.get(group, [])
if not gr:
sep = self.addSeparator()
gr.append(sep)
before = gr[position]
widget = self.insertWidget(before, button)
gr.insert(position, widget)
self._groups[group] = gr
def _icon(self, name):
pm = QtGui.QPixmap(name)
if hasattr(pm, 'setDevicePixelRatio'):
pm.setDevicePixelRatio(self.toolmanager.canvas._dpi_ratio)
return QtGui.QIcon(pm)
def toggle_toolitem(self, name, toggled):
if name not in self._toolitems:
return
for button, handler in self._toolitems[name]:
button.toggled.disconnect(handler)
button.setChecked(toggled)
button.toggled.connect(handler)
def remove_toolitem(self, name):
for button, handler in self._toolitems[name]:
button.setParent(None)
del self._toolitems[name]
class StatusbarQt(StatusbarBase, QtWidgets.QLabel):
def __init__(self, window, *args, **kwargs):
StatusbarBase.__init__(self, *args, **kwargs)
QtWidgets.QLabel.__init__(self)
window.statusBar().addWidget(self)
def set_message(self, s):
self.setText(s)
class ConfigureSubplotsQt(backend_tools.ConfigureSubplotsBase):
def trigger(self, *args):
NavigationToolbar2QT.configure_subplots(
self._make_classic_style_pseudo_toolbar())
class SaveFigureQt(backend_tools.SaveFigureBase):
def trigger(self, *args):
NavigationToolbar2QT.save_figure(
self._make_classic_style_pseudo_toolbar())
class SetCursorQt(backend_tools.SetCursorBase):
def set_cursor(self, cursor):
NavigationToolbar2QT.set_cursor(
self._make_classic_style_pseudo_toolbar(), cursor)
class RubberbandQt(backend_tools.RubberbandBase):
def draw_rubberband(self, x0, y0, x1, y1):
NavigationToolbar2QT.draw_rubberband(
self._make_classic_style_pseudo_toolbar(), None, x0, y0, x1, y1)
def remove_rubberband(self):
NavigationToolbar2QT.remove_rubberband(
self._make_classic_style_pseudo_toolbar())
class HelpQt(backend_tools.ToolHelpBase):
def trigger(self, *args):
QtWidgets.QMessageBox.information(None, "Help", self._get_help_html())
class ToolCopyToClipboardQT(backend_tools.ToolCopyToClipboardBase):
def trigger(self, *args, **kwargs):
pixmap = self.canvas.grab()
qApp.clipboard().setPixmap(pixmap)
backend_tools.ToolSaveFigure = SaveFigureQt
backend_tools.ToolConfigureSubplots = ConfigureSubplotsQt
backend_tools.ToolSetCursor = SetCursorQt
backend_tools.ToolRubberband = RubberbandQt
backend_tools.ToolHelp = HelpQt
backend_tools.ToolCopyToClipboard = ToolCopyToClipboardQT
@cbook.deprecated("3.0")
def error_msg_qt(msg, parent=None):
if not isinstance(msg, str):
msg = ','.join(map(str, msg))
QtWidgets.QMessageBox.warning(None, "Matplotlib",
msg, QtGui.QMessageBox.Ok)
@cbook.deprecated("3.0")
def exception_handler(type, value, tb):
"""Handle uncaught exceptions
It does not catch SystemExit
"""
msg = ''
# get the filename attribute if available (for IOError)
if hasattr(value, 'filename') and value.filename is not None:
msg = value.filename + ': '
if hasattr(value, 'strerror') and value.strerror is not None:
msg += value.strerror
else:
msg += str(value)
if len(msg):
error_msg_qt(msg)
@_Backend.export
class _BackendQT5(_Backend):
required_interactive_framework = "qt5"
FigureCanvas = FigureCanvasQT
FigureManager = FigureManagerQT
@staticmethod
def trigger_manager_draw(manager):
manager.canvas.draw_idle()
@staticmethod
def mainloop():
old_signal = signal.getsignal(signal.SIGINT)
# allow SIGINT exceptions to close the plot window.
signal.signal(signal.SIGINT, signal.SIG_DFL)
try:
qApp.exec_()
finally:
# reset the SIGINT exception handler
signal.signal(signal.SIGINT, old_signal)
|
3de21440789ccf991e55fb05e06fab21c8f5d9f036cad88426ff588ce30298e1
|
"""
An agg http://antigrain.com/ backend
Features that are implemented
* capstyles and join styles
* dashes
* linewidth
* lines, rectangles, ellipses
* clipping to a rectangle
* output to RGBA and PNG, optionally JPEG and TIFF
* alpha blending
* DPI scaling properly - everything scales properly (dashes, linewidths, etc)
* draw polygon
* freetype2 w/ ft2font
TODO:
* integrate screen dpi w/ ppi and text
"""
try:
import threading
except ImportError:
import dummy_threading as threading
import numpy as np
from collections import OrderedDict
from math import radians, cos, sin
from matplotlib import cbook, rcParams, __version__
from matplotlib.backend_bases import (
_Backend, FigureCanvasBase, FigureManagerBase, RendererBase)
from matplotlib.font_manager import findfont, get_font
from matplotlib.ft2font import (LOAD_FORCE_AUTOHINT, LOAD_NO_HINTING,
LOAD_DEFAULT, LOAD_NO_AUTOHINT)
from matplotlib.mathtext import MathTextParser
from matplotlib.path import Path
from matplotlib.transforms import Bbox, BboxBase
from matplotlib import colors as mcolors
from matplotlib.backends._backend_agg import RendererAgg as _RendererAgg
from matplotlib.backend_bases import _has_pil
if _has_pil:
from PIL import Image
backend_version = 'v2.2'
def get_hinting_flag():
mapping = {
True: LOAD_FORCE_AUTOHINT,
False: LOAD_NO_HINTING,
'either': LOAD_DEFAULT,
'native': LOAD_NO_AUTOHINT,
'auto': LOAD_FORCE_AUTOHINT,
'none': LOAD_NO_HINTING
}
return mapping[rcParams['text.hinting']]
class RendererAgg(RendererBase):
"""
The renderer handles all the drawing primitives using a graphics
context instance that controls the colors/styles
"""
# we want to cache the fonts at the class level so that when
# multiple figures are created we can reuse them. This helps with
# a bug on windows where the creation of too many figures leads to
# too many open file handles. However, storing them at the class
# level is not thread safe. The solution here is to let the
# FigureCanvas acquire a lock on the fontd at the start of the
# draw, and release it when it is done. This allows multiple
# renderers to share the cached fonts, but only one figure can
# draw at time and so the font cache is used by only one
# renderer at a time.
lock = threading.RLock()
def __init__(self, width, height, dpi):
RendererBase.__init__(self)
self.dpi = dpi
self.width = width
self.height = height
self._renderer = _RendererAgg(int(width), int(height), dpi)
self._filter_renderers = []
self._update_methods()
self.mathtext_parser = MathTextParser('Agg')
self.bbox = Bbox.from_bounds(0, 0, self.width, self.height)
def __getstate__(self):
# We only want to preserve the init keywords of the Renderer.
# Anything else can be re-created.
return {'width': self.width, 'height': self.height, 'dpi': self.dpi}
def __setstate__(self, state):
self.__init__(state['width'], state['height'], state['dpi'])
def _update_methods(self):
self.draw_gouraud_triangle = self._renderer.draw_gouraud_triangle
self.draw_gouraud_triangles = self._renderer.draw_gouraud_triangles
self.draw_image = self._renderer.draw_image
self.draw_markers = self._renderer.draw_markers
self.draw_path_collection = self._renderer.draw_path_collection
self.draw_quad_mesh = self._renderer.draw_quad_mesh
self.copy_from_bbox = self._renderer.copy_from_bbox
self.get_content_extents = self._renderer.get_content_extents
def tostring_rgba_minimized(self):
extents = self.get_content_extents()
bbox = [[extents[0], self.height - (extents[1] + extents[3])],
[extents[0] + extents[2], self.height - extents[1]]]
region = self.copy_from_bbox(bbox)
return np.array(region), extents
def draw_path(self, gc, path, transform, rgbFace=None):
# docstring inherited
nmax = rcParams['agg.path.chunksize'] # here at least for testing
npts = path.vertices.shape[0]
if (nmax > 100 and npts > nmax and path.should_simplify and
rgbFace is None and gc.get_hatch() is None):
nch = np.ceil(npts / nmax)
chsize = int(np.ceil(npts / nch))
i0 = np.arange(0, npts, chsize)
i1 = np.zeros_like(i0)
i1[:-1] = i0[1:] - 1
i1[-1] = npts
for ii0, ii1 in zip(i0, i1):
v = path.vertices[ii0:ii1, :]
c = path.codes
if c is not None:
c = c[ii0:ii1]
c[0] = Path.MOVETO # move to end of last chunk
p = Path(v, c)
try:
self._renderer.draw_path(gc, p, transform, rgbFace)
except OverflowError:
raise OverflowError("Exceeded cell block limit (set "
"'agg.path.chunksize' rcparam)")
else:
try:
self._renderer.draw_path(gc, path, transform, rgbFace)
except OverflowError:
raise OverflowError("Exceeded cell block limit (set "
"'agg.path.chunksize' rcparam)")
def draw_mathtext(self, gc, x, y, s, prop, angle):
"""
Draw the math text using matplotlib.mathtext
"""
ox, oy, width, height, descent, font_image, used_characters = \
self.mathtext_parser.parse(s, self.dpi, prop)
xd = descent * sin(radians(angle))
yd = descent * cos(radians(angle))
x = np.round(x + ox + xd)
y = np.round(y - oy + yd)
self._renderer.draw_text_image(font_image, x, y + 1, angle, gc)
def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
# docstring inherited
if ismath:
return self.draw_mathtext(gc, x, y, s, prop, angle)
flags = get_hinting_flag()
font = self._get_agg_font(prop)
if font is None:
return None
if len(s) == 1 and ord(s) > 127:
font.load_char(ord(s), flags=flags)
else:
# We pass '0' for angle here, since it will be rotated (in raster
# space) in the following call to draw_text_image).
font.set_text(s, 0, flags=flags)
font.draw_glyphs_to_bitmap(antialiased=rcParams['text.antialiased'])
d = font.get_descent() / 64.0
# The descent needs to be adjusted for the angle.
xo, yo = font.get_bitmap_offset()
xo /= 64.0
yo /= 64.0
xd = -d * sin(radians(angle))
yd = d * cos(radians(angle))
self._renderer.draw_text_image(
font, np.round(x - xd + xo), np.round(y + yd + yo) + 1, angle, gc)
def get_text_width_height_descent(self, s, prop, ismath):
# docstring inherited
if ismath in ["TeX", "TeX!"]:
# todo: handle props
texmanager = self.get_texmanager()
fontsize = prop.get_size_in_points()
w, h, d = texmanager.get_text_width_height_descent(
s, fontsize, renderer=self)
return w, h, d
if ismath:
ox, oy, width, height, descent, fonts, used_characters = \
self.mathtext_parser.parse(s, self.dpi, prop)
return width, height, descent
flags = get_hinting_flag()
font = self._get_agg_font(prop)
font.set_text(s, 0.0, flags=flags)
w, h = font.get_width_height() # width and height of unrotated string
d = font.get_descent()
w /= 64.0 # convert from subpixels
h /= 64.0
d /= 64.0
return w, h, d
def draw_tex(self, gc, x, y, s, prop, angle, ismath='TeX!', mtext=None):
# docstring inherited
# todo, handle props, angle, origins
size = prop.get_size_in_points()
texmanager = self.get_texmanager()
Z = texmanager.get_grey(s, size, self.dpi)
Z = np.array(Z * 255.0, np.uint8)
w, h, d = self.get_text_width_height_descent(s, prop, ismath)
xd = d * sin(radians(angle))
yd = d * cos(radians(angle))
x = np.round(x + xd)
y = np.round(y + yd)
self._renderer.draw_text_image(Z, x, y, angle, gc)
def get_canvas_width_height(self):
# docstring inherited
return self.width, self.height
def _get_agg_font(self, prop):
"""
Get the font for text instance t, caching for efficiency
"""
fname = findfont(prop)
font = get_font(fname)
font.clear()
size = prop.get_size_in_points()
font.set_size(size, self.dpi)
return font
def points_to_pixels(self, points):
# docstring inherited
return points * self.dpi / 72
def buffer_rgba(self):
return memoryview(self._renderer)
def tostring_argb(self):
return np.asarray(self._renderer).take([3, 0, 1, 2], axis=2).tobytes()
def tostring_rgb(self):
return np.asarray(self._renderer).take([0, 1, 2], axis=2).tobytes()
def clear(self):
self._renderer.clear()
def option_image_nocomposite(self):
# docstring inherited
# It is generally faster to composite each image directly to
# the Figure, and there's no file size benefit to compositing
# with the Agg backend
return True
def option_scale_image(self):
# docstring inherited
return False
def restore_region(self, region, bbox=None, xy=None):
"""
Restore the saved region. If bbox (instance of BboxBase, or
its extents) is given, only the region specified by the bbox
will be restored. *xy* (a pair of floats) optionally
specifies the new position (the LLC of the original region,
not the LLC of the bbox) where the region will be restored.
>>> region = renderer.copy_from_bbox()
>>> x1, y1, x2, y2 = region.get_extents()
>>> renderer.restore_region(region, bbox=(x1+dx, y1, x2, y2),
... xy=(x1-dx, y1))
"""
if bbox is not None or xy is not None:
if bbox is None:
x1, y1, x2, y2 = region.get_extents()
elif isinstance(bbox, BboxBase):
x1, y1, x2, y2 = bbox.extents
else:
x1, y1, x2, y2 = bbox
if xy is None:
ox, oy = x1, y1
else:
ox, oy = xy
# The incoming data is float, but the _renderer type-checking wants
# to see integers.
self._renderer.restore_region(region, int(x1), int(y1),
int(x2), int(y2), int(ox), int(oy))
else:
self._renderer.restore_region(region)
def start_filter(self):
"""
Start filtering. It simply create a new canvas (the old one is saved).
"""
self._filter_renderers.append(self._renderer)
self._renderer = _RendererAgg(int(self.width), int(self.height),
self.dpi)
self._update_methods()
def stop_filter(self, post_processing):
"""
Save the plot in the current canvas as a image and apply
the *post_processing* function.
def post_processing(image, dpi):
# ny, nx, depth = image.shape
# image (numpy array) has RGBA channels and has a depth of 4.
...
# create a new_image (numpy array of 4 channels, size can be
# different). The resulting image may have offsets from
# lower-left corner of the original image
return new_image, offset_x, offset_y
The saved renderer is restored and the returned image from
post_processing is plotted (using draw_image) on it.
"""
width, height = int(self.width), int(self.height)
buffer, (l, b, w, h) = self.tostring_rgba_minimized()
self._renderer = self._filter_renderers.pop()
self._update_methods()
if w > 0 and h > 0:
img = np.frombuffer(buffer, np.uint8)
img, ox, oy = post_processing(img.reshape((h, w, 4)) / 255.,
self.dpi)
gc = self.new_gc()
if img.dtype.kind == 'f':
img = np.asarray(img * 255., np.uint8)
img = img[::-1]
self._renderer.draw_image(gc, l + ox, height - b - h + oy, img)
class FigureCanvasAgg(FigureCanvasBase):
"""
The canvas the figure renders into. Calls the draw and print fig
methods, creates the renderers, etc...
Attributes
----------
figure : `matplotlib.figure.Figure`
A high-level Figure instance
"""
def copy_from_bbox(self, bbox):
renderer = self.get_renderer()
return renderer.copy_from_bbox(bbox)
def restore_region(self, region, bbox=None, xy=None):
renderer = self.get_renderer()
return renderer.restore_region(region, bbox, xy)
def draw(self):
"""
Draw the figure using the renderer.
"""
self.renderer = self.get_renderer(cleared=True)
with RendererAgg.lock:
self.figure.draw(self.renderer)
# A GUI class may be need to update a window using this draw, so
# don't forget to call the superclass.
super().draw()
def get_renderer(self, cleared=False):
l, b, w, h = self.figure.bbox.bounds
key = w, h, self.figure.dpi
reuse_renderer = (hasattr(self, "renderer")
and getattr(self, "_lastKey", None) == key)
if not reuse_renderer:
self.renderer = RendererAgg(w, h, self.figure.dpi)
self._lastKey = key
elif cleared:
self.renderer.clear()
return self.renderer
def tostring_rgb(self):
"""Get the image as an RGB byte string.
`draw` must be called at least once before this function will work and
to update the renderer for any subsequent changes to the Figure.
Returns
-------
bytes
"""
return self.renderer.tostring_rgb()
def tostring_argb(self):
"""Get the image as an ARGB byte string.
`draw` must be called at least once before this function will work and
to update the renderer for any subsequent changes to the Figure.
Returns
-------
bytes
"""
return self.renderer.tostring_argb()
def buffer_rgba(self):
"""Get the image as a memoryview to the renderer's buffer.
`draw` must be called at least once before this function will work and
to update the renderer for any subsequent changes to the Figure.
Returns
-------
memoryview
"""
return self.renderer.buffer_rgba()
def print_raw(self, filename_or_obj, *args, **kwargs):
FigureCanvasAgg.draw(self)
renderer = self.get_renderer()
with cbook._setattr_cm(renderer, dpi=self.figure.dpi), \
cbook.open_file_cm(filename_or_obj, "wb") as fh:
fh.write(renderer._renderer.buffer_rgba())
print_rgba = print_raw
def print_png(self, filename_or_obj, *args,
metadata=None, pil_kwargs=None,
**kwargs):
"""
Write the figure to a PNG file.
Parameters
----------
filename_or_obj : str or PathLike or file-like object
The file to write to.
metadata : dict, optional
Metadata in the PNG file as key-value pairs of bytes or latin-1
encodable strings.
According to the PNG specification, keys must be shorter than 79
chars.
The `PNG specification`_ defines some common keywords that may be
used as appropriate:
- Title: Short (one line) title or caption for image.
- Author: Name of image's creator.
- Description: Description of image (possibly long).
- Copyright: Copyright notice.
- Creation Time: Time of original image creation
(usually RFC 1123 format).
- Software: Software used to create the image.
- Disclaimer: Legal disclaimer.
- Warning: Warning of nature of content.
- Source: Device used to create the image.
- Comment: Miscellaneous comment;
conversion from other image format.
Other keywords may be invented for other purposes.
If 'Software' is not given, an autogenerated value for matplotlib
will be used.
For more details see the `PNG specification`_.
.. _PNG specification: \
https://www.w3.org/TR/2003/REC-PNG-20031110/#11keywords
pil_kwargs : dict, optional
If set to a non-None value, use Pillow to save the figure instead
of Matplotlib's builtin PNG support, and pass these keyword
arguments to `PIL.Image.save`.
If the 'pnginfo' key is present, it completely overrides
*metadata*, including the default 'Software' key.
"""
from matplotlib import _png
if metadata is None:
metadata = {}
metadata = {
"Software":
f"matplotlib version{__version__}, http://matplotlib.org/",
**metadata,
}
if pil_kwargs is not None:
from PIL import Image
from PIL.PngImagePlugin import PngInfo
buf, size = self.print_to_buffer()
# Only use the metadata kwarg if pnginfo is not set, because the
# semantics of duplicate keys in pnginfo is unclear.
if "pnginfo" not in pil_kwargs:
pnginfo = PngInfo()
for k, v in metadata.items():
pnginfo.add_text(k, v)
pil_kwargs["pnginfo"] = pnginfo
pil_kwargs.setdefault("dpi", (self.figure.dpi, self.figure.dpi))
(Image.frombuffer("RGBA", size, buf, "raw", "RGBA", 0, 1)
.save(filename_or_obj, format="png", **pil_kwargs))
else:
FigureCanvasAgg.draw(self)
renderer = self.get_renderer()
with cbook._setattr_cm(renderer, dpi=self.figure.dpi), \
cbook.open_file_cm(filename_or_obj, "wb") as fh:
_png.write_png(renderer._renderer, fh,
self.figure.dpi, metadata=metadata)
def print_to_buffer(self):
FigureCanvasAgg.draw(self)
renderer = self.get_renderer()
with cbook._setattr_cm(renderer, dpi=self.figure.dpi):
return (renderer._renderer.buffer_rgba(),
(int(renderer.width), int(renderer.height)))
if _has_pil:
# Note that these methods should typically be called via savefig() and
# print_figure(), and the latter ensures that `self.figure.dpi` already
# matches the dpi kwarg (if any).
def print_jpg(self, filename_or_obj, *args, dryrun=False,
pil_kwargs=None, **kwargs):
"""
Write the figure to a JPEG file.
Parameters
----------
filename_or_obj : str or PathLike or file-like object
The file to write to.
Other Parameters
----------------
quality : int
The image quality, on a scale from 1 (worst) to 100 (best).
The default is :rc:`savefig.jpeg_quality`. Values above
95 should be avoided; 100 completely disables the JPEG
quantization stage.
optimize : bool
If present, indicates that the encoder should
make an extra pass over the image in order to select
optimal encoder settings.
progressive : bool
If present, indicates that this image
should be stored as a progressive JPEG file.
pil_kwargs : dict, optional
Additional keyword arguments that are passed to
`PIL.Image.save` when saving the figure. These take precedence
over *quality*, *optimize* and *progressive*.
"""
buf, size = self.print_to_buffer()
if dryrun:
return
# The image is "pasted" onto a white background image to safely
# handle any transparency
image = Image.frombuffer('RGBA', size, buf, 'raw', 'RGBA', 0, 1)
rgba = mcolors.to_rgba(rcParams['savefig.facecolor'])
color = tuple([int(x * 255) for x in rgba[:3]])
background = Image.new('RGB', size, color)
background.paste(image, image)
if pil_kwargs is None:
pil_kwargs = {}
for k in ["quality", "optimize", "progressive"]:
if k in kwargs:
pil_kwargs.setdefault(k, kwargs[k])
pil_kwargs.setdefault("quality", rcParams["savefig.jpeg_quality"])
pil_kwargs.setdefault("dpi", (self.figure.dpi, self.figure.dpi))
return background.save(
filename_or_obj, format='jpeg', **pil_kwargs)
print_jpeg = print_jpg
def print_tif(self, filename_or_obj, *args, dryrun=False,
pil_kwargs=None, **kwargs):
buf, size = self.print_to_buffer()
if dryrun:
return
image = Image.frombuffer('RGBA', size, buf, 'raw', 'RGBA', 0, 1)
if pil_kwargs is None:
pil_kwargs = {}
pil_kwargs.setdefault("dpi", (self.figure.dpi, self.figure.dpi))
return image.save(filename_or_obj, format='tiff', **pil_kwargs)
print_tiff = print_tif
@_Backend.export
class _BackendAgg(_Backend):
FigureCanvas = FigureCanvasAgg
FigureManager = FigureManagerBase
|
2e64415301a9e691c1870e834d03082b23004d725a71b43e94b2700c03e5b85e
|
"""
MS Windows-specific helper for the TkAgg backend.
With rcParams['tk.window_focus'] default of False, it is
effectively disabled.
It uses a tiny C++ extension module to access MS Win functions.
This module is deprecated and will be removed in version 3.2
"""
from matplotlib import rcParams, cbook
cbook.warn_deprecated('3.0', obj_type='module', name='backends.windowing')
try:
if not rcParams['tk.window_focus']:
raise ImportError
from matplotlib.backends._tkagg import (
Win32_GetForegroundWindow as GetForegroundWindow,
Win32_SetForegroundWindow as SetForegroundWindow)
except ImportError:
def GetForegroundWindow():
return 0
def SetForegroundWindow(hwnd):
pass
class FocusManager(object):
def __init__(self):
self._shellWindow = GetForegroundWindow()
def __del__(self):
SetForegroundWindow(self._shellWindow)
|
ad4a64ce6940b92ffde4caa060f48eb973456b0168707c9ae57a451c9c60c518
|
"""
A PostScript backend, which can produce both PostScript .ps and .eps.
"""
import datetime
import glob
from io import StringIO, TextIOWrapper
import logging
import os
import pathlib
import re
import shutil
import subprocess
from tempfile import TemporaryDirectory
import textwrap
import time
import numpy as np
import matplotlib as mpl
from matplotlib import (
cbook, _path, __version__, rcParams, checkdep_ghostscript)
from matplotlib.backend_bases import (
_Backend, FigureCanvasBase, FigureManagerBase, GraphicsContextBase,
RendererBase)
from matplotlib.cbook import (get_realpath_and_stat, is_writable_file_like,
file_requires_unicode)
from matplotlib.font_manager import is_opentype_cff_font, get_font
from matplotlib.ft2font import KERNING_DEFAULT, LOAD_NO_HINTING
from matplotlib.ttconv import convert_ttf_to_ps
from matplotlib.mathtext import MathTextParser
from matplotlib._mathtext_data import uni2type1
from matplotlib.path import Path
from matplotlib.transforms import Affine2D
from matplotlib.backends.backend_mixed import MixedModeRenderer
from . import _backend_pdf_ps
_log = logging.getLogger(__name__)
backend_version = 'Level II'
debugPS = 0
class PsBackendHelper(object):
def __init__(self):
self._cached = {}
@cbook.deprecated("3.1")
@property
def gs_exe(self):
"""
executable name of ghostscript.
"""
try:
return self._cached["gs_exe"]
except KeyError:
pass
gs_exe, gs_version = checkdep_ghostscript()
if gs_exe is None:
gs_exe = 'gs'
self._cached["gs_exe"] = str(gs_exe)
return str(gs_exe)
@cbook.deprecated("3.1")
@property
def gs_version(self):
"""
version of ghostscript.
"""
try:
return self._cached["gs_version"]
except KeyError:
pass
s = subprocess.Popen(
[self.gs_exe, "--version"], stdout=subprocess.PIPE)
pipe, stderr = s.communicate()
ver = pipe.decode('ascii')
try:
gs_version = tuple(map(int, ver.strip().split(".")))
except ValueError:
# if something went wrong parsing return null version number
gs_version = (0, 0)
self._cached["gs_version"] = gs_version
return gs_version
@cbook.deprecated("3.1")
@property
def supports_ps2write(self):
"""
True if the installed ghostscript supports ps2write device.
"""
return self.gs_version[0] >= 9
ps_backend_helper = PsBackendHelper()
papersize = {'letter': (8.5, 11),
'legal': (8.5, 14),
'ledger': (11, 17),
'a0': (33.11, 46.81),
'a1': (23.39, 33.11),
'a2': (16.54, 23.39),
'a3': (11.69, 16.54),
'a4': (8.27, 11.69),
'a5': (5.83, 8.27),
'a6': (4.13, 5.83),
'a7': (2.91, 4.13),
'a8': (2.07, 2.91),
'a9': (1.457, 2.05),
'a10': (1.02, 1.457),
'b0': (40.55, 57.32),
'b1': (28.66, 40.55),
'b2': (20.27, 28.66),
'b3': (14.33, 20.27),
'b4': (10.11, 14.33),
'b5': (7.16, 10.11),
'b6': (5.04, 7.16),
'b7': (3.58, 5.04),
'b8': (2.51, 3.58),
'b9': (1.76, 2.51),
'b10': (1.26, 1.76)}
def _get_papertype(w, h):
for key, (pw, ph) in sorted(papersize.items(), reverse=True):
if key.startswith('l'):
continue
if w < pw and h < ph:
return key
return 'a0'
def _num_to_str(val):
if isinstance(val, str):
return val
ival = int(val)
if val == ival:
return str(ival)
s = "%1.3f" % val
s = s.rstrip("0")
s = s.rstrip(".")
return s
def _nums_to_str(*args):
return ' '.join(map(_num_to_str, args))
def quote_ps_string(s):
"Quote dangerous characters of S for use in a PostScript string constant."
s = s.replace(b"\\", b"\\\\")
s = s.replace(b"(", b"\\(")
s = s.replace(b")", b"\\)")
s = s.replace(b"'", b"\\251")
s = s.replace(b"`", b"\\301")
s = re.sub(br"[^ -~\n]", lambda x: br"\%03o" % ord(x.group()), s)
return s.decode('ascii')
def _move_path_to_path_or_stream(src, dst):
"""
Move the contents of file at *src* to path-or-filelike *dst*.
If *dst* is a path, the metadata of *src* are *not* copied.
"""
if is_writable_file_like(dst):
fh = (open(src, 'r', encoding='latin-1')
if file_requires_unicode(dst)
else open(src, 'rb'))
with fh:
shutil.copyfileobj(fh, dst)
else:
shutil.move(src, dst, copy_function=shutil.copyfile)
class RendererPS(_backend_pdf_ps.RendererPDFPSBase):
"""
The renderer handles all the drawing primitives using a graphics
context instance that controls the colors/styles.
"""
@property
@cbook.deprecated("3.1")
def afmfontd(self, _cache=cbook.maxdict(50)):
return _cache
_afm_font_dir = pathlib.Path(rcParams["datapath"], "fonts", "afm")
_use_afm_rc_name = "ps.useafm"
def __init__(self, width, height, pswriter, imagedpi=72):
# Although postscript itself is dpi independent, we need to inform the
# image code about a requested dpi to generate high resolution images
# and them scale them before embedding them.
RendererBase.__init__(self)
self.width = width
self.height = height
self._pswriter = pswriter
if rcParams['text.usetex']:
self.textcnt = 0
self.psfrag = []
self.imagedpi = imagedpi
# current renderer state (None=uninitialised)
self.color = None
self.linewidth = None
self.linejoin = None
self.linecap = None
self.linedash = None
self.fontname = None
self.fontsize = None
self._hatches = {}
self.image_magnification = imagedpi / 72
self._clip_paths = {}
self._path_collection_id = 0
self.used_characters = {}
self.mathtext_parser = MathTextParser("PS")
def track_characters(self, font, s):
"""Keeps track of which characters are required from each font."""
realpath, stat_key = get_realpath_and_stat(font.fname)
used_characters = self.used_characters.setdefault(
stat_key, (realpath, set()))
used_characters[1].update(map(ord, s))
def merge_used_characters(self, other):
for stat_key, (realpath, charset) in other.items():
used_characters = self.used_characters.setdefault(
stat_key, (realpath, set()))
used_characters[1].update(charset)
def set_color(self, r, g, b, store=1):
if (r, g, b) != self.color:
if r == g and r == b:
self._pswriter.write("%1.3f setgray\n" % r)
else:
self._pswriter.write(
"%1.3f %1.3f %1.3f setrgbcolor\n" % (r, g, b))
if store:
self.color = (r, g, b)
def set_linewidth(self, linewidth, store=1):
linewidth = float(linewidth)
if linewidth != self.linewidth:
self._pswriter.write("%1.3f setlinewidth\n" % linewidth)
if store:
self.linewidth = linewidth
def set_linejoin(self, linejoin, store=1):
if linejoin != self.linejoin:
self._pswriter.write("%d setlinejoin\n" % linejoin)
if store:
self.linejoin = linejoin
def set_linecap(self, linecap, store=1):
if linecap != self.linecap:
self._pswriter.write("%d setlinecap\n" % linecap)
if store:
self.linecap = linecap
def set_linedash(self, offset, seq, store=1):
if self.linedash is not None:
oldo, oldseq = self.linedash
if np.array_equal(seq, oldseq) and oldo == offset:
return
if seq is not None and len(seq):
s = "[%s] %d setdash\n" % (_nums_to_str(*seq), offset)
self._pswriter.write(s)
else:
self._pswriter.write("[] 0 setdash\n")
if store:
self.linedash = (offset, seq)
def set_font(self, fontname, fontsize, store=1):
if rcParams['ps.useafm']:
return
if (fontname, fontsize) != (self.fontname, self.fontsize):
out = ("/%s findfont\n"
"%1.3f scalefont\n"
"setfont\n" % (fontname, fontsize))
self._pswriter.write(out)
if store:
self.fontname = fontname
self.fontsize = fontsize
def create_hatch(self, hatch):
sidelen = 72
if hatch in self._hatches:
return self._hatches[hatch]
name = 'H%d' % len(self._hatches)
linewidth = rcParams['hatch.linewidth']
pageheight = self.height * 72
self._pswriter.write("""\
<< /PatternType 1
/PaintType 2
/TilingType 2
/BBox[0 0 %(sidelen)d %(sidelen)d]
/XStep %(sidelen)d
/YStep %(sidelen)d
/PaintProc {
pop
%(linewidth)f setlinewidth
""" % locals())
self._pswriter.write(
self._convert_path(Path.hatch(hatch), Affine2D().scale(sidelen),
simplify=False))
self._pswriter.write("""\
fill
stroke
} bind
>>
matrix
0.0 %(pageheight)f translate
makepattern
/%(name)s exch def
""" % locals())
self._hatches[hatch] = name
return name
def get_image_magnification(self):
"""
Get the factor by which to magnify images passed to draw_image.
Allows a backend to have images at a different resolution to other
artists.
"""
return self.image_magnification
def draw_image(self, gc, x, y, im, transform=None):
# docstring inherited
h, w = im.shape[:2]
imagecmd = "false 3 colorimage"
data = im[::-1, :, :3] # Vertically flipped rgb values.
# data.tobytes().hex() has no spaces, so can be linewrapped by relying
# on textwrap.fill breaking long words.
hexlines = textwrap.fill(data.tobytes().hex(), 128)
if transform is None:
matrix = "1 0 0 1 0 0"
xscale = w / self.image_magnification
yscale = h / self.image_magnification
else:
matrix = " ".join(map(str, transform.frozen().to_values()))
xscale = 1.0
yscale = 1.0
figh = self.height * 72
bbox = gc.get_clip_rectangle()
clippath, clippath_trans = gc.get_clip_path()
clip = []
if bbox is not None:
clipx, clipy, clipw, cliph = bbox.bounds
clip.append(
'%s clipbox' % _nums_to_str(clipw, cliph, clipx, clipy))
if clippath is not None:
id = self._get_clip_path(clippath, clippath_trans)
clip.append('%s' % id)
clip = '\n'.join(clip)
ps = """gsave
%(clip)s
%(x)s %(y)s translate
[%(matrix)s] concat
%(xscale)s %(yscale)s scale
/DataString %(w)s string def
%(w)s %(h)s 8 [ %(w)s 0 0 -%(h)s 0 %(h)s ]
{
currentfile DataString readhexstring pop
} bind %(imagecmd)s
%(hexlines)s
grestore
""" % locals()
self._pswriter.write(ps)
def _convert_path(self, path, transform, clip=False, simplify=None):
if clip:
clip = (0.0, 0.0, self.width * 72.0, self.height * 72.0)
else:
clip = None
return _path.convert_to_string(
path, transform, clip, simplify, None,
6, [b'm', b'l', b'', b'c', b'cl'], True).decode('ascii')
def _get_clip_path(self, clippath, clippath_transform):
key = (clippath, id(clippath_transform))
pid = self._clip_paths.get(key)
if pid is None:
pid = 'c%x' % len(self._clip_paths)
ps_cmd = ['/%s {' % pid]
ps_cmd.append(self._convert_path(clippath, clippath_transform,
simplify=False))
ps_cmd.extend(['clip', 'newpath', '} bind def\n'])
self._pswriter.write('\n'.join(ps_cmd))
self._clip_paths[key] = pid
return pid
def draw_path(self, gc, path, transform, rgbFace=None):
# docstring inherited
clip = rgbFace is None and gc.get_hatch_path() is None
simplify = path.should_simplify and clip
ps = self._convert_path(path, transform, clip=clip, simplify=simplify)
self._draw_ps(ps, gc, rgbFace)
def draw_markers(
self, gc, marker_path, marker_trans, path, trans, rgbFace=None):
# docstring inherited
if debugPS:
self._pswriter.write('% draw_markers \n')
ps_color = (
None
if _is_transparent(rgbFace)
else '%1.3f setgray' % rgbFace[0]
if rgbFace[0] == rgbFace[1] == rgbFace[2]
else '%1.3f %1.3f %1.3f setrgbcolor' % rgbFace[:3])
# construct the generic marker command:
# don't want the translate to be global
ps_cmd = ['/o {', 'gsave', 'newpath', 'translate']
lw = gc.get_linewidth()
alpha = (gc.get_alpha()
if gc.get_forced_alpha() or len(gc.get_rgb()) == 3
else gc.get_rgb()[3])
stroke = lw > 0 and alpha > 0
if stroke:
ps_cmd.append('%.1f setlinewidth' % lw)
jint = gc.get_joinstyle()
ps_cmd.append('%d setlinejoin' % jint)
cint = gc.get_capstyle()
ps_cmd.append('%d setlinecap' % cint)
ps_cmd.append(self._convert_path(marker_path, marker_trans,
simplify=False))
if rgbFace:
if stroke:
ps_cmd.append('gsave')
if ps_color:
ps_cmd.extend([ps_color, 'fill'])
if stroke:
ps_cmd.append('grestore')
if stroke:
ps_cmd.append('stroke')
ps_cmd.extend(['grestore', '} bind def'])
for vertices, code in path.iter_segments(
trans,
clip=(0, 0, self.width*72, self.height*72),
simplify=False):
if len(vertices):
x, y = vertices[-2:]
ps_cmd.append("%g %g o" % (x, y))
ps = '\n'.join(ps_cmd)
self._draw_ps(ps, gc, rgbFace, fill=False, stroke=False)
def draw_path_collection(self, gc, master_transform, paths, all_transforms,
offsets, offsetTrans, facecolors, edgecolors,
linewidths, linestyles, antialiaseds, urls,
offset_position):
# Is the optimization worth it? Rough calculation:
# cost of emitting a path in-line is
# (len_path + 2) * uses_per_path
# cost of definition+use is
# (len_path + 3) + 3 * uses_per_path
len_path = len(paths[0].vertices) if len(paths) > 0 else 0
uses_per_path = self._iter_collection_uses_per_path(
paths, all_transforms, offsets, facecolors, edgecolors)
should_do_optimization = \
len_path + 3 * uses_per_path + 3 < (len_path + 2) * uses_per_path
if not should_do_optimization:
return RendererBase.draw_path_collection(
self, gc, master_transform, paths, all_transforms,
offsets, offsetTrans, facecolors, edgecolors,
linewidths, linestyles, antialiaseds, urls,
offset_position)
write = self._pswriter.write
path_codes = []
for i, (path, transform) in enumerate(self._iter_collection_raw_paths(
master_transform, paths, all_transforms)):
name = 'p%x_%x' % (self._path_collection_id, i)
ps_cmd = ['/%s {' % name,
'newpath', 'translate']
ps_cmd.append(self._convert_path(path, transform, simplify=False))
ps_cmd.extend(['} bind def\n'])
write('\n'.join(ps_cmd))
path_codes.append(name)
for xo, yo, path_id, gc0, rgbFace in self._iter_collection(
gc, master_transform, all_transforms, path_codes, offsets,
offsetTrans, facecolors, edgecolors, linewidths, linestyles,
antialiaseds, urls, offset_position):
ps = "%g %g %s" % (xo, yo, path_id)
self._draw_ps(ps, gc0, rgbFace)
self._path_collection_id += 1
def draw_tex(self, gc, x, y, s, prop, angle, ismath='TeX!', mtext=None):
# docstring inherited
w, h, bl = self.get_text_width_height_descent(s, prop, ismath)
fontsize = prop.get_size_in_points()
thetext = 'psmarker%d' % self.textcnt
color = '%1.3f,%1.3f,%1.3f' % gc.get_rgb()[:3]
fontcmd = {'sans-serif': r'{\sffamily %s}',
'monospace': r'{\ttfamily %s}'}.get(
rcParams['font.family'][0], r'{\rmfamily %s}')
s = fontcmd % s
tex = r'\color[rgb]{%s} %s' % (color, s)
corr = 0 # w/2*(fontsize-10)/10
if rcParams['text.latex.preview']:
# use baseline alignment!
pos = _nums_to_str(x-corr, y)
self.psfrag.append(
r'\psfrag{%s}[Bl][Bl][1][%f]{\fontsize{%f}{%f}%s}' % (
thetext, angle, fontsize, fontsize*1.25, tex))
else:
# Stick to the bottom alignment, but this may give incorrect
# baseline some times.
pos = _nums_to_str(x-corr, y-bl)
self.psfrag.append(
r'\psfrag{%s}[bl][bl][1][%f]{\fontsize{%f}{%f}%s}' % (
thetext, angle, fontsize, fontsize*1.25, tex))
ps = """\
gsave
%(pos)s moveto
(%(thetext)s)
show
grestore
""" % locals()
self._pswriter.write(ps)
self.textcnt += 1
def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
# docstring inherited
# local to avoid repeated attribute lookups
write = self._pswriter.write
if debugPS:
write("% text\n")
if _is_transparent(gc.get_rgb()):
return # Special handling for fully transparent.
if ismath == 'TeX':
return self.draw_tex(gc, x, y, s, prop, angle)
elif ismath:
return self.draw_mathtext(gc, x, y, s, prop, angle)
elif rcParams['ps.useafm']:
self.set_color(*gc.get_rgb())
font = self._get_font_afm(prop)
fontname = font.get_fontname()
fontsize = prop.get_size_in_points()
scale = 0.001 * fontsize
thisx = 0
thisy = font.get_str_bbox_and_descent(s)[4] * scale
last_name = None
lines = []
for c in s:
name = uni2type1.get(ord(c), 'question')
try:
width = font.get_width_from_char_name(name)
except KeyError:
name = 'question'
width = font.get_width_char('?')
if last_name is not None:
kern = font.get_kern_dist_from_name(last_name, name)
else:
kern = 0
last_name = name
thisx += kern * scale
lines.append('%f %f m /%s glyphshow' % (thisx, thisy, name))
thisx += width * scale
thetext = "\n".join(lines)
ps = """\
gsave
/%(fontname)s findfont
%(fontsize)s scalefont
setfont
%(x)f %(y)f translate
%(angle)f rotate
%(thetext)s
grestore
""" % locals()
self._pswriter.write(ps)
else:
font = self._get_font_ttf(prop)
font.set_text(s, 0, flags=LOAD_NO_HINTING)
self.track_characters(font, s)
self.set_color(*gc.get_rgb())
ps_name = (font.postscript_name
.encode('ascii', 'replace').decode('ascii'))
self.set_font(ps_name, prop.get_size_in_points())
lastgind = None
lines = []
thisx = 0
thisy = 0
for c in s:
ccode = ord(c)
gind = font.get_char_index(ccode)
if gind is None:
ccode = ord('?')
name = '.notdef'
gind = 0
else:
name = font.get_glyph_name(gind)
glyph = font.load_char(ccode, flags=LOAD_NO_HINTING)
if lastgind is not None:
kern = font.get_kerning(lastgind, gind, KERNING_DEFAULT)
else:
kern = 0
lastgind = gind
thisx += kern / 64
lines.append('%f %f m /%s glyphshow' % (thisx, thisy, name))
thisx += glyph.linearHoriAdvance / 65536
thetext = '\n'.join(lines)
ps = """gsave
%(x)f %(y)f translate
%(angle)f rotate
%(thetext)s
grestore
""" % locals()
self._pswriter.write(ps)
def new_gc(self):
# docstring inherited
return GraphicsContextPS()
def draw_mathtext(self, gc, x, y, s, prop, angle):
"""Draw the math text using matplotlib.mathtext."""
if debugPS:
self._pswriter.write("% mathtext\n")
width, height, descent, pswriter, used_characters = \
self.mathtext_parser.parse(s, 72, prop)
self.merge_used_characters(used_characters)
self.set_color(*gc.get_rgb())
thetext = pswriter.getvalue()
ps = """gsave
%(x)f %(y)f translate
%(angle)f rotate
%(thetext)s
grestore
""" % locals()
self._pswriter.write(ps)
def draw_gouraud_triangle(self, gc, points, colors, trans):
self.draw_gouraud_triangles(gc, points.reshape((1, 3, 2)),
colors.reshape((1, 3, 4)), trans)
def draw_gouraud_triangles(self, gc, points, colors, trans):
assert len(points) == len(colors)
assert points.ndim == 3
assert points.shape[1] == 3
assert points.shape[2] == 2
assert colors.ndim == 3
assert colors.shape[1] == 3
assert colors.shape[2] == 4
shape = points.shape
flat_points = points.reshape((shape[0] * shape[1], 2))
flat_points = trans.transform(flat_points)
flat_colors = colors.reshape((shape[0] * shape[1], 4))
points_min = np.min(flat_points, axis=0) - (1 << 12)
points_max = np.max(flat_points, axis=0) + (1 << 12)
factor = np.ceil((2 ** 32 - 1) / (points_max - points_min))
xmin, ymin = points_min
xmax, ymax = points_max
streamarr = np.empty(
(shape[0] * shape[1],),
dtype=[('flags', 'u1'),
('points', '>u4', (2,)),
('colors', 'u1', (3,))])
streamarr['flags'] = 0
streamarr['points'] = (flat_points - points_min) * factor
streamarr['colors'] = flat_colors[:, :3] * 255.0
stream = quote_ps_string(streamarr.tostring())
self._pswriter.write("""
gsave
<< /ShadingType 4
/ColorSpace [/DeviceRGB]
/BitsPerCoordinate 32
/BitsPerComponent 8
/BitsPerFlag 8
/AntiAlias true
/Decode [ %(xmin)f %(xmax)f %(ymin)f %(ymax)f 0 1 0 1 0 1 ]
/DataSource (%(stream)s)
>>
shfill
grestore
""" % locals())
def _draw_ps(self, ps, gc, rgbFace, fill=True, stroke=True, command=None):
"""
Emit the PostScript snippet 'ps' with all the attributes from 'gc'
applied. 'ps' must consist of PostScript commands to construct a path.
The fill and/or stroke kwargs can be set to False if the
'ps' string already includes filling and/or stroking, in
which case _draw_ps is just supplying properties and
clipping.
"""
# local variable eliminates all repeated attribute lookups
write = self._pswriter.write
if debugPS and command:
write("% "+command+"\n")
mightstroke = (gc.get_linewidth() > 0
and not _is_transparent(gc.get_rgb()))
if not mightstroke:
stroke = False
if _is_transparent(rgbFace):
fill = False
hatch = gc.get_hatch()
if mightstroke:
self.set_linewidth(gc.get_linewidth())
jint = gc.get_joinstyle()
self.set_linejoin(jint)
cint = gc.get_capstyle()
self.set_linecap(cint)
self.set_linedash(*gc.get_dashes())
self.set_color(*gc.get_rgb()[:3])
write('gsave\n')
cliprect = gc.get_clip_rectangle()
if cliprect:
x, y, w, h = cliprect.bounds
write('%1.4g %1.4g %1.4g %1.4g clipbox\n' % (w, h, x, y))
clippath, clippath_trans = gc.get_clip_path()
if clippath:
id = self._get_clip_path(clippath, clippath_trans)
write('%s\n' % id)
# Jochen, is the strip necessary? - this could be a honking big string
write(ps.strip())
write("\n")
if fill:
if stroke or hatch:
write("gsave\n")
self.set_color(store=0, *rgbFace[:3])
write("fill\n")
if stroke or hatch:
write("grestore\n")
if hatch:
hatch_name = self.create_hatch(hatch)
write("gsave\n")
write("%f %f %f " % gc.get_hatch_color()[:3])
write("%s setpattern fill grestore\n" % hatch_name)
if stroke:
write("stroke\n")
write("grestore\n")
def _is_transparent(rgb_or_rgba):
if rgb_or_rgba is None:
return True # Consistent with rgbFace semantics.
elif len(rgb_or_rgba) == 4:
if rgb_or_rgba[3] == 0:
return True
if rgb_or_rgba[3] != 1:
_log.warning(
"The PostScript backend does not support transparency; "
"partially transparent artists will be rendered opaque.")
return False
else: # len() == 3.
return False
class GraphicsContextPS(GraphicsContextBase):
def get_capstyle(self):
return {'butt': 0, 'round': 1, 'projecting': 2}[
GraphicsContextBase.get_capstyle(self)]
def get_joinstyle(self):
return {'miter': 0, 'round': 1, 'bevel': 2}[
GraphicsContextBase.get_joinstyle(self)]
@cbook.deprecated("3.1")
def shouldstroke(self):
return (self.get_linewidth() > 0.0 and
(len(self.get_rgb()) <= 3 or self.get_rgb()[3] != 0.0))
class FigureCanvasPS(FigureCanvasBase):
fixed_dpi = 72
def draw(self):
pass
filetypes = {'ps': 'Postscript',
'eps': 'Encapsulated Postscript'}
def get_default_filetype(self):
return 'ps'
def print_ps(self, outfile, *args, **kwargs):
return self._print_ps(outfile, 'ps', *args, **kwargs)
def print_eps(self, outfile, *args, **kwargs):
return self._print_ps(outfile, 'eps', *args, **kwargs)
def _print_ps(self, outfile, format, *args,
papertype=None, dpi=72, facecolor='w', edgecolor='w',
orientation='portrait',
**kwargs):
if papertype is None:
papertype = rcParams['ps.papersize']
papertype = papertype.lower()
if papertype == 'auto':
pass
elif papertype not in papersize:
raise RuntimeError('%s is not a valid papertype. Use one of %s' %
(papertype, ', '.join(papersize)))
orientation = orientation.lower()
cbook._check_in_list(['landscape', 'portrait'],
orientation=orientation)
isLandscape = (orientation == 'landscape')
self.figure.set_dpi(72) # Override the dpi kwarg
if rcParams['text.usetex']:
self._print_figure_tex(outfile, format, dpi, facecolor, edgecolor,
orientation, isLandscape, papertype,
**kwargs)
else:
self._print_figure(outfile, format, dpi, facecolor, edgecolor,
orientation, isLandscape, papertype,
**kwargs)
def _print_figure(
self, outfile, format, dpi=72, facecolor='w', edgecolor='w',
orientation='portrait', isLandscape=False, papertype=None,
metadata=None, *,
dryrun=False, bbox_inches_restore=None, **kwargs):
"""
Render the figure to hardcopy. Set the figure patch face and
edge colors. This is useful because some of the GUIs have a
gray figure face color background and you'll probably want to
override this on hardcopy
If outfile is a string, it is interpreted as a file name.
If the extension matches .ep* write encapsulated postscript,
otherwise write a stand-alone PostScript file.
If outfile is a file object, a stand-alone PostScript file is
written into this file object.
metadata must be a dictionary. Currently, only the value for
the key 'Creator' is used.
"""
isEPSF = format == 'eps'
if isinstance(outfile, (str, os.PathLike)):
outfile = title = os.fspath(outfile)
title = title.encode("ascii", "replace").decode("ascii")
passed_in_file_object = False
elif is_writable_file_like(outfile):
title = None
passed_in_file_object = True
else:
raise ValueError("outfile must be a path or a file-like object")
# find the appropriate papertype
width, height = self.figure.get_size_inches()
if papertype == 'auto':
if isLandscape:
papertype = _get_papertype(height, width)
else:
papertype = _get_papertype(width, height)
if isLandscape:
paperHeight, paperWidth = papersize[papertype]
else:
paperWidth, paperHeight = papersize[papertype]
if rcParams['ps.usedistiller'] and not papertype == 'auto':
# distillers will improperly clip eps files if the pagesize is
# too small
if width > paperWidth or height > paperHeight:
if isLandscape:
papertype = _get_papertype(height, width)
paperHeight, paperWidth = papersize[papertype]
else:
papertype = _get_papertype(width, height)
paperWidth, paperHeight = papersize[papertype]
# center the figure on the paper
xo = 72 * 0.5 * (paperWidth - width)
yo = 72 * 0.5 * (paperHeight - height)
l, b, w, h = self.figure.bbox.bounds
llx = xo
lly = yo
urx = llx + w
ury = lly + h
rotation = 0
if isLandscape:
llx, lly, urx, ury = lly, llx, ury, urx
xo, yo = 72 * paperHeight - yo, xo
rotation = 90
bbox = (llx, lly, urx, ury)
# generate PostScript code for the figure and store it in a string
origfacecolor = self.figure.get_facecolor()
origedgecolor = self.figure.get_edgecolor()
self.figure.set_facecolor(facecolor)
self.figure.set_edgecolor(edgecolor)
if dryrun:
class NullWriter(object):
def write(self, *args, **kwargs):
pass
self._pswriter = NullWriter()
else:
self._pswriter = StringIO()
# mixed mode rendering
ps_renderer = RendererPS(width, height, self._pswriter, imagedpi=dpi)
renderer = MixedModeRenderer(
self.figure, width, height, dpi, ps_renderer,
bbox_inches_restore=bbox_inches_restore)
self.figure.draw(renderer)
if dryrun: # return immediately if dryrun (tightbbox=True)
return
self.figure.set_facecolor(origfacecolor)
self.figure.set_edgecolor(origedgecolor)
# check for custom metadata
if metadata is not None and 'Creator' in metadata:
creator_str = metadata['Creator']
else:
creator_str = "matplotlib version " + __version__ + \
", http://matplotlib.org/"
def print_figure_impl(fh):
# write the PostScript headers
if isEPSF:
print("%!PS-Adobe-3.0 EPSF-3.0", file=fh)
else:
print("%!PS-Adobe-3.0\n"
"%%DocumentPaperSizes: {papertype}\n"
"%%Pages: 1\n".format(papertype=papertype),
end="", file=fh)
if title:
print("%%Title: " + title, file=fh)
# get source date from SOURCE_DATE_EPOCH, if set
# See https://reproducible-builds.org/specs/source-date-epoch/
source_date_epoch = os.getenv("SOURCE_DATE_EPOCH")
if source_date_epoch:
source_date = datetime.datetime.utcfromtimestamp(
int(source_date_epoch)).strftime("%a %b %d %H:%M:%S %Y")
else:
source_date = time.ctime()
print("%%Creator: {creator_str}\n"
"%%CreationDate: {source_date}\n"
"%%Orientation: {orientation}\n"
"%%BoundingBox: {bbox[0]} {bbox[1]} {bbox[2]} {bbox[3]}\n"
"%%EndComments\n"
.format(creator_str=creator_str, source_date=source_date,
orientation=orientation, bbox=bbox),
end="", file=fh)
Ndict = len(psDefs)
print("%%BeginProlog", file=fh)
if not rcParams['ps.useafm']:
Ndict += len(ps_renderer.used_characters)
print("/mpldict %d dict def" % Ndict, file=fh)
print("mpldict begin", file=fh)
for d in psDefs:
d = d.strip()
for l in d.split('\n'):
print(l.strip(), file=fh)
if not rcParams['ps.useafm']:
for font_filename, chars in \
ps_renderer.used_characters.values():
if len(chars):
font = get_font(font_filename)
glyph_ids = [font.get_char_index(c) for c in chars]
fonttype = rcParams['ps.fonttype']
# Can not use more than 255 characters from a
# single font for Type 3
if len(glyph_ids) > 255:
fonttype = 42
# The ttf to ps (subsetting) support doesn't work for
# OpenType fonts that are Postscript inside (like the
# STIX fonts). This will simply turn that off to avoid
# errors.
if is_opentype_cff_font(font_filename):
raise RuntimeError(
"OpenType CFF fonts can not be saved using "
"the internal Postscript backend at this "
"time; consider using the Cairo backend")
else:
fh.flush()
try:
convert_ttf_to_ps(os.fsencode(font_filename),
fh, fonttype, glyph_ids)
except RuntimeError:
_log.warning("The PostScript backend does not "
"currently support the selected "
"font.")
raise
print("end", file=fh)
print("%%EndProlog", file=fh)
if not isEPSF:
print("%%Page: 1 1", file=fh)
print("mpldict begin", file=fh)
print("%s translate" % _nums_to_str(xo, yo), file=fh)
if rotation:
print("%d rotate" % rotation, file=fh)
print("%s clipbox" % _nums_to_str(width*72, height*72, 0, 0),
file=fh)
# write the figure
content = self._pswriter.getvalue()
if not isinstance(content, str):
content = content.decode('ascii')
print(content, file=fh)
# write the trailer
print("end", file=fh)
print("showpage", file=fh)
if not isEPSF:
print("%%EOF", file=fh)
fh.flush()
if rcParams['ps.usedistiller']:
# We are going to use an external program to process the output.
# Write to a temporary file.
with TemporaryDirectory() as tmpdir:
tmpfile = os.path.join(tmpdir, "tmp.ps")
with open(tmpfile, 'w', encoding='latin-1') as fh:
print_figure_impl(fh)
if rcParams['ps.usedistiller'] == 'ghostscript':
gs_distill(tmpfile, isEPSF, ptype=papertype, bbox=bbox)
elif rcParams['ps.usedistiller'] == 'xpdf':
xpdf_distill(tmpfile, isEPSF, ptype=papertype, bbox=bbox)
_move_path_to_path_or_stream(tmpfile, outfile)
else:
# Write directly to outfile.
if passed_in_file_object:
requires_unicode = file_requires_unicode(outfile)
if not requires_unicode:
fh = TextIOWrapper(outfile, encoding="latin-1")
# Prevent the TextIOWrapper from closing the underlying
# file.
fh.close = lambda: None
else:
fh = outfile
print_figure_impl(fh)
else:
with open(outfile, 'w', encoding='latin-1') as fh:
print_figure_impl(fh)
def _print_figure_tex(
self, outfile, format, dpi, facecolor, edgecolor,
orientation, isLandscape, papertype, metadata=None, *,
dryrun=False, bbox_inches_restore=None, **kwargs):
"""
If text.usetex is True in rc, a temporary pair of tex/eps files
are created to allow tex to manage the text layout via the PSFrags
package. These files are processed to yield the final ps or eps file.
metadata must be a dictionary. Currently, only the value for
the key 'Creator' is used.
"""
isEPSF = format == 'eps'
if is_writable_file_like(outfile):
title = None
else:
try:
title = os.fspath(outfile)
except TypeError:
raise ValueError(
"outfile must be a path or a file-like object")
self.figure.dpi = 72 # ignore the dpi kwarg
width, height = self.figure.get_size_inches()
xo = 0
yo = 0
l, b, w, h = self.figure.bbox.bounds
llx = xo
lly = yo
urx = llx + w
ury = lly + h
bbox = (llx, lly, urx, ury)
# generate PostScript code for the figure and store it in a string
origfacecolor = self.figure.get_facecolor()
origedgecolor = self.figure.get_edgecolor()
self.figure.set_facecolor(facecolor)
self.figure.set_edgecolor(edgecolor)
if dryrun:
class NullWriter(object):
def write(self, *args, **kwargs):
pass
self._pswriter = NullWriter()
else:
self._pswriter = StringIO()
# mixed mode rendering
ps_renderer = RendererPS(width, height, self._pswriter, imagedpi=dpi)
renderer = MixedModeRenderer(self.figure,
width, height, dpi, ps_renderer,
bbox_inches_restore=bbox_inches_restore)
self.figure.draw(renderer)
if dryrun: # return immediately if dryrun (tightbbox=True)
return
self.figure.set_facecolor(origfacecolor)
self.figure.set_edgecolor(origedgecolor)
# check for custom metadata
if metadata is not None and 'Creator' in metadata:
creator_str = metadata['Creator']
else:
creator_str = "matplotlib version " + __version__ + \
", http://matplotlib.org/"
# write to a temp file, we'll move it to outfile when done
with TemporaryDirectory() as tmpdir:
tmpfile = os.path.join(tmpdir, "tmp.ps")
with open(tmpfile, 'w', encoding='latin-1') as fh:
# write the Encapsulated PostScript headers
print("%!PS-Adobe-3.0 EPSF-3.0", file=fh)
if title:
print("%%Title: "+title, file=fh)
# get source date from SOURCE_DATE_EPOCH, if set
# See https://reproducible-builds.org/specs/source-date-epoch/
source_date_epoch = os.getenv("SOURCE_DATE_EPOCH")
if source_date_epoch:
source_date = datetime.datetime.utcfromtimestamp(
int(source_date_epoch)).strftime(
"%a %b %d %H:%M:%S %Y")
else:
source_date = time.ctime()
print(
"%%Creator: {creator_str}\n"
"%%CreationDate: {source_date}\n"
"%%BoundingBox: {bbox[0]} {bbox[1]} {bbox[2]} {bbox[3]}\n"
"%%EndComments\n"
.format(creator_str=creator_str, source_date=source_date,
bbox=bbox),
end="", file=fh)
print("%%BeginProlog\n"
"/mpldict {len_psDefs} dict def\n"
"mpldict begin\n"
"{psDefs}\n"
"end\n"
"%%EndProlog\n"
.format(len_psDefs=len(psDefs),
psDefs="\n".join(psDefs)),
end="", file=fh)
print("mpldict begin", file=fh)
print("%s translate" % _nums_to_str(xo, yo), file=fh)
print("%s clipbox" % _nums_to_str(width*72, height*72, 0, 0),
file=fh)
# write the figure
print(self._pswriter.getvalue(), file=fh)
# write the trailer
print("end", file=fh)
print("showpage", file=fh)
fh.flush()
if isLandscape: # now we are ready to rotate
isLandscape = True
width, height = height, width
bbox = (lly, llx, ury, urx)
# set the paper size to the figure size if isEPSF. The
# resulting ps file has the given size with correct bounding
# box so that there is no need to call 'pstoeps'
if isEPSF:
paperWidth, paperHeight = self.figure.get_size_inches()
if isLandscape:
paperWidth, paperHeight = paperHeight, paperWidth
else:
temp_papertype = _get_papertype(width, height)
if papertype == 'auto':
papertype = temp_papertype
paperWidth, paperHeight = papersize[temp_papertype]
else:
paperWidth, paperHeight = papersize[papertype]
if (width > paperWidth or height > paperHeight) and isEPSF:
paperWidth, paperHeight = papersize[temp_papertype]
_log.info('Your figure is too big to fit on %s paper. '
'%s paper will be used to prevent clipping.',
papertype, temp_papertype)
texmanager = ps_renderer.get_texmanager()
font_preamble = texmanager.get_font_preamble()
custom_preamble = texmanager.get_custom_preamble()
psfrag_rotated = convert_psfrags(tmpfile, ps_renderer.psfrag,
font_preamble,
custom_preamble, paperWidth,
paperHeight,
orientation)
if (rcParams['ps.usedistiller'] == 'ghostscript'
or rcParams['text.usetex']):
gs_distill(tmpfile, isEPSF, ptype=papertype, bbox=bbox,
rotated=psfrag_rotated)
elif rcParams['ps.usedistiller'] == 'xpdf':
xpdf_distill(tmpfile, isEPSF, ptype=papertype, bbox=bbox,
rotated=psfrag_rotated)
_move_path_to_path_or_stream(tmpfile, outfile)
def convert_psfrags(tmpfile, psfrags, font_preamble, custom_preamble,
paperWidth, paperHeight, orientation):
"""
When we want to use the LaTeX backend with postscript, we write PSFrag tags
to a temporary postscript file, each one marking a position for LaTeX to
render some text. convert_psfrags generates a LaTeX document containing the
commands to convert those tags to text. LaTeX/dvips produces the postscript
file that includes the actual text.
"""
tmpdir = os.path.split(tmpfile)[0]
epsfile = tmpfile+'.eps'
shutil.move(tmpfile, epsfile)
latexfile = tmpfile+'.tex'
dvifile = tmpfile+'.dvi'
psfile = tmpfile+'.ps'
if orientation == 'landscape':
angle = 90
else:
angle = 0
if rcParams['text.latex.unicode']:
unicode_preamble = """\\usepackage{ucs}
\\usepackage[utf8x]{inputenc}"""
else:
unicode_preamble = ''
s = r"""\documentclass{article}
%s
%s
%s
\usepackage[
dvips, papersize={%sin,%sin}, body={%sin,%sin}, margin={0in,0in}]{geometry}
\usepackage{psfrag}
\usepackage[dvips]{graphicx}
\usepackage{color}
\pagestyle{empty}
\begin{document}
\begin{figure}
\centering
\leavevmode
%s
\includegraphics*[angle=%s]{%s}
\end{figure}
\end{document}
""" % (font_preamble, unicode_preamble, custom_preamble,
paperWidth, paperHeight, paperWidth, paperHeight,
'\n'.join(psfrags), angle, os.path.split(epsfile)[-1])
try:
pathlib.Path(latexfile).write_text(
s, encoding='utf-8' if rcParams['text.latex.unicode'] else 'ascii')
except UnicodeEncodeError:
_log.info("You are using unicode and latex, but have not enabled the "
"Matplotlib 'text.latex.unicode' rcParam.")
raise
# Replace \\ for / so latex does not think there is a function call
latexfile = latexfile.replace("\\", "/")
# Replace ~ so Latex does not think it is line break
latexfile = latexfile.replace("~", "\\string~")
cbook._check_and_log_subprocess(
["latex", "-interaction=nonstopmode", '"%s"' % latexfile],
_log, cwd=tmpdir)
cbook._check_and_log_subprocess(
['dvips', '-q', '-R0', '-o', os.path.basename(psfile),
os.path.basename(dvifile)], _log, cwd=tmpdir)
os.remove(epsfile)
shutil.move(psfile, tmpfile)
# check if the dvips created a ps in landscape paper. Somehow,
# above latex+dvips results in a ps file in a landscape mode for a
# certain figure sizes (e.g., 8.3in,5.8in which is a5). And the
# bounding box of the final output got messed up. We check see if
# the generated ps file is in landscape and return this
# information. The return value is used in pstoeps step to recover
# the correct bounding box. 2010-06-05 JJL
with open(tmpfile) as fh:
if "Landscape" in fh.read(1000):
psfrag_rotated = True
else:
psfrag_rotated = False
if not debugPS:
for fname in glob.glob(tmpfile+'.*'):
os.remove(fname)
return psfrag_rotated
def gs_distill(tmpfile, eps=False, ptype='letter', bbox=None, rotated=False):
"""
Use ghostscript's pswrite or epswrite device to distill a file.
This yields smaller files without illegal encapsulated postscript
operators. The output is low-level, converting text to outlines.
"""
if eps:
paper_option = "-dEPSCrop"
else:
paper_option = "-sPAPERSIZE=%s" % ptype
psfile = tmpfile + '.ps'
dpi = rcParams['ps.distiller.res']
cbook._check_and_log_subprocess(
[mpl._get_executable_info("gs").executable,
"-dBATCH", "-dNOPAUSE", "-r%d" % dpi, "-sDEVICE=ps2write",
paper_option, "-sOutputFile=%s" % psfile, tmpfile],
_log)
os.remove(tmpfile)
shutil.move(psfile, tmpfile)
# While it is best if above steps preserve the original bounding
# box, there seem to be cases when it is not. For those cases,
# the original bbox can be restored during the pstoeps step.
if eps:
# For some versions of gs, above steps result in an ps file where the
# original bbox is no more correct. Do not adjust bbox for now.
pstoeps(tmpfile, bbox, rotated=rotated)
def xpdf_distill(tmpfile, eps=False, ptype='letter', bbox=None, rotated=False):
"""
Use ghostscript's ps2pdf and xpdf's/poppler's pdftops to distill a file.
This yields smaller files without illegal encapsulated postscript
operators. This distiller is preferred, generating high-level postscript
output that treats text as text.
"""
pdffile = tmpfile + '.pdf'
psfile = tmpfile + '.ps'
# Pass options as `-foo#bar` instead of `-foo=bar` to keep Windows happy
# (https://www.ghostscript.com/doc/9.22/Use.htm#MS_Windows).
cbook._check_and_log_subprocess(
["ps2pdf",
"-dAutoFilterColorImages#false",
"-dAutoFilterGrayImages#false",
"-dAutoRotatePages#false",
"-sGrayImageFilter#FlateEncode",
"-sColorImageFilter#FlateEncode",
"-dEPSCrop" if eps else "-sPAPERSIZE#%s" % ptype,
tmpfile, pdffile], _log)
cbook._check_and_log_subprocess(
["pdftops", "-paper", "match", "-level2", pdffile, psfile], _log)
os.remove(tmpfile)
shutil.move(psfile, tmpfile)
if eps:
pstoeps(tmpfile)
for fname in glob.glob(tmpfile+'.*'):
os.remove(fname)
def get_bbox_header(lbrt, rotated=False):
"""
return a postscript header string for the given bbox lbrt=(l, b, r, t).
Optionally, return rotate command.
"""
l, b, r, t = lbrt
if rotated:
rotate = "%.2f %.2f translate\n90 rotate" % (l+r, 0)
else:
rotate = ""
bbox_info = '%%%%BoundingBox: %d %d %d %d' % (l, b, np.ceil(r), np.ceil(t))
hires_bbox_info = '%%%%HiResBoundingBox: %.6f %.6f %.6f %.6f' % (
l, b, r, t)
return '\n'.join([bbox_info, hires_bbox_info]), rotate
# get_bbox is deprecated. I don't see any reason to use ghostscript to
# find the bounding box, as the required bounding box is alread known.
@cbook.deprecated("3.0")
def get_bbox(tmpfile, bbox):
"""
Use ghostscript's bbox device to find the center of the bounding box.
Return an appropriately sized bbox centered around that point. A bit of a
hack.
"""
gs_exe = ps_backend_helper.gs_exe
command = [gs_exe, "-dBATCH", "-dNOPAUSE", "-sDEVICE=bbox", "%s" % tmpfile]
_log.debug(command)
p = subprocess.Popen(command, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
close_fds=True)
(stdout, stderr) = (p.stdout, p.stderr)
_log.debug(stdout.read())
bbox_info = stderr.read()
_log.info(bbox_info)
bbox_found = re.search('%%HiResBoundingBox: .*', bbox_info)
if bbox_found:
bbox_info = bbox_found.group()
else:
raise RuntimeError(
'Ghostscript was not able to extract a bounding box.'
'Here is the Ghostscript output:\n\n%s' % bbox_info)
l, b, r, t = [float(i) for i in bbox_info.split()[-4:]]
# this is a hack to deal with the fact that ghostscript does not return the
# intended bbox, but a tight bbox. For now, we just center the ink in the
# intended bbox. This is not ideal, users may intend the ink to not be
# centered.
if bbox is None:
l, b, r, t = (l-1, b-1, r+1, t+1)
else:
x = (l+r)/2
y = (b+t)/2
dx = (bbox[2]-bbox[0])/2
dy = (bbox[3]-bbox[1])/2
l, b, r, t = (x-dx, y-dy, x+dx, y+dy)
bbox_info = '%%%%BoundingBox: %d %d %d %d' % (l, b, np.ceil(r), np.ceil(t))
hires_bbox_info = '%%%%HiResBoundingBox: %.6f %.6f %.6f %.6f' % (
l, b, r, t)
return '\n'.join([bbox_info, hires_bbox_info])
def pstoeps(tmpfile, bbox=None, rotated=False):
"""
Convert the postscript to encapsulated postscript. The bbox of
the eps file will be replaced with the given *bbox* argument. If
None, original bbox will be used.
"""
# if rotated==True, the output eps file need to be rotated
if bbox:
bbox_info, rotate = get_bbox_header(bbox, rotated=rotated)
else:
bbox_info, rotate = None, None
epsfile = tmpfile + '.eps'
with open(epsfile, 'wb') as epsh, open(tmpfile, 'rb') as tmph:
write = epsh.write
# Modify the header:
for line in tmph:
if line.startswith(b'%!PS'):
write(b"%!PS-Adobe-3.0 EPSF-3.0\n")
if bbox:
write(bbox_info.encode('ascii') + b'\n')
elif line.startswith(b'%%EndComments'):
write(line)
write(b'%%BeginProlog\n'
b'save\n'
b'countdictstack\n'
b'mark\n'
b'newpath\n'
b'/showpage {} def\n'
b'/setpagedevice {pop} def\n'
b'%%EndProlog\n'
b'%%Page 1 1\n')
if rotate:
write(rotate.encode('ascii') + b'\n')
break
elif bbox and line.startswith((b'%%Bound', b'%%HiResBound',
b'%%DocumentMedia', b'%%Pages')):
pass
else:
write(line)
# Now rewrite the rest of the file, and modify the trailer.
# This is done in a second loop such that the header of the embedded
# eps file is not modified.
for line in tmph:
if line.startswith(b'%%EOF'):
write(b'cleartomark\n'
b'countdictstack\n'
b'exch sub { end } repeat\n'
b'restore\n'
b'showpage\n'
b'%%EOF\n')
elif line.startswith(b'%%PageBoundingBox'):
pass
else:
write(line)
os.remove(tmpfile)
shutil.move(epsfile, tmpfile)
FigureManagerPS = FigureManagerBase
# The following Python dictionary psDefs contains the entries for the
# PostScript dictionary mpldict. This dictionary implements most of
# the matplotlib primitives and some abbreviations.
#
# References:
# http://www.adobe.com/products/postscript/pdfs/PLRM.pdf
# http://www.mactech.com/articles/mactech/Vol.09/09.04/PostscriptTutorial/
# http://www.math.ubc.ca/people/faculty/cass/graphics/text/www/
#
# The usage comments use the notation of the operator summary
# in the PostScript Language reference manual.
psDefs = [
# x y *m* -
"/m { moveto } bind def",
# x y *l* -
"/l { lineto } bind def",
# x y *r* -
"/r { rlineto } bind def",
# x1 y1 x2 y2 x y *c* -
"/c { curveto } bind def",
# *closepath* -
"/cl { closepath } bind def",
# w h x y *box* -
"""/box {
m
1 index 0 r
0 exch r
neg 0 r
cl
} bind def""",
# w h x y *clipbox* -
"""/clipbox {
box
clip
newpath
} bind def""",
]
@_Backend.export
class _BackendPS(_Backend):
FigureCanvas = FigureCanvasPS
|
ac0e18c8ae9cab72c7b5b3d85ec5092a0350e1f22a79549c373e1a4b94b13931
|
import importlib
import logging
import os
import sys
import matplotlib
from matplotlib import cbook
from matplotlib.backend_bases import _Backend
_log = logging.getLogger(__name__)
# NOTE: plt.switch_backend() (called at import time) will add a "backend"
# attribute here for backcompat.
def _get_running_interactive_framework():
"""
Return the interactive framework whose event loop is currently running, if
any, or "headless" if no event loop can be started, or None.
Returns
-------
Optional[str]
One of the following values: "qt5", "qt4", "gtk3", "wx", "tk",
"macosx", "headless", ``None``.
"""
QtWidgets = (sys.modules.get("PyQt5.QtWidgets")
or sys.modules.get("PySide2.QtWidgets"))
if QtWidgets and QtWidgets.QApplication.instance():
return "qt5"
QtGui = (sys.modules.get("PyQt4.QtGui")
or sys.modules.get("PySide.QtGui"))
if QtGui and QtGui.QApplication.instance():
return "qt4"
Gtk = sys.modules.get("gi.repository.Gtk")
if Gtk and Gtk.main_level():
return "gtk3"
wx = sys.modules.get("wx")
if wx and wx.GetApp():
return "wx"
tkinter = sys.modules.get("tkinter")
if tkinter:
for frame in sys._current_frames().values():
while frame:
if frame.f_code == tkinter.mainloop.__code__:
return "tk"
frame = frame.f_back
if 'matplotlib.backends._macosx' in sys.modules:
if sys.modules["matplotlib.backends._macosx"].event_loop_is_running():
return "macosx"
if sys.platform.startswith("linux") and not os.environ.get("DISPLAY"):
return "headless"
return None
@cbook.deprecated("3.0")
def pylab_setup(name=None):
"""
Return new_figure_manager, draw_if_interactive and show for pyplot.
This provides the backend-specific functions that are used by pyplot to
abstract away the difference between backends.
Parameters
----------
name : str, optional
The name of the backend to use. If `None`, falls back to
``matplotlib.get_backend()`` (which return :rc:`backend`).
Returns
-------
backend_mod : module
The module which contains the backend of choice
new_figure_manager : function
Create a new figure manager (roughly maps to GUI window)
draw_if_interactive : function
Redraw the current figure if pyplot is interactive
show : function
Show (and possibly block) any unshown figures.
"""
# Import the requested backend into a generic module object.
if name is None:
name = matplotlib.get_backend()
backend_name = (name[9:] if name.startswith("module://")
else "matplotlib.backends.backend_{}".format(name.lower()))
backend_mod = importlib.import_module(backend_name)
# Create a local Backend class whose body corresponds to the contents of
# the backend module. This allows the Backend class to fill in the missing
# methods through inheritance.
Backend = type("Backend", (_Backend,), vars(backend_mod))
# Need to keep a global reference to the backend for compatibility reasons.
# See https://github.com/matplotlib/matplotlib/issues/6092
global backend
backend = name
_log.debug('backend %s version %s', name, Backend.backend_version)
return (backend_mod,
Backend.new_figure_manager,
Backend.draw_if_interactive,
Backend.show)
|
4fcc7f356028f7f5af9e9c3a1e7b2779123d032031729f344c37becf67a8b1b3
|
"""
Common functionality between the PDF and PS backends.
"""
import functools
import matplotlib as mpl
from .. import font_manager, ft2font
from ..afm import AFM
from ..backend_bases import RendererBase
@functools.lru_cache(50)
def _cached_get_afm_from_fname(fname):
with open(fname, "rb") as fh:
return AFM(fh)
class RendererPDFPSBase(RendererBase):
# The following attributes must be defined by the subclasses:
# - _afm_font_dir
# - _use_afm_rc_name
def flipy(self):
# docstring inherited
return False # y increases from bottom to top.
def option_scale_image(self):
# docstring inherited
return True # PDF and PS support arbitrary image scaling.
def option_image_nocomposite(self):
# docstring inherited
# Decide whether to composite image based on rcParam value.
return not mpl.rcParams["image.composite_image"]
def get_canvas_width_height(self):
# docstring inherited
return self.width * 72.0, self.height * 72.0
def get_text_width_height_descent(self, s, prop, ismath):
# docstring inherited
if mpl.rcParams["text.usetex"]:
texmanager = self.get_texmanager()
fontsize = prop.get_size_in_points()
w, h, d = texmanager.get_text_width_height_descent(
s, fontsize, renderer=self)
return w, h, d
elif ismath:
parse = self.mathtext_parser.parse(s, 72, prop)
return parse.width, parse.height, parse.depth
elif mpl.rcParams[self._use_afm_rc_name]:
font = self._get_font_afm(prop)
l, b, w, h, d = font.get_str_bbox_and_descent(s)
scale = prop.get_size_in_points() / 1000
w *= scale
h *= scale
d *= scale
return w, h, d
else:
font = self._get_font_ttf(prop)
font.set_text(s, 0.0, flags=ft2font.LOAD_NO_HINTING)
w, h = font.get_width_height()
d = font.get_descent()
scale = 1 / 64
w *= scale
h *= scale
d *= scale
return w, h, d
def _get_font_afm(self, prop):
fname = (
font_manager.findfont(
prop, fontext="afm", directory=self._afm_font_dir)
or font_manager.findfont(
"Helvetica", fontext="afm", directory=self._afm_font_dir))
return _cached_get_afm_from_fname(fname)
def _get_font_ttf(self, prop):
fname = font_manager.findfont(prop)
font = font_manager.get_font(fname)
font.clear()
font.set_size(prop.get_size_in_points(), 72)
return font
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.