matplotlib-rs 0.0.8__cp313-cp313-win_amd64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- docs/releases/0.0.1.md +268 -0
- docs/releases/0.0.2.md +69 -0
- docs/releases/0.0.3.md +80 -0
- docs/releases/0.0.4.md +73 -0
- docs/releases/0.0.5.md +24 -0
- docs/releases/0.0.6.md +24 -0
- docs/releases/0.0.7.md +24 -0
- docs/releases/0.0.8.md +16 -0
- licenses/LICENSE_CONTOURPY +29 -0
- licenses/LICENSE_CYCLER +27 -0
- licenses/LICENSE_DATEUTIL +54 -0
- licenses/LICENSE_KIWISOLVER +71 -0
- licenses/LICENSE_LIBWEBP +56 -0
- licenses/LICENSE_MATPLOTLIB +1253 -0
- licenses/LICENSE_PYPARSING +20 -0
- licenses/LICENSE_QHULL +39 -0
- licenses/LICENSE_SIX +18 -0
- matplotlib_rs/__init__.py +1683 -0
- matplotlib_rs/__main__.py +27 -0
- matplotlib_rs/_afm.py +500 -0
- matplotlib_rs/_animation_data.py +263 -0
- matplotlib_rs/_api/__init__.py +495 -0
- matplotlib_rs/_api/deprecation.py +534 -0
- matplotlib_rs/_axis_py.py +2991 -0
- matplotlib_rs/_blocking_input.py +31 -0
- matplotlib_rs/_cm.py +1500 -0
- matplotlib_rs/_cm_bivar.py +1289 -0
- matplotlib_rs/_cm_listed.py +2848 -0
- matplotlib_rs/_cm_multivar.py +167 -0
- matplotlib_rs/_color_data.py +1142 -0
- matplotlib_rs/_colormap.py +132 -0
- matplotlib_rs/_constrained_layout.py +825 -0
- matplotlib_rs/_contour.py +108 -0
- matplotlib_rs/_doc_cache.py +12214 -0
- matplotlib_rs/_docstring.py +142 -0
- matplotlib_rs/_enums.py +178 -0
- matplotlib_rs/_figure_rs.py +294 -0
- matplotlib_rs/_fontconfig_pattern.py +129 -0
- matplotlib_rs/_foreign.py +220 -0
- matplotlib_rs/_hook.py +94 -0
- matplotlib_rs/_image.py +160 -0
- matplotlib_rs/_imageio.py +229 -0
- matplotlib_rs/_internal_utils.py +65 -0
- matplotlib_rs/_kiwi.py +484 -0
- matplotlib_rs/_layoutgrid.py +549 -0
- matplotlib_rs/_live.py +192 -0
- matplotlib_rs/_mathtext.py +3103 -0
- matplotlib_rs/_mathtext_data.py +1811 -0
- matplotlib_rs/_mplrs.cp313-win_amd64.pyd +0 -0
- matplotlib_rs/_path.py +25 -0
- matplotlib_rs/_png.py +162 -0
- matplotlib_rs/_pylab_helpers.py +137 -0
- matplotlib_rs/_qhull.py +66 -0
- matplotlib_rs/_rcpush.py +84 -0
- matplotlib_rs/_spines_rs.py +108 -0
- matplotlib_rs/_style_helpers.py +52 -0
- matplotlib_rs/_text_helpers.py +51 -0
- matplotlib_rs/_tight_bbox.py +85 -0
- matplotlib_rs/_tight_layout.py +302 -0
- matplotlib_rs/_tri.py +140 -0
- matplotlib_rs/_type1font.py +1228 -0
- matplotlib_rs/_vendor/__init__.py +8 -0
- matplotlib_rs/_vendor/cycler.py +574 -0
- matplotlib_rs/_vendor/dateutil/__init__.py +27 -0
- matplotlib_rs/_vendor/dateutil/_common.py +44 -0
- matplotlib_rs/_vendor/dateutil/_tzdata_impl.py +148 -0
- matplotlib_rs/_vendor/dateutil/_version.py +5 -0
- matplotlib_rs/_vendor/dateutil/easter.py +90 -0
- matplotlib_rs/_vendor/dateutil/parser/__init__.py +62 -0
- matplotlib_rs/_vendor/dateutil/parser/_parser.py +1614 -0
- matplotlib_rs/_vendor/dateutil/parser/isoparser.py +417 -0
- matplotlib_rs/_vendor/dateutil/relativedelta.py +597 -0
- matplotlib_rs/_vendor/dateutil/rrule.py +1765 -0
- matplotlib_rs/_vendor/dateutil/tz/__init__.py +61 -0
- matplotlib_rs/_vendor/dateutil/tz/_common.py +420 -0
- matplotlib_rs/_vendor/dateutil/tz/_factories.py +81 -0
- matplotlib_rs/_vendor/dateutil/tz/_tzfile.py +1429 -0
- matplotlib_rs/_vendor/dateutil/tz/_tzpath.py +105 -0
- matplotlib_rs/_vendor/dateutil/tz/tz.py +1473 -0
- matplotlib_rs/_vendor/dateutil/tz/win.py +371 -0
- matplotlib_rs/_vendor/dateutil/tzwin.py +3 -0
- matplotlib_rs/_vendor/dateutil/utils.py +72 -0
- matplotlib_rs/_vendor/dateutil/zoneinfo/__init__.py +234 -0
- matplotlib_rs/_vendor/pyparsing/__init__.py +414 -0
- matplotlib_rs/_vendor/pyparsing/actions.py +265 -0
- matplotlib_rs/_vendor/pyparsing/common.py +571 -0
- matplotlib_rs/_vendor/pyparsing/core.py +6973 -0
- matplotlib_rs/_vendor/pyparsing/exceptions.py +354 -0
- matplotlib_rs/_vendor/pyparsing/helpers.py +1770 -0
- matplotlib_rs/_vendor/pyparsing/results.py +929 -0
- matplotlib_rs/_vendor/pyparsing/testing.py +399 -0
- matplotlib_rs/_vendor/pyparsing/unicode.py +357 -0
- matplotlib_rs/_vendor/pyparsing/util.py +515 -0
- matplotlib_rs/_vendor/pyparsing/warnings.py +11 -0
- matplotlib_rs/_vendor/six.py +1004 -0
- matplotlib_rs/animation.py +1843 -0
- matplotlib_rs/artist.py +2302 -0
- matplotlib_rs/axes/__init__.py +19 -0
- matplotlib_rs/axes/_axes.py +9402 -0
- matplotlib_rs/axes/_bar.py +185 -0
- matplotlib_rs/axes/_base.py +5236 -0
- matplotlib_rs/axes/_base_rs.py +727 -0
- matplotlib_rs/axes/_boxplot.py +391 -0
- matplotlib_rs/axes/_hist.py +99 -0
- matplotlib_rs/axes/_secondary_axes.py +357 -0
- matplotlib_rs/axis.py +1963 -0
- matplotlib_rs/backend_bases.py +3760 -0
- matplotlib_rs/backend_managers.py +388 -0
- matplotlib_rs/backend_tools.py +1002 -0
- matplotlib_rs/backends/__init__.py +6 -0
- matplotlib_rs/backends/_backend_pdf_ps.py +451 -0
- matplotlib_rs/backends/backend_agg.py +552 -0
- matplotlib_rs/backends/backend_mixed.py +123 -0
- matplotlib_rs/backends/backend_pdf.py +2711 -0
- matplotlib_rs/backends/backend_pgf.py +1031 -0
- matplotlib_rs/backends/backend_ps.py +1491 -0
- matplotlib_rs/backends/backend_svg.py +1395 -0
- matplotlib_rs/backends/backend_template.py +214 -0
- matplotlib_rs/backends/registry.py +423 -0
- matplotlib_rs/bezier.py +691 -0
- matplotlib_rs/category.py +236 -0
- matplotlib_rs/cbook.py +2762 -0
- matplotlib_rs/cm.py +251 -0
- matplotlib_rs/collections.py +2711 -0
- matplotlib_rs/colorbar.py +1586 -0
- matplotlib_rs/colorizer.py +909 -0
- matplotlib_rs/colors.py +4278 -0
- matplotlib_rs/container.py +256 -0
- matplotlib_rs/contour.py +1756 -0
- matplotlib_rs/dates.py +1847 -0
- matplotlib_rs/dviread.py +1386 -0
- matplotlib_rs/figure.py +3815 -0
- matplotlib_rs/font_manager.py +1855 -0
- matplotlib_rs/ft2font.py +515 -0
- matplotlib_rs/gridspec.py +808 -0
- matplotlib_rs/hatch.py +244 -0
- matplotlib_rs/image.py +1863 -0
- matplotlib_rs/inset.py +291 -0
- matplotlib_rs/layout_engine.py +310 -0
- matplotlib_rs/legend.py +1480 -0
- matplotlib_rs/legend_handler.py +812 -0
- matplotlib_rs/lines.py +1886 -0
- matplotlib_rs/markers.py +908 -0
- matplotlib_rs/mathtext.py +141 -0
- matplotlib_rs/mlab.py +959 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSans-Bold.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSans-BoldOblique.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSans-Oblique.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSans.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansDisplay.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansMono-Bold.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansMono-BoldOblique.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansMono-Oblique.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansMono.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerif-Bold.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerif-BoldItalic.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerif-Italic.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerif.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerifDisplay.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/LICENSE_DEJAVU +99 -0
- matplotlib_rs/mpl-data/fonts/ttf/LICENSE_STIX +124 -0
- matplotlib_rs/mpl-data/fonts/ttf/LastResortHE-Regular.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXGeneral.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXGeneralBol.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXGeneralBolIta.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXGeneralItalic.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXNonUni.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXNonUniBol.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXNonUniBolIta.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXNonUniIta.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXSizFiveSymReg.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXSizFourSymBol.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXSizFourSymReg.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXSizOneSymBol.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXSizOneSymReg.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXSizThreeSymBol.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXSizThreeSymReg.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXSizTwoSymBol.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXSizTwoSymReg.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/cmb10.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/cmex10.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/cmmi10.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/cmr10.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/cmss10.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/cmsy10.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/cmti10.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/cmtt10.ttf +0 -0
- matplotlib_rs/mpl-data/images/back-symbolic.svg +46 -0
- matplotlib_rs/mpl-data/images/back.pdf +0 -0
- matplotlib_rs/mpl-data/images/back.png +0 -0
- matplotlib_rs/mpl-data/images/back.svg +46 -0
- matplotlib_rs/mpl-data/images/back_large.png +0 -0
- matplotlib_rs/mpl-data/images/filesave-symbolic.svg +68 -0
- matplotlib_rs/mpl-data/images/filesave.pdf +72 -0
- matplotlib_rs/mpl-data/images/filesave.png +0 -0
- matplotlib_rs/mpl-data/images/filesave.svg +68 -0
- matplotlib_rs/mpl-data/images/filesave_large.png +0 -0
- matplotlib_rs/mpl-data/images/forward-symbolic.svg +46 -0
- matplotlib_rs/mpl-data/images/forward.pdf +0 -0
- matplotlib_rs/mpl-data/images/forward.png +0 -0
- matplotlib_rs/mpl-data/images/forward.svg +46 -0
- matplotlib_rs/mpl-data/images/forward_large.png +0 -0
- matplotlib_rs/mpl-data/images/hand.pdf +0 -0
- matplotlib_rs/mpl-data/images/hand.png +0 -0
- matplotlib_rs/mpl-data/images/hand.svg +130 -0
- matplotlib_rs/mpl-data/images/help-symbolic.svg +52 -0
- matplotlib_rs/mpl-data/images/help.pdf +71 -0
- matplotlib_rs/mpl-data/images/help.png +0 -0
- matplotlib_rs/mpl-data/images/help.svg +52 -0
- matplotlib_rs/mpl-data/images/help_large.png +0 -0
- matplotlib_rs/mpl-data/images/home-symbolic.svg +59 -0
- matplotlib_rs/mpl-data/images/home.pdf +0 -0
- matplotlib_rs/mpl-data/images/home.png +0 -0
- matplotlib_rs/mpl-data/images/home.svg +59 -0
- matplotlib_rs/mpl-data/images/home_large.png +0 -0
- matplotlib_rs/mpl-data/images/matplotlib.pdf +0 -0
- matplotlib_rs/mpl-data/images/matplotlib.png +0 -0
- matplotlib_rs/mpl-data/images/matplotlib.svg +3171 -0
- matplotlib_rs/mpl-data/images/matplotlib_large.png +0 -0
- matplotlib_rs/mpl-data/images/move-symbolic.svg +73 -0
- matplotlib_rs/mpl-data/images/move.pdf +0 -0
- matplotlib_rs/mpl-data/images/move.png +0 -0
- matplotlib_rs/mpl-data/images/move.svg +73 -0
- matplotlib_rs/mpl-data/images/move_large.png +0 -0
- matplotlib_rs/mpl-data/images/qt4_editor_options.pdf +0 -0
- matplotlib_rs/mpl-data/images/qt4_editor_options.png +0 -0
- matplotlib_rs/mpl-data/images/qt4_editor_options.svg +48 -0
- matplotlib_rs/mpl-data/images/qt4_editor_options_large.png +0 -0
- matplotlib_rs/mpl-data/images/subplots-symbolic.svg +81 -0
- matplotlib_rs/mpl-data/images/subplots.pdf +0 -0
- matplotlib_rs/mpl-data/images/subplots.png +0 -0
- matplotlib_rs/mpl-data/images/subplots.svg +81 -0
- matplotlib_rs/mpl-data/images/subplots_large.png +0 -0
- matplotlib_rs/mpl-data/images/zoom_to_rect-symbolic.svg +40 -0
- matplotlib_rs/mpl-data/images/zoom_to_rect.pdf +69 -0
- matplotlib_rs/mpl-data/images/zoom_to_rect.png +0 -0
- matplotlib_rs/mpl-data/images/zoom_to_rect.svg +40 -0
- matplotlib_rs/mpl-data/images/zoom_to_rect_large.png +0 -0
- matplotlib_rs/mpl-data/kpsewhich.lua +4 -0
- matplotlib_rs/mpl-data/matplotlibrc +849 -0
- matplotlib_rs/mpl-data/plot_directive/plot_directive.css +16 -0
- matplotlib_rs/mpl-data/sample_data/Minduka_Present_Blue_Pack.png +0 -0
- matplotlib_rs/mpl-data/sample_data/README.txt +2 -0
- matplotlib_rs/mpl-data/sample_data/Stocks.csv +526 -0
- matplotlib_rs/mpl-data/sample_data/axes_grid/bivariate_normal.npy +0 -0
- matplotlib_rs/mpl-data/sample_data/data_x_x2_x3.csv +11 -0
- matplotlib_rs/mpl-data/sample_data/eeg.dat +0 -0
- matplotlib_rs/mpl-data/sample_data/embedding_in_wx3.xrc +65 -0
- matplotlib_rs/mpl-data/sample_data/goog.npz +0 -0
- matplotlib_rs/mpl-data/sample_data/grace_hopper.jpg +0 -0
- matplotlib_rs/mpl-data/sample_data/jacksboro_fault_dem.npz +0 -0
- matplotlib_rs/mpl-data/sample_data/logo2.png +0 -0
- matplotlib_rs/mpl-data/sample_data/membrane.dat +0 -0
- matplotlib_rs/mpl-data/sample_data/msft.csv +66 -0
- matplotlib_rs/mpl-data/sample_data/s1045.ima.gz +0 -0
- matplotlib_rs/mpl-data/sample_data/topobathy.npz +0 -0
- matplotlib_rs/mpl-data/stylelib/Solarize_Light2.mplstyle +53 -0
- matplotlib_rs/mpl-data/stylelib/_classic_test_patch.mplstyle +8 -0
- matplotlib_rs/mpl-data/stylelib/_mpl-gallery-nogrid.mplstyle +19 -0
- matplotlib_rs/mpl-data/stylelib/_mpl-gallery.mplstyle +19 -0
- matplotlib_rs/mpl-data/stylelib/bmh.mplstyle +27 -0
- matplotlib_rs/mpl-data/stylelib/classic.mplstyle +491 -0
- matplotlib_rs/mpl-data/stylelib/dark_background.mplstyle +26 -0
- matplotlib_rs/mpl-data/stylelib/fast.mplstyle +11 -0
- matplotlib_rs/mpl-data/stylelib/fivethirtyeight.mplstyle +37 -0
- matplotlib_rs/mpl-data/stylelib/ggplot.mplstyle +39 -0
- matplotlib_rs/mpl-data/stylelib/grayscale.mplstyle +29 -0
- matplotlib_rs/mpl-data/stylelib/petroff10.mplstyle +5 -0
- matplotlib_rs/mpl-data/stylelib/petroff6.mplstyle +5 -0
- matplotlib_rs/mpl-data/stylelib/petroff8.mplstyle +5 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-bright.mplstyle +3 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-colorblind.mplstyle +3 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-dark-palette.mplstyle +3 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-dark.mplstyle +30 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-darkgrid.mplstyle +30 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-deep.mplstyle +3 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-muted.mplstyle +3 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-notebook.mplstyle +21 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-paper.mplstyle +21 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-pastel.mplstyle +3 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-poster.mplstyle +21 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-talk.mplstyle +21 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-ticks.mplstyle +30 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-white.mplstyle +30 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-whitegrid.mplstyle +30 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8.mplstyle +57 -0
- matplotlib_rs/mpl-data/stylelib/tableau-colorblind10.mplstyle +3 -0
- matplotlib_rs/mpl_toolkits/__init__.py +3 -0
- matplotlib_rs/mpl_toolkits/axes_grid1/__init__.py +11 -0
- matplotlib_rs/mpl_toolkits/axes_grid1/anchored_artists.py +415 -0
- matplotlib_rs/mpl_toolkits/axes_grid1/axes_divider.py +619 -0
- matplotlib_rs/mpl_toolkits/axes_grid1/axes_grid.py +565 -0
- matplotlib_rs/mpl_toolkits/axes_grid1/axes_rgb.py +158 -0
- matplotlib_rs/mpl_toolkits/axes_grid1/axes_size.py +272 -0
- matplotlib_rs/mpl_toolkits/axes_grid1/inset_locator.py +525 -0
- matplotlib_rs/mpl_toolkits/axes_grid1/mpl_axes.py +129 -0
- matplotlib_rs/mpl_toolkits/axes_grid1/parasite_axes.py +261 -0
- matplotlib_rs/mpl_toolkits/axisartist/__init__.py +15 -0
- matplotlib_rs/mpl_toolkits/axisartist/angle_helper.py +396 -0
- matplotlib_rs/mpl_toolkits/axisartist/axes_divider.py +3 -0
- matplotlib_rs/mpl_toolkits/axisartist/axis_artist.py +1148 -0
- matplotlib_rs/mpl_toolkits/axisartist/axisline_style.py +193 -0
- matplotlib_rs/mpl_toolkits/axisartist/axislines.py +475 -0
- matplotlib_rs/mpl_toolkits/axisartist/floating_axes.py +265 -0
- matplotlib_rs/mpl_toolkits/axisartist/grid_finder.py +329 -0
- matplotlib_rs/mpl_toolkits/axisartist/grid_helper_curvelinear.py +353 -0
- matplotlib_rs/mpl_toolkits/axisartist/parasite_axes.py +8 -0
- matplotlib_rs/mpl_toolkits/mplot3d/__init__.py +4 -0
- matplotlib_rs/mpl_toolkits/mplot3d/art3d.py +1758 -0
- matplotlib_rs/mpl_toolkits/mplot3d/axes3d.py +4462 -0
- matplotlib_rs/mpl_toolkits/mplot3d/axis3d.py +807 -0
- matplotlib_rs/mpl_toolkits/mplot3d/proj3d.py +270 -0
- matplotlib_rs/offsetbox.py +1726 -0
- matplotlib_rs/patches.py +5049 -0
- matplotlib_rs/path.py +1147 -0
- matplotlib_rs/patheffects.py +512 -0
- matplotlib_rs/projections/__init__.py +126 -0
- matplotlib_rs/projections/geo.py +512 -0
- matplotlib_rs/projections/polar.py +1518 -0
- matplotlib_rs/pylab.py +68 -0
- matplotlib_rs/pyplot.py +4834 -0
- matplotlib_rs/quiver.py +1236 -0
- matplotlib_rs/rcsetup.py +3435 -0
- matplotlib_rs/sankey.py +815 -0
- matplotlib_rs/scale.py +1002 -0
- matplotlib_rs/spines.py +618 -0
- matplotlib_rs/stackplot.py +144 -0
- matplotlib_rs/streamplot.py +768 -0
- matplotlib_rs/style/__init__.py +269 -0
- matplotlib_rs/style/core.py +28 -0
- matplotlib_rs/table.py +860 -0
- matplotlib_rs/texmanager.py +375 -0
- matplotlib_rs/text.py +2412 -0
- matplotlib_rs/textpath.py +377 -0
- matplotlib_rs/ticker.py +3111 -0
- matplotlib_rs/transforms.py +3069 -0
- matplotlib_rs/tri/__init__.py +24 -0
- matplotlib_rs/tri/_triangulation.py +248 -0
- matplotlib_rs/tri/_tricontour.py +271 -0
- matplotlib_rs/tri/_trifinder.py +97 -0
- matplotlib_rs/tri/_triinterpolate.py +1575 -0
- matplotlib_rs/tri/_tripcolor.py +170 -0
- matplotlib_rs/tri/_triplot.py +87 -0
- matplotlib_rs/tri/_trirefine.py +308 -0
- matplotlib_rs/tri/_tritools.py +264 -0
- matplotlib_rs/typing.py +597 -0
- matplotlib_rs/units.py +196 -0
- matplotlib_rs/widgets.py +4455 -0
- matplotlib_rs-0.0.8.dist-info/METADATA +392 -0
- matplotlib_rs-0.0.8.dist-info/RECORD +352 -0
- matplotlib_rs-0.0.8.dist-info/WHEEL +4 -0
- matplotlib_rs-0.0.8.dist-info/sboms/matplotlib-rs.cyclonedx.json +4390 -0
|
@@ -0,0 +1,3760 @@
|
|
|
1
|
+
# Vendored from matplotlib 3.11 (see licenses/LICENSE_MATPLOTLIB), adapted for matplotlib_rs.
|
|
2
|
+
"""
|
|
3
|
+
Abstract base classes define the primitives that renderers and
|
|
4
|
+
graphics contexts must implement to serve as a Matplotlib backend.
|
|
5
|
+
|
|
6
|
+
`RendererBase`
|
|
7
|
+
An abstract base class to handle drawing/rendering operations.
|
|
8
|
+
|
|
9
|
+
`FigureCanvasBase`
|
|
10
|
+
The abstraction layer that separates the `.Figure` from the backend
|
|
11
|
+
specific details like a user interface drawing area.
|
|
12
|
+
|
|
13
|
+
`GraphicsContextBase`
|
|
14
|
+
An abstract base class that provides color, line styles, etc.
|
|
15
|
+
|
|
16
|
+
`Event`
|
|
17
|
+
The base class for all of the Matplotlib event handling. Derived classes
|
|
18
|
+
such as `KeyEvent` and `MouseEvent` store the meta data like keys and
|
|
19
|
+
buttons pressed, x and y locations in pixel and `~.axes.Axes` coordinates.
|
|
20
|
+
|
|
21
|
+
`ShowBase`
|
|
22
|
+
The base class for the ``Show`` class of each interactive backend; the
|
|
23
|
+
'show' callable is then set to ``Show.__call__``.
|
|
24
|
+
|
|
25
|
+
`ToolContainerBase`
|
|
26
|
+
The base class for the Toolbar class of each interactive backend.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from collections import namedtuple
|
|
30
|
+
from contextlib import ExitStack, contextmanager, nullcontext
|
|
31
|
+
from enum import Enum, IntEnum
|
|
32
|
+
import functools
|
|
33
|
+
import importlib
|
|
34
|
+
import inspect
|
|
35
|
+
import io
|
|
36
|
+
import itertools
|
|
37
|
+
import logging
|
|
38
|
+
import os
|
|
39
|
+
import pathlib
|
|
40
|
+
import signal
|
|
41
|
+
import socket
|
|
42
|
+
import sys
|
|
43
|
+
import time
|
|
44
|
+
import weakref
|
|
45
|
+
from weakref import WeakKeyDictionary
|
|
46
|
+
|
|
47
|
+
import numpy as np
|
|
48
|
+
|
|
49
|
+
import matplotlib_rs as mpl
|
|
50
|
+
from matplotlib_rs import (
|
|
51
|
+
_api, backend_tools as tools, cbook, colors, _docstring, text,
|
|
52
|
+
_tight_bbox, transforms, widgets, is_interactive, rcParams)
|
|
53
|
+
from matplotlib_rs._pylab_helpers import Gcf
|
|
54
|
+
from matplotlib_rs.backend_managers import ToolManager
|
|
55
|
+
from matplotlib_rs.cbook import _setattr_cm
|
|
56
|
+
from matplotlib_rs.layout_engine import ConstrainedLayoutEngine
|
|
57
|
+
from matplotlib_rs.path import Path
|
|
58
|
+
from matplotlib_rs.transforms import Affine2D
|
|
59
|
+
from matplotlib_rs._enums import JoinStyle, CapStyle
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
_log = logging.getLogger(__name__)
|
|
63
|
+
_default_filetypes = {
|
|
64
|
+
'eps': 'Encapsulated Postscript',
|
|
65
|
+
'gif': 'Graphics Interchange Format',
|
|
66
|
+
'jpg': 'Joint Photographic Experts Group',
|
|
67
|
+
'jpeg': 'Joint Photographic Experts Group',
|
|
68
|
+
'pdf': 'Portable Document Format',
|
|
69
|
+
'pgf': 'PGF code for LaTeX',
|
|
70
|
+
'png': 'Portable Network Graphics',
|
|
71
|
+
'ps': 'Postscript',
|
|
72
|
+
'raw': 'Raw RGBA bitmap',
|
|
73
|
+
'rgba': 'Raw RGBA bitmap',
|
|
74
|
+
'svg': 'Scalable Vector Graphics',
|
|
75
|
+
'svgz': 'Scalable Vector Graphics',
|
|
76
|
+
'tif': 'Tagged Image File Format',
|
|
77
|
+
'tiff': 'Tagged Image File Format',
|
|
78
|
+
'webp': 'WebP Image Format',
|
|
79
|
+
'avif': 'AV1 Image File Format',
|
|
80
|
+
}
|
|
81
|
+
_default_backends = { # matplotlib_rs backends
|
|
82
|
+
'eps': 'matplotlib.backends.backend_ps',
|
|
83
|
+
'gif': 'matplotlib.backends.backend_agg',
|
|
84
|
+
'jpg': 'matplotlib.backends.backend_agg',
|
|
85
|
+
'jpeg': 'matplotlib.backends.backend_agg',
|
|
86
|
+
'pdf': 'matplotlib.backends.backend_pdf',
|
|
87
|
+
'pgf': 'matplotlib.backends.backend_pgf',
|
|
88
|
+
'png': 'matplotlib.backends.backend_agg',
|
|
89
|
+
'ps': 'matplotlib.backends.backend_ps',
|
|
90
|
+
'raw': 'matplotlib.backends.backend_agg',
|
|
91
|
+
'rgba': 'matplotlib.backends.backend_agg',
|
|
92
|
+
'svg': 'matplotlib.backends.backend_svg',
|
|
93
|
+
'svgz': 'matplotlib.backends.backend_svg',
|
|
94
|
+
'tif': 'matplotlib.backends.backend_agg',
|
|
95
|
+
'tiff': 'matplotlib.backends.backend_agg',
|
|
96
|
+
'webp': 'matplotlib.backends.backend_agg',
|
|
97
|
+
'avif': 'matplotlib.backends.backend_agg',
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def register_backend(format, backend, description=None):
|
|
102
|
+
"""
|
|
103
|
+
Register a backend for saving to a given file format.
|
|
104
|
+
|
|
105
|
+
Parameters
|
|
106
|
+
----------
|
|
107
|
+
format : str
|
|
108
|
+
File extension
|
|
109
|
+
backend : module string or canvas class
|
|
110
|
+
Backend for handling file output
|
|
111
|
+
description : str, default: ""
|
|
112
|
+
Description of the file type.
|
|
113
|
+
"""
|
|
114
|
+
if description is None:
|
|
115
|
+
description = ''
|
|
116
|
+
_default_backends[format] = backend
|
|
117
|
+
_default_filetypes[format] = description
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def get_registered_canvas_class(format):
|
|
121
|
+
"""
|
|
122
|
+
Return the registered default canvas for given file format.
|
|
123
|
+
Handles deferred import of required backend.
|
|
124
|
+
"""
|
|
125
|
+
if format not in _default_backends:
|
|
126
|
+
return None
|
|
127
|
+
backend_class = _default_backends[format]
|
|
128
|
+
if isinstance(backend_class, str):
|
|
129
|
+
backend_class = importlib.import_module(backend_class).FigureCanvas
|
|
130
|
+
_default_backends[format] = backend_class
|
|
131
|
+
return backend_class
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
class RendererBase:
|
|
135
|
+
"""
|
|
136
|
+
An abstract base class to handle drawing/rendering operations.
|
|
137
|
+
|
|
138
|
+
The following methods must be implemented in the backend for full
|
|
139
|
+
functionality (though just implementing `draw_path` alone would give a
|
|
140
|
+
highly capable backend):
|
|
141
|
+
|
|
142
|
+
* `draw_path`
|
|
143
|
+
* `draw_image`
|
|
144
|
+
* `draw_gouraud_triangles`
|
|
145
|
+
|
|
146
|
+
The following methods *should* be implemented in the backend for
|
|
147
|
+
optimization reasons:
|
|
148
|
+
|
|
149
|
+
* `draw_text`
|
|
150
|
+
* `draw_markers`
|
|
151
|
+
* `draw_path_collection`
|
|
152
|
+
* `draw_quad_mesh`
|
|
153
|
+
"""
|
|
154
|
+
def __init__(self):
|
|
155
|
+
super().__init__()
|
|
156
|
+
self._texmanager = None
|
|
157
|
+
self._raster_depth = 0
|
|
158
|
+
self._rasterizing = False
|
|
159
|
+
|
|
160
|
+
@property
|
|
161
|
+
def _text2path(self):
|
|
162
|
+
t = self.__dict__.get('_rs_text2path')
|
|
163
|
+
if t is None:
|
|
164
|
+
t = self.__dict__['_rs_text2path'] = text.TextToPath()
|
|
165
|
+
return t
|
|
166
|
+
|
|
167
|
+
@_text2path.setter
|
|
168
|
+
def _text2path(self, value):
|
|
169
|
+
self.__dict__['_rs_text2path'] = value
|
|
170
|
+
|
|
171
|
+
def open_group(self, s, gid=None):
|
|
172
|
+
"""
|
|
173
|
+
Open a grouping element with label *s* and *gid* (if set) as id.
|
|
174
|
+
|
|
175
|
+
Only used by the SVG renderer.
|
|
176
|
+
"""
|
|
177
|
+
|
|
178
|
+
def close_group(self, s):
|
|
179
|
+
"""
|
|
180
|
+
Close a grouping element with label *s*.
|
|
181
|
+
|
|
182
|
+
Only used by the SVG renderer.
|
|
183
|
+
"""
|
|
184
|
+
|
|
185
|
+
def draw_path(self, gc, path, transform, rgbFace=None):
|
|
186
|
+
"""Draw a `~.path.Path` instance using the given affine transform."""
|
|
187
|
+
raise NotImplementedError
|
|
188
|
+
|
|
189
|
+
def draw_markers(self, gc, marker_path, marker_trans, path,
|
|
190
|
+
trans, rgbFace=None):
|
|
191
|
+
"""
|
|
192
|
+
Draw a marker at each of *path*'s vertices (excluding control points).
|
|
193
|
+
|
|
194
|
+
The base (fallback) implementation makes multiple calls to `draw_path`.
|
|
195
|
+
Backends may want to override this method in order to draw the marker
|
|
196
|
+
only once and reuse it multiple times.
|
|
197
|
+
|
|
198
|
+
Parameters
|
|
199
|
+
----------
|
|
200
|
+
gc : `.GraphicsContextBase`
|
|
201
|
+
The graphics context.
|
|
202
|
+
marker_path : `~matplotlib.path.Path`
|
|
203
|
+
The path for the marker.
|
|
204
|
+
marker_trans : `~matplotlib.transforms.Transform`
|
|
205
|
+
An affine transform applied to the marker.
|
|
206
|
+
path : `~matplotlib.path.Path`
|
|
207
|
+
The locations to draw the markers.
|
|
208
|
+
trans : `~matplotlib.transforms.Transform`
|
|
209
|
+
An affine transform applied to the path.
|
|
210
|
+
rgbFace : :mpltype:`color`, optional
|
|
211
|
+
"""
|
|
212
|
+
for vertices, codes in path.iter_segments(trans, simplify=False):
|
|
213
|
+
if len(vertices):
|
|
214
|
+
x, y = vertices[-2:]
|
|
215
|
+
self.draw_path(gc, marker_path,
|
|
216
|
+
marker_trans +
|
|
217
|
+
transforms.Affine2D().translate(x, y),
|
|
218
|
+
rgbFace)
|
|
219
|
+
|
|
220
|
+
def draw_path_collection(self, gc, master_transform, paths, all_transforms,
|
|
221
|
+
offsets, offset_trans, facecolors, edgecolors,
|
|
222
|
+
linewidths, linestyles, antialiaseds, urls,
|
|
223
|
+
offset_position, *, hatchcolors=None):
|
|
224
|
+
"""
|
|
225
|
+
Draw a collection of *paths*.
|
|
226
|
+
|
|
227
|
+
Each path is first transformed by the corresponding entry
|
|
228
|
+
in *all_transforms* (a list of (3, 3) matrices) and then by
|
|
229
|
+
*master_transform*. They are then translated by the corresponding
|
|
230
|
+
entry in *offsets*, which has been first transformed by *offset_trans*.
|
|
231
|
+
|
|
232
|
+
*facecolors*, *edgecolors*, *linewidths*, *linestyles*, *antialiased*
|
|
233
|
+
and *hatchcolors* are lists that set the corresponding properties.
|
|
234
|
+
|
|
235
|
+
.. versionadded:: 3.11
|
|
236
|
+
Allow *hatchcolors* to be specified.
|
|
237
|
+
|
|
238
|
+
*offset_position* is unused now, but the argument is kept for
|
|
239
|
+
backwards compatibility.
|
|
240
|
+
|
|
241
|
+
The base (fallback) implementation makes multiple calls to `draw_path`.
|
|
242
|
+
Backends may want to override this in order to render each set of
|
|
243
|
+
path data only once, and then reference that path multiple times with
|
|
244
|
+
the different offsets, colors, styles etc. The generator methods
|
|
245
|
+
`!_iter_collection_raw_paths` and `!_iter_collection` are provided to
|
|
246
|
+
help with (and standardize) the implementation across backends. It
|
|
247
|
+
is highly recommended to use those generators, so that changes to the
|
|
248
|
+
behavior of `draw_path_collection` can be made globally.
|
|
249
|
+
"""
|
|
250
|
+
path_ids = self._iter_collection_raw_paths(master_transform,
|
|
251
|
+
paths, all_transforms)
|
|
252
|
+
|
|
253
|
+
if hatchcolors is None:
|
|
254
|
+
hatchcolors = []
|
|
255
|
+
|
|
256
|
+
for xo, yo, path_id, gc0, rgbFace in self._iter_collection(
|
|
257
|
+
gc, list(path_ids), offsets, offset_trans,
|
|
258
|
+
facecolors, edgecolors, linewidths, linestyles,
|
|
259
|
+
antialiaseds, urls, offset_position, hatchcolors=hatchcolors):
|
|
260
|
+
path, transform = path_id
|
|
261
|
+
# Only apply another translation if we have an offset, else we
|
|
262
|
+
# reuse the initial transform.
|
|
263
|
+
if xo != 0 or yo != 0:
|
|
264
|
+
# The transformation can be used by multiple paths. Since
|
|
265
|
+
# translate is a inplace operation, we need to copy the
|
|
266
|
+
# transformation by .frozen() before applying the translation.
|
|
267
|
+
transform = transform.frozen()
|
|
268
|
+
transform.translate(xo, yo)
|
|
269
|
+
self.draw_path(gc0, path, transform, rgbFace)
|
|
270
|
+
|
|
271
|
+
def draw_quad_mesh(self, gc, master_transform, meshWidth, meshHeight,
|
|
272
|
+
coordinates, offsets, offsetTrans, facecolors,
|
|
273
|
+
antialiased, edgecolors):
|
|
274
|
+
"""
|
|
275
|
+
Draw a quadmesh.
|
|
276
|
+
|
|
277
|
+
The base (fallback) implementation converts the quadmesh to paths and
|
|
278
|
+
then calls `draw_path_collection`.
|
|
279
|
+
"""
|
|
280
|
+
|
|
281
|
+
from matplotlib_rs.collections import QuadMesh
|
|
282
|
+
paths = QuadMesh._convert_mesh_to_paths(coordinates)
|
|
283
|
+
|
|
284
|
+
if edgecolors is None:
|
|
285
|
+
edgecolors = facecolors
|
|
286
|
+
linewidths = np.array([gc.get_linewidth()], float)
|
|
287
|
+
|
|
288
|
+
return self.draw_path_collection(
|
|
289
|
+
gc, master_transform, paths, [], offsets, offsetTrans, facecolors,
|
|
290
|
+
edgecolors, linewidths, [], [antialiased], [None], 'screen')
|
|
291
|
+
|
|
292
|
+
def draw_gouraud_triangles(self, gc, triangles_array, colors_array,
|
|
293
|
+
transform):
|
|
294
|
+
"""
|
|
295
|
+
Draw a series of Gouraud triangles.
|
|
296
|
+
|
|
297
|
+
Parameters
|
|
298
|
+
----------
|
|
299
|
+
gc : `.GraphicsContextBase`
|
|
300
|
+
The graphics context.
|
|
301
|
+
triangles_array : (N, 3, 2) array-like
|
|
302
|
+
Array of *N* (x, y) points for the triangles.
|
|
303
|
+
colors_array : (N, 3, 4) array-like
|
|
304
|
+
Array of *N* RGBA colors for each point of the triangles.
|
|
305
|
+
transform : `~matplotlib.transforms.Transform`
|
|
306
|
+
An affine transform to apply to the points.
|
|
307
|
+
"""
|
|
308
|
+
raise NotImplementedError
|
|
309
|
+
|
|
310
|
+
def _iter_collection_raw_paths(self, master_transform, paths,
|
|
311
|
+
all_transforms):
|
|
312
|
+
"""
|
|
313
|
+
Helper method (along with `_iter_collection`) to implement
|
|
314
|
+
`draw_path_collection` in a memory-efficient manner.
|
|
315
|
+
|
|
316
|
+
This method yields all of the base path/transform combinations, given a
|
|
317
|
+
master transform, a list of paths and list of transforms.
|
|
318
|
+
|
|
319
|
+
The arguments should be exactly what is passed in to
|
|
320
|
+
`draw_path_collection`.
|
|
321
|
+
|
|
322
|
+
The backend should take each yielded path and transform and create an
|
|
323
|
+
object that can be referenced (reused) later.
|
|
324
|
+
"""
|
|
325
|
+
Npaths = len(paths)
|
|
326
|
+
Ntransforms = len(all_transforms)
|
|
327
|
+
N = max(Npaths, Ntransforms)
|
|
328
|
+
|
|
329
|
+
if Npaths == 0:
|
|
330
|
+
return
|
|
331
|
+
|
|
332
|
+
transform = transforms.IdentityTransform()
|
|
333
|
+
for i in range(N):
|
|
334
|
+
path = paths[i % Npaths]
|
|
335
|
+
if Ntransforms:
|
|
336
|
+
transform = Affine2D(all_transforms[i % Ntransforms])
|
|
337
|
+
yield path, transform + master_transform
|
|
338
|
+
|
|
339
|
+
def _iter_collection_uses_per_path(self, paths, all_transforms,
|
|
340
|
+
offsets, facecolors, edgecolors):
|
|
341
|
+
"""
|
|
342
|
+
Compute how many times each raw path object returned by
|
|
343
|
+
`_iter_collection_raw_paths` would be used when calling
|
|
344
|
+
`_iter_collection`. This is intended for the backend to decide
|
|
345
|
+
on the tradeoff between using the paths in-line and storing
|
|
346
|
+
them once and reusing. Rounds up in case the number of uses
|
|
347
|
+
is not the same for every path.
|
|
348
|
+
"""
|
|
349
|
+
Npaths = len(paths)
|
|
350
|
+
if Npaths == 0 or len(facecolors) == len(edgecolors) == 0:
|
|
351
|
+
return 0
|
|
352
|
+
Npath_ids = max(Npaths, len(all_transforms))
|
|
353
|
+
N = max(Npath_ids, len(offsets))
|
|
354
|
+
return (N + Npath_ids - 1) // Npath_ids
|
|
355
|
+
|
|
356
|
+
def _iter_collection(self, gc, path_ids, offsets, offset_trans, facecolors,
|
|
357
|
+
edgecolors, linewidths, linestyles,
|
|
358
|
+
antialiaseds, urls, offset_position, *, hatchcolors):
|
|
359
|
+
"""
|
|
360
|
+
Helper method (along with `_iter_collection_raw_paths`) to implement
|
|
361
|
+
`draw_path_collection` in a memory-efficient manner.
|
|
362
|
+
|
|
363
|
+
This method yields all of the path, offset and graphics context
|
|
364
|
+
combinations to draw the path collection. The caller should already
|
|
365
|
+
have looped over the results of `_iter_collection_raw_paths` to draw
|
|
366
|
+
this collection.
|
|
367
|
+
|
|
368
|
+
The arguments should be the same as that passed into
|
|
369
|
+
`draw_path_collection`, with the exception of *path_ids*, which is a
|
|
370
|
+
list of arbitrary objects that the backend will use to reference one of
|
|
371
|
+
the paths created in the `_iter_collection_raw_paths` stage.
|
|
372
|
+
|
|
373
|
+
Each yielded result is of the form::
|
|
374
|
+
|
|
375
|
+
xo, yo, path_id, gc, rgbFace
|
|
376
|
+
|
|
377
|
+
where *xo*, *yo* is an offset; *path_id* is one of the elements of
|
|
378
|
+
*path_ids*; *gc* is a graphics context and *rgbFace* is a color to
|
|
379
|
+
use for filling the path.
|
|
380
|
+
"""
|
|
381
|
+
Npaths = len(path_ids)
|
|
382
|
+
Noffsets = len(offsets)
|
|
383
|
+
N = max(Npaths, Noffsets)
|
|
384
|
+
Nfacecolors = len(facecolors)
|
|
385
|
+
Nedgecolors = len(edgecolors)
|
|
386
|
+
Nhatchcolors = len(hatchcolors)
|
|
387
|
+
Nlinewidths = len(linewidths)
|
|
388
|
+
Nlinestyles = len(linestyles)
|
|
389
|
+
Nurls = len(urls)
|
|
390
|
+
|
|
391
|
+
if (Nfacecolors == 0 and Nedgecolors == 0 and Nhatchcolors == 0) or Npaths == 0:
|
|
392
|
+
return
|
|
393
|
+
|
|
394
|
+
gc0 = self.new_gc()
|
|
395
|
+
gc0.copy_properties(gc)
|
|
396
|
+
|
|
397
|
+
def cycle_or_default(seq, default=None):
|
|
398
|
+
# Cycle over *seq* if it is not empty; else always yield *default*.
|
|
399
|
+
return (itertools.cycle(seq) if len(seq)
|
|
400
|
+
else itertools.repeat(default))
|
|
401
|
+
|
|
402
|
+
pathids = cycle_or_default(path_ids)
|
|
403
|
+
toffsets = cycle_or_default(offset_trans.transform(offsets), (0, 0))
|
|
404
|
+
fcs = cycle_or_default(facecolors)
|
|
405
|
+
ecs = cycle_or_default(edgecolors)
|
|
406
|
+
hcs = cycle_or_default(hatchcolors)
|
|
407
|
+
lws = cycle_or_default(linewidths)
|
|
408
|
+
lss = cycle_or_default(linestyles)
|
|
409
|
+
aas = cycle_or_default(antialiaseds)
|
|
410
|
+
urls = cycle_or_default(urls)
|
|
411
|
+
|
|
412
|
+
if Nedgecolors == 0:
|
|
413
|
+
gc0.set_linewidth(0.0)
|
|
414
|
+
|
|
415
|
+
for pathid, (xo, yo), fc, ec, hc, lw, ls, aa, url in itertools.islice(
|
|
416
|
+
zip(pathids, toffsets, fcs, ecs, hcs, lws, lss, aas, urls), N):
|
|
417
|
+
if not (np.isfinite(xo) and np.isfinite(yo)):
|
|
418
|
+
continue
|
|
419
|
+
if Nedgecolors:
|
|
420
|
+
if Nlinewidths:
|
|
421
|
+
gc0.set_linewidth(lw)
|
|
422
|
+
if Nlinestyles:
|
|
423
|
+
gc0.set_dashes(*ls)
|
|
424
|
+
ec_rgba = colors.to_rgba(ec)
|
|
425
|
+
# Fully transparent edges are treated as "no stroke".
|
|
426
|
+
if ec_rgba[3] == 0.0:
|
|
427
|
+
gc0.set_linewidth(0)
|
|
428
|
+
else:
|
|
429
|
+
gc0.set_foreground(ec_rgba, isRGBA=True)
|
|
430
|
+
if Nhatchcolors:
|
|
431
|
+
gc0.set_hatch_color(hc)
|
|
432
|
+
if fc is not None and len(fc) == 4 and fc[3] == 0:
|
|
433
|
+
fc = None
|
|
434
|
+
gc0.set_antialiased(aa)
|
|
435
|
+
if Nurls:
|
|
436
|
+
gc0.set_url(url)
|
|
437
|
+
yield xo, yo, pathid, gc0, fc
|
|
438
|
+
gc0.restore()
|
|
439
|
+
|
|
440
|
+
def get_image_magnification(self):
|
|
441
|
+
"""
|
|
442
|
+
Get the factor by which to magnify images passed to `draw_image`.
|
|
443
|
+
Allows a backend to have images at a different resolution to other
|
|
444
|
+
artists.
|
|
445
|
+
"""
|
|
446
|
+
return 1.0
|
|
447
|
+
|
|
448
|
+
def draw_image(self, gc, x, y, im, transform=None):
|
|
449
|
+
"""
|
|
450
|
+
Draw an RGBA image.
|
|
451
|
+
|
|
452
|
+
Parameters
|
|
453
|
+
----------
|
|
454
|
+
gc : `.GraphicsContextBase`
|
|
455
|
+
A graphics context with clipping information.
|
|
456
|
+
|
|
457
|
+
x : float
|
|
458
|
+
The distance in physical units (i.e., dots or pixels) from the left
|
|
459
|
+
hand side of the canvas.
|
|
460
|
+
|
|
461
|
+
y : float
|
|
462
|
+
The distance in physical units (i.e., dots or pixels) from the
|
|
463
|
+
bottom side of the canvas.
|
|
464
|
+
|
|
465
|
+
im : (N, M, 4) array of `numpy.uint8`
|
|
466
|
+
An array of RGBA pixels.
|
|
467
|
+
|
|
468
|
+
transform : `~matplotlib.transforms.Affine2DBase`
|
|
469
|
+
If and only if the concrete backend is written such that
|
|
470
|
+
`~.RendererBase.option_scale_image` returns ``True``, an affine
|
|
471
|
+
transformation (i.e., an `.Affine2DBase`) *may* be passed to
|
|
472
|
+
`~.RendererBase.draw_image`. The translation vector of the
|
|
473
|
+
transformation is given in physical units (i.e., dots or pixels).
|
|
474
|
+
Note that the transformation does not override *x* and *y*,
|
|
475
|
+
and has to be applied *before* translatingthe result by
|
|
476
|
+
*x* and *y* (this can be accomplished by adding *x*
|
|
477
|
+
and *y* to the translation vector defined by *transform*).
|
|
478
|
+
"""
|
|
479
|
+
raise NotImplementedError
|
|
480
|
+
|
|
481
|
+
def option_image_nocomposite(self):
|
|
482
|
+
"""
|
|
483
|
+
Return whether image composition by Matplotlib should be skipped.
|
|
484
|
+
|
|
485
|
+
Raster backends should usually return False (letting the C-level
|
|
486
|
+
rasterizer take care of image composition); vector backends should
|
|
487
|
+
usually return ``not rcParams["image.composite_image"]``.
|
|
488
|
+
"""
|
|
489
|
+
return False
|
|
490
|
+
|
|
491
|
+
def option_scale_image(self):
|
|
492
|
+
"""
|
|
493
|
+
Return whether arbitrary affine transformations in
|
|
494
|
+
`~.RendererBase.draw_image` are supported (True for most vector backends).
|
|
495
|
+
"""
|
|
496
|
+
return False
|
|
497
|
+
|
|
498
|
+
def draw_tex(self, gc, x, y, s, prop, angle, *, mtext=None):
|
|
499
|
+
"""
|
|
500
|
+
Draw a TeX instance.
|
|
501
|
+
|
|
502
|
+
Parameters
|
|
503
|
+
----------
|
|
504
|
+
gc : `.GraphicsContextBase`
|
|
505
|
+
The graphics context.
|
|
506
|
+
x : float
|
|
507
|
+
The x location of the text in display coords.
|
|
508
|
+
y : float
|
|
509
|
+
The y location of the text baseline in display coords.
|
|
510
|
+
s : str
|
|
511
|
+
The TeX text string.
|
|
512
|
+
prop : `~matplotlib.font_manager.FontProperties`
|
|
513
|
+
The font properties.
|
|
514
|
+
angle : float
|
|
515
|
+
The rotation angle in degrees anti-clockwise.
|
|
516
|
+
mtext : `~matplotlib.text.Text`
|
|
517
|
+
The original text object to be rendered.
|
|
518
|
+
"""
|
|
519
|
+
self._draw_text_as_path(gc, x, y, s, prop, angle, ismath="TeX", mtext=mtext)
|
|
520
|
+
|
|
521
|
+
def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
|
|
522
|
+
"""
|
|
523
|
+
Draw a text instance.
|
|
524
|
+
|
|
525
|
+
Parameters
|
|
526
|
+
----------
|
|
527
|
+
gc : `.GraphicsContextBase`
|
|
528
|
+
The graphics context.
|
|
529
|
+
x : float
|
|
530
|
+
The x location of the text in display coords.
|
|
531
|
+
y : float
|
|
532
|
+
The y location of the text baseline in display coords.
|
|
533
|
+
s : str
|
|
534
|
+
The text string.
|
|
535
|
+
prop : `~matplotlib.font_manager.FontProperties`
|
|
536
|
+
The font properties.
|
|
537
|
+
angle : float
|
|
538
|
+
The rotation angle in degrees anti-clockwise.
|
|
539
|
+
ismath : bool or "TeX"
|
|
540
|
+
If True, use mathtext parser.
|
|
541
|
+
mtext : `~matplotlib.text.Text`
|
|
542
|
+
The original text object to be rendered.
|
|
543
|
+
|
|
544
|
+
Notes
|
|
545
|
+
-----
|
|
546
|
+
**Notes for backend implementers:**
|
|
547
|
+
|
|
548
|
+
`.RendererBase.draw_text` also supports passing "TeX" to the *ismath*
|
|
549
|
+
parameter to use TeX rendering, but this is not required for actual
|
|
550
|
+
rendering backends, and indeed many builtin backends do not support
|
|
551
|
+
this. Rather, TeX rendering is provided by `~.RendererBase.draw_tex`.
|
|
552
|
+
"""
|
|
553
|
+
self._draw_text_as_path(gc, x, y, s, prop, angle, ismath, mtext)
|
|
554
|
+
|
|
555
|
+
def _draw_text_as_path(self, gc, x, y, s, prop, angle, ismath, mtext):
|
|
556
|
+
"""
|
|
557
|
+
Draw the text by converting them to paths using `.TextToPath`.
|
|
558
|
+
|
|
559
|
+
This private helper supports the same parameters as
|
|
560
|
+
`~.RendererBase.draw_text`; setting *ismath* to "TeX" triggers TeX
|
|
561
|
+
rendering.
|
|
562
|
+
"""
|
|
563
|
+
if mtext is not None:
|
|
564
|
+
features = mtext.get_fontfeatures()
|
|
565
|
+
language = mtext.get_language()
|
|
566
|
+
else:
|
|
567
|
+
features = language = None
|
|
568
|
+
text2path = self._text2path
|
|
569
|
+
fontsize = self.points_to_pixels(prop.get_size_in_points())
|
|
570
|
+
verts, codes = text2path.get_text_path(prop, s, ismath=ismath,
|
|
571
|
+
features=features, language=language)
|
|
572
|
+
path = Path(verts, codes)
|
|
573
|
+
if self.flipy():
|
|
574
|
+
width, height = self.get_canvas_width_height()
|
|
575
|
+
transform = (Affine2D()
|
|
576
|
+
.scale(fontsize / text2path.FONT_SCALE)
|
|
577
|
+
.rotate_deg(angle)
|
|
578
|
+
.translate(x, height - y))
|
|
579
|
+
else:
|
|
580
|
+
transform = (Affine2D()
|
|
581
|
+
.scale(fontsize / text2path.FONT_SCALE)
|
|
582
|
+
.rotate_deg(angle)
|
|
583
|
+
.translate(x, y))
|
|
584
|
+
color = gc.get_rgb()
|
|
585
|
+
gc.set_linewidth(0.0)
|
|
586
|
+
self.draw_path(gc, path, transform, rgbFace=color)
|
|
587
|
+
|
|
588
|
+
def get_text_width_height_descent(self, s, prop, ismath):
|
|
589
|
+
"""
|
|
590
|
+
Get the width, height, and descent (offset from the bottom to the baseline), in
|
|
591
|
+
display coords, of the string *s* with `.FontProperties` *prop*.
|
|
592
|
+
|
|
593
|
+
Whitespace at the start and the end of *s* is included in the reported width.
|
|
594
|
+
"""
|
|
595
|
+
fontsize = prop.get_size_in_points()
|
|
596
|
+
|
|
597
|
+
if ismath == 'TeX':
|
|
598
|
+
# todo: handle properties
|
|
599
|
+
return self.get_texmanager().get_text_width_height_descent(
|
|
600
|
+
s, fontsize, renderer=self)
|
|
601
|
+
|
|
602
|
+
dpi = self.points_to_pixels(72)
|
|
603
|
+
if ismath:
|
|
604
|
+
dims = self._text2path.mathtext_parser.parse(s, dpi, prop)
|
|
605
|
+
return dims[0:3] # return width, height, descent
|
|
606
|
+
|
|
607
|
+
flags = self._text2path._get_hinting_flag()
|
|
608
|
+
font = self._text2path._get_font(prop)
|
|
609
|
+
font.set_size(fontsize, dpi)
|
|
610
|
+
# the width and height of unrotated string
|
|
611
|
+
font.set_text(s, 0.0, flags=flags)
|
|
612
|
+
w, h = font.get_width_height()
|
|
613
|
+
d = font.get_descent()
|
|
614
|
+
w /= 64.0 # convert from subpixels
|
|
615
|
+
h /= 64.0
|
|
616
|
+
d /= 64.0
|
|
617
|
+
return w, h, d
|
|
618
|
+
|
|
619
|
+
def flipy(self):
|
|
620
|
+
"""
|
|
621
|
+
Return whether y values increase from top to bottom.
|
|
622
|
+
|
|
623
|
+
Note that this only affects drawing of texts.
|
|
624
|
+
"""
|
|
625
|
+
return True
|
|
626
|
+
|
|
627
|
+
def get_canvas_width_height(self):
|
|
628
|
+
"""Return the canvas width and height in display coords."""
|
|
629
|
+
return 1, 1
|
|
630
|
+
|
|
631
|
+
def get_texmanager(self):
|
|
632
|
+
"""Return the `.TexManager` instance."""
|
|
633
|
+
if self._texmanager is None:
|
|
634
|
+
from matplotlib_rs.texmanager import TexManager
|
|
635
|
+
self._texmanager = TexManager()
|
|
636
|
+
return self._texmanager
|
|
637
|
+
|
|
638
|
+
def new_gc(self):
|
|
639
|
+
"""Return an instance of a `.GraphicsContextBase`."""
|
|
640
|
+
return GraphicsContextBase()
|
|
641
|
+
|
|
642
|
+
def points_to_pixels(self, points):
|
|
643
|
+
"""
|
|
644
|
+
Convert points to display units.
|
|
645
|
+
|
|
646
|
+
You need to override this function (unless your backend
|
|
647
|
+
doesn't have a dpi, e.g., postscript or svg). Some imaging
|
|
648
|
+
systems assume some value for pixels per inch::
|
|
649
|
+
|
|
650
|
+
points to pixels = points * pixels_per_inch/72 * dpi/72
|
|
651
|
+
|
|
652
|
+
Parameters
|
|
653
|
+
----------
|
|
654
|
+
points : float or array-like
|
|
655
|
+
|
|
656
|
+
Returns
|
|
657
|
+
-------
|
|
658
|
+
Points converted to pixels
|
|
659
|
+
"""
|
|
660
|
+
return points
|
|
661
|
+
|
|
662
|
+
def start_rasterizing(self):
|
|
663
|
+
"""
|
|
664
|
+
Switch to the raster renderer.
|
|
665
|
+
|
|
666
|
+
Used by `.MixedModeRenderer`.
|
|
667
|
+
"""
|
|
668
|
+
|
|
669
|
+
def stop_rasterizing(self):
|
|
670
|
+
"""
|
|
671
|
+
Switch back to the vector renderer and draw the contents of the raster
|
|
672
|
+
renderer as an image on the vector renderer.
|
|
673
|
+
|
|
674
|
+
Used by `.MixedModeRenderer`.
|
|
675
|
+
"""
|
|
676
|
+
|
|
677
|
+
def start_filter(self):
|
|
678
|
+
"""
|
|
679
|
+
Switch to a temporary renderer for image filtering effects.
|
|
680
|
+
|
|
681
|
+
Currently only supported by the agg renderer.
|
|
682
|
+
"""
|
|
683
|
+
|
|
684
|
+
def stop_filter(self, filter_func):
|
|
685
|
+
"""
|
|
686
|
+
Switch back to the original renderer. The contents of the temporary
|
|
687
|
+
renderer is processed with the *filter_func* and is drawn on the
|
|
688
|
+
original renderer as an image.
|
|
689
|
+
|
|
690
|
+
Currently only supported by the agg renderer.
|
|
691
|
+
"""
|
|
692
|
+
|
|
693
|
+
def _draw_disabled(self):
|
|
694
|
+
"""
|
|
695
|
+
Context manager to temporary disable drawing.
|
|
696
|
+
|
|
697
|
+
This is used for getting the drawn size of Artists. This lets us
|
|
698
|
+
run the draw process to update any Python state but does not pay the
|
|
699
|
+
cost of the draw_XYZ calls on the canvas.
|
|
700
|
+
"""
|
|
701
|
+
no_ops = {
|
|
702
|
+
meth_name: functools.update_wrapper(lambda *args, **kwargs: None,
|
|
703
|
+
getattr(RendererBase, meth_name))
|
|
704
|
+
for meth_name in dir(RendererBase)
|
|
705
|
+
if (meth_name.startswith("draw_")
|
|
706
|
+
or meth_name in ["open_group", "close_group"])
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
return _setattr_cm(self, **no_ops)
|
|
710
|
+
|
|
711
|
+
|
|
712
|
+
class GraphicsContextBase:
|
|
713
|
+
"""An abstract base class that provides color, line styles, etc."""
|
|
714
|
+
|
|
715
|
+
def __init__(self):
|
|
716
|
+
self._alpha = 1.0
|
|
717
|
+
self._forced_alpha = False # if True, _alpha overrides A from RGBA
|
|
718
|
+
self._antialiased = 1 # use 0, 1 not True, False for extension code
|
|
719
|
+
self._capstyle = CapStyle('butt')
|
|
720
|
+
self._cliprect = None
|
|
721
|
+
self._clippath = None
|
|
722
|
+
self._dashes = 0, None
|
|
723
|
+
self._joinstyle = JoinStyle('round')
|
|
724
|
+
self._linestyle = 'solid'
|
|
725
|
+
self._linewidth = 1
|
|
726
|
+
self._rgb = (0.0, 0.0, 0.0, 1.0)
|
|
727
|
+
self._hatch = None
|
|
728
|
+
self._hatch_color = None
|
|
729
|
+
self._hatch_linewidth = rcParams['hatch.linewidth']
|
|
730
|
+
self._url = None
|
|
731
|
+
self._gid = None
|
|
732
|
+
self._snap = None
|
|
733
|
+
self._sketch = None
|
|
734
|
+
|
|
735
|
+
def copy_properties(self, gc):
|
|
736
|
+
"""Copy properties from *gc* to self."""
|
|
737
|
+
self._alpha = gc._alpha
|
|
738
|
+
self._forced_alpha = gc._forced_alpha
|
|
739
|
+
self._antialiased = gc._antialiased
|
|
740
|
+
self._capstyle = gc._capstyle
|
|
741
|
+
self._cliprect = gc._cliprect
|
|
742
|
+
self._clippath = gc._clippath
|
|
743
|
+
self._dashes = gc._dashes
|
|
744
|
+
self._joinstyle = gc._joinstyle
|
|
745
|
+
self._linestyle = gc._linestyle
|
|
746
|
+
self._linewidth = gc._linewidth
|
|
747
|
+
self._rgb = gc._rgb
|
|
748
|
+
self._hatch = gc._hatch
|
|
749
|
+
self._hatch_color = gc._hatch_color
|
|
750
|
+
self._hatch_linewidth = gc._hatch_linewidth
|
|
751
|
+
self._url = gc._url
|
|
752
|
+
self._gid = gc._gid
|
|
753
|
+
self._snap = gc._snap
|
|
754
|
+
self._sketch = gc._sketch
|
|
755
|
+
|
|
756
|
+
def restore(self):
|
|
757
|
+
"""
|
|
758
|
+
Restore the graphics context from the stack - needed only
|
|
759
|
+
for backends that save graphics contexts on a stack.
|
|
760
|
+
"""
|
|
761
|
+
|
|
762
|
+
def get_alpha(self):
|
|
763
|
+
"""
|
|
764
|
+
Return the alpha value used for blending - not supported on all
|
|
765
|
+
backends.
|
|
766
|
+
"""
|
|
767
|
+
return self._alpha
|
|
768
|
+
|
|
769
|
+
def get_antialiased(self):
|
|
770
|
+
"""Return whether the object should try to do antialiased rendering."""
|
|
771
|
+
return self._antialiased
|
|
772
|
+
|
|
773
|
+
def get_capstyle(self):
|
|
774
|
+
"""Return the `.CapStyle`."""
|
|
775
|
+
return self._capstyle.name
|
|
776
|
+
|
|
777
|
+
def get_clip_rectangle(self):
|
|
778
|
+
"""
|
|
779
|
+
Return the clip rectangle as a `~matplotlib.transforms.Bbox` instance.
|
|
780
|
+
"""
|
|
781
|
+
return self._cliprect
|
|
782
|
+
|
|
783
|
+
def get_clip_path(self):
|
|
784
|
+
"""
|
|
785
|
+
Return the clip path in the form (path, transform), where path
|
|
786
|
+
is a `~.path.Path` instance, and transform is
|
|
787
|
+
an affine transform to apply to the path before clipping.
|
|
788
|
+
"""
|
|
789
|
+
if self._clippath is not None:
|
|
790
|
+
tpath, tr = self._clippath.get_transformed_path_and_affine()
|
|
791
|
+
if np.all(np.isfinite(tpath.vertices)):
|
|
792
|
+
return tpath, tr
|
|
793
|
+
else:
|
|
794
|
+
_log.warning("Ill-defined clip_path detected. Returning None.")
|
|
795
|
+
return None, None
|
|
796
|
+
return None, None
|
|
797
|
+
|
|
798
|
+
def get_dashes(self):
|
|
799
|
+
"""
|
|
800
|
+
Return the dash style as an (offset, dash-list) pair.
|
|
801
|
+
|
|
802
|
+
See `.set_dashes` for details.
|
|
803
|
+
|
|
804
|
+
Default value is (None, None).
|
|
805
|
+
"""
|
|
806
|
+
return self._dashes
|
|
807
|
+
|
|
808
|
+
def get_forced_alpha(self):
|
|
809
|
+
"""
|
|
810
|
+
Return whether the value given by get_alpha() should be used to
|
|
811
|
+
override any other alpha-channel values.
|
|
812
|
+
"""
|
|
813
|
+
return self._forced_alpha
|
|
814
|
+
|
|
815
|
+
def get_joinstyle(self):
|
|
816
|
+
"""Return the `.JoinStyle`."""
|
|
817
|
+
return self._joinstyle.name
|
|
818
|
+
|
|
819
|
+
def get_linewidth(self):
|
|
820
|
+
"""Return the line width in points."""
|
|
821
|
+
return self._linewidth
|
|
822
|
+
|
|
823
|
+
def get_rgb(self):
|
|
824
|
+
"""Return a tuple of three or four floats from 0-1."""
|
|
825
|
+
return self._rgb
|
|
826
|
+
|
|
827
|
+
def get_url(self):
|
|
828
|
+
"""Return a url if one is set, None otherwise."""
|
|
829
|
+
return self._url
|
|
830
|
+
|
|
831
|
+
def get_gid(self):
|
|
832
|
+
"""Return the object identifier if one is set, None otherwise."""
|
|
833
|
+
return self._gid
|
|
834
|
+
|
|
835
|
+
def get_snap(self):
|
|
836
|
+
"""
|
|
837
|
+
Return the snap setting, which can be:
|
|
838
|
+
|
|
839
|
+
* True: snap vertices to the nearest pixel center
|
|
840
|
+
* False: leave vertices as-is
|
|
841
|
+
* None: (auto) If the path contains only rectilinear line segments,
|
|
842
|
+
round to the nearest pixel center
|
|
843
|
+
"""
|
|
844
|
+
return self._snap
|
|
845
|
+
|
|
846
|
+
def set_alpha(self, alpha):
|
|
847
|
+
"""
|
|
848
|
+
Set the alpha value used for blending - not supported on all backends.
|
|
849
|
+
|
|
850
|
+
If ``alpha=None`` (the default), the alpha components of the
|
|
851
|
+
foreground and fill colors will be used to set their respective
|
|
852
|
+
transparencies (where applicable); otherwise, ``alpha`` will override
|
|
853
|
+
them.
|
|
854
|
+
"""
|
|
855
|
+
if alpha is not None:
|
|
856
|
+
self._alpha = alpha
|
|
857
|
+
self._forced_alpha = True
|
|
858
|
+
else:
|
|
859
|
+
self._alpha = 1.0
|
|
860
|
+
self._forced_alpha = False
|
|
861
|
+
self.set_foreground(self._rgb, isRGBA=True)
|
|
862
|
+
|
|
863
|
+
def set_antialiased(self, b):
|
|
864
|
+
"""Set whether object should be drawn with antialiased rendering."""
|
|
865
|
+
# Use ints to make life easier on extension code trying to read the gc.
|
|
866
|
+
self._antialiased = int(bool(b))
|
|
867
|
+
|
|
868
|
+
@_docstring.interpd
|
|
869
|
+
def set_capstyle(self, cs):
|
|
870
|
+
"""
|
|
871
|
+
Set how to draw endpoints of lines.
|
|
872
|
+
|
|
873
|
+
Parameters
|
|
874
|
+
----------
|
|
875
|
+
cs : `.CapStyle` or %(CapStyle)s
|
|
876
|
+
"""
|
|
877
|
+
self._capstyle = CapStyle(cs)
|
|
878
|
+
|
|
879
|
+
def set_clip_rectangle(self, rectangle):
|
|
880
|
+
"""Set the clip rectangle to a `.Bbox` or None."""
|
|
881
|
+
self._cliprect = rectangle
|
|
882
|
+
|
|
883
|
+
def set_clip_path(self, path):
|
|
884
|
+
"""Set the clip path to a `.TransformedPath` or None."""
|
|
885
|
+
_api.check_isinstance((transforms.TransformedPath, None), path=path)
|
|
886
|
+
self._clippath = path
|
|
887
|
+
|
|
888
|
+
def set_dashes(self, dash_offset, dash_list):
|
|
889
|
+
"""
|
|
890
|
+
Set the dash style for the gc.
|
|
891
|
+
|
|
892
|
+
Parameters
|
|
893
|
+
----------
|
|
894
|
+
dash_offset : float
|
|
895
|
+
Distance, in points, into the dash pattern at which to
|
|
896
|
+
start the pattern. It is usually set to 0.
|
|
897
|
+
dash_list : array-like or None
|
|
898
|
+
The on-off sequence as points. None specifies a solid line. All
|
|
899
|
+
values must otherwise be non-negative (:math:`\\ge 0`).
|
|
900
|
+
|
|
901
|
+
Notes
|
|
902
|
+
-----
|
|
903
|
+
See p. 666 of the PostScript
|
|
904
|
+
`Language Reference
|
|
905
|
+
<https://www.adobe.com/jp/print/postscript/pdfs/PLRM.pdf>`_
|
|
906
|
+
for more info.
|
|
907
|
+
"""
|
|
908
|
+
if dash_list is not None:
|
|
909
|
+
dl = np.asarray(dash_list)
|
|
910
|
+
if np.any(dl < 0.0):
|
|
911
|
+
raise ValueError(
|
|
912
|
+
"All values in the dash list must be non-negative")
|
|
913
|
+
if dl.size and not np.any(dl > 0.0):
|
|
914
|
+
raise ValueError(
|
|
915
|
+
'At least one value in the dash list must be positive')
|
|
916
|
+
self._dashes = dash_offset, dash_list
|
|
917
|
+
|
|
918
|
+
def set_foreground(self, fg, isRGBA=False):
|
|
919
|
+
"""
|
|
920
|
+
Set the foreground color.
|
|
921
|
+
|
|
922
|
+
Parameters
|
|
923
|
+
----------
|
|
924
|
+
fg : :mpltype:`color`
|
|
925
|
+
isRGBA : bool
|
|
926
|
+
If *fg* is known to be an ``(r, g, b, a)`` tuple, *isRGBA* can be
|
|
927
|
+
set to True to improve performance.
|
|
928
|
+
"""
|
|
929
|
+
if self._forced_alpha and isRGBA:
|
|
930
|
+
self._rgb = fg[:3] + (self._alpha,)
|
|
931
|
+
elif self._forced_alpha:
|
|
932
|
+
self._rgb = colors.to_rgba(fg, self._alpha)
|
|
933
|
+
elif isRGBA:
|
|
934
|
+
self._rgb = fg
|
|
935
|
+
else:
|
|
936
|
+
self._rgb = colors.to_rgba(fg)
|
|
937
|
+
|
|
938
|
+
@_docstring.interpd
|
|
939
|
+
def set_joinstyle(self, js):
|
|
940
|
+
"""
|
|
941
|
+
Set how to draw connections between line segments.
|
|
942
|
+
|
|
943
|
+
Parameters
|
|
944
|
+
----------
|
|
945
|
+
js : `.JoinStyle` or %(JoinStyle)s
|
|
946
|
+
"""
|
|
947
|
+
self._joinstyle = JoinStyle(js)
|
|
948
|
+
|
|
949
|
+
def set_linewidth(self, w):
|
|
950
|
+
"""Set the linewidth in points."""
|
|
951
|
+
self._linewidth = float(w)
|
|
952
|
+
|
|
953
|
+
def set_url(self, url):
|
|
954
|
+
"""Set the url for links in compatible backends."""
|
|
955
|
+
self._url = url
|
|
956
|
+
|
|
957
|
+
def set_gid(self, id):
|
|
958
|
+
"""Set the id."""
|
|
959
|
+
self._gid = id
|
|
960
|
+
|
|
961
|
+
def set_snap(self, snap):
|
|
962
|
+
"""
|
|
963
|
+
Set the snap setting which may be:
|
|
964
|
+
|
|
965
|
+
* True: snap vertices to the nearest pixel center
|
|
966
|
+
* False: leave vertices as-is
|
|
967
|
+
* None: (auto) If the path contains only rectilinear line segments,
|
|
968
|
+
round to the nearest pixel center
|
|
969
|
+
"""
|
|
970
|
+
self._snap = snap
|
|
971
|
+
|
|
972
|
+
def set_hatch(self, hatch):
|
|
973
|
+
"""Set the hatch style (for fills)."""
|
|
974
|
+
self._hatch = hatch
|
|
975
|
+
|
|
976
|
+
def get_hatch(self):
|
|
977
|
+
"""Get the current hatch style."""
|
|
978
|
+
return self._hatch
|
|
979
|
+
|
|
980
|
+
def get_hatch_path(self, density=6.0):
|
|
981
|
+
"""Return a `.Path` for the current hatch."""
|
|
982
|
+
hatch = self.get_hatch()
|
|
983
|
+
if hatch is None:
|
|
984
|
+
return None
|
|
985
|
+
return Path.hatch(hatch, density)
|
|
986
|
+
|
|
987
|
+
def get_hatch_color(self):
|
|
988
|
+
"""Get the hatch color."""
|
|
989
|
+
return self._hatch_color
|
|
990
|
+
|
|
991
|
+
def set_hatch_color(self, hatch_color):
|
|
992
|
+
"""Set the hatch color."""
|
|
993
|
+
self._hatch_color = colors.to_rgba(hatch_color)
|
|
994
|
+
|
|
995
|
+
def get_hatch_linewidth(self):
|
|
996
|
+
"""Get the hatch linewidth."""
|
|
997
|
+
return self._hatch_linewidth
|
|
998
|
+
|
|
999
|
+
def set_hatch_linewidth(self, hatch_linewidth):
|
|
1000
|
+
"""Set the hatch linewidth."""
|
|
1001
|
+
self._hatch_linewidth = hatch_linewidth
|
|
1002
|
+
|
|
1003
|
+
def get_sketch_params(self):
|
|
1004
|
+
"""
|
|
1005
|
+
Return the sketch parameters for the artist.
|
|
1006
|
+
|
|
1007
|
+
Returns
|
|
1008
|
+
-------
|
|
1009
|
+
tuple or `None`
|
|
1010
|
+
|
|
1011
|
+
A 3-tuple with the following elements:
|
|
1012
|
+
|
|
1013
|
+
* ``scale``: The amplitude of the wiggle perpendicular to the
|
|
1014
|
+
source line.
|
|
1015
|
+
* ``length``: The length of the wiggle along the line.
|
|
1016
|
+
* ``randomness``: The scale factor by which the length is
|
|
1017
|
+
shrunken or expanded.
|
|
1018
|
+
|
|
1019
|
+
May return `None` if no sketch parameters were set.
|
|
1020
|
+
"""
|
|
1021
|
+
return self._sketch
|
|
1022
|
+
|
|
1023
|
+
def set_sketch_params(self, scale=None, length=None, randomness=None):
|
|
1024
|
+
"""
|
|
1025
|
+
Set the sketch parameters.
|
|
1026
|
+
|
|
1027
|
+
Parameters
|
|
1028
|
+
----------
|
|
1029
|
+
scale : float, optional
|
|
1030
|
+
The amplitude of the wiggle perpendicular to the source line, in
|
|
1031
|
+
pixels. If scale is `None`, or not provided, no sketch filter will
|
|
1032
|
+
be provided.
|
|
1033
|
+
length : float, default: 128
|
|
1034
|
+
The length of the wiggle along the line, in pixels.
|
|
1035
|
+
randomness : float, default: 16
|
|
1036
|
+
The scale factor by which the length is shrunken or expanded.
|
|
1037
|
+
"""
|
|
1038
|
+
self._sketch = (
|
|
1039
|
+
None if scale is None
|
|
1040
|
+
else (scale, length or 128., randomness or 16.))
|
|
1041
|
+
|
|
1042
|
+
|
|
1043
|
+
class TimerBase:
|
|
1044
|
+
"""
|
|
1045
|
+
A base class for providing timer events, useful for things animations.
|
|
1046
|
+
Backends need to implement a few specific methods in order to use their
|
|
1047
|
+
own timing mechanisms so that the timer events are integrated into their
|
|
1048
|
+
event loops.
|
|
1049
|
+
|
|
1050
|
+
Subclasses must override the following methods:
|
|
1051
|
+
|
|
1052
|
+
- ``_timer_start``: Backend-specific code for starting the timer.
|
|
1053
|
+
- ``_timer_stop``: Backend-specific code for stopping the timer.
|
|
1054
|
+
|
|
1055
|
+
Subclasses may additionally override the following methods:
|
|
1056
|
+
|
|
1057
|
+
- ``_timer_set_single_shot``: Code for setting the timer to single shot
|
|
1058
|
+
operating mode, if supported by the timer object. If not, the `TimerBase`
|
|
1059
|
+
class itself will store the flag and the ``_on_timer`` method should be
|
|
1060
|
+
overridden to support such behavior.
|
|
1061
|
+
|
|
1062
|
+
- ``_timer_set_interval``: Code for setting the interval on the timer, if
|
|
1063
|
+
there is a method for doing so on the timer object.
|
|
1064
|
+
|
|
1065
|
+
- ``_on_timer``: The internal function that any timer object should call,
|
|
1066
|
+
which will handle the task of running all callbacks that have been set.
|
|
1067
|
+
"""
|
|
1068
|
+
|
|
1069
|
+
def __init__(self, interval=None, callbacks=None):
|
|
1070
|
+
"""
|
|
1071
|
+
Parameters
|
|
1072
|
+
----------
|
|
1073
|
+
interval : int, default: 1000ms
|
|
1074
|
+
The time between timer events in milliseconds. Will be stored as
|
|
1075
|
+
``timer.interval``.
|
|
1076
|
+
callbacks : list[tuple[callable, tuple, dict]]
|
|
1077
|
+
List of (func, args, kwargs) tuples that will be called upon timer
|
|
1078
|
+
events. This list is accessible as ``timer.callbacks`` and can be
|
|
1079
|
+
manipulated directly, or the functions `~.TimerBase.add_callback`
|
|
1080
|
+
and `~.TimerBase.remove_callback` can be used.
|
|
1081
|
+
"""
|
|
1082
|
+
self.callbacks = [] if callbacks is None else callbacks.copy()
|
|
1083
|
+
# Set .interval and not ._interval to go through the property setter.
|
|
1084
|
+
self.interval = 1000 if interval is None else interval
|
|
1085
|
+
self.single_shot = False
|
|
1086
|
+
|
|
1087
|
+
def __del__(self):
|
|
1088
|
+
"""Need to stop timer and possibly disconnect timer."""
|
|
1089
|
+
self._timer_stop()
|
|
1090
|
+
|
|
1091
|
+
def start(self):
|
|
1092
|
+
"""Start the timer."""
|
|
1093
|
+
self._timer_start()
|
|
1094
|
+
|
|
1095
|
+
def stop(self):
|
|
1096
|
+
"""Stop the timer."""
|
|
1097
|
+
self._timer_stop()
|
|
1098
|
+
|
|
1099
|
+
def _timer_start(self):
|
|
1100
|
+
pass
|
|
1101
|
+
|
|
1102
|
+
def _timer_stop(self):
|
|
1103
|
+
pass
|
|
1104
|
+
|
|
1105
|
+
@property
|
|
1106
|
+
def interval(self):
|
|
1107
|
+
"""The time between timer events, in milliseconds."""
|
|
1108
|
+
return self._interval
|
|
1109
|
+
|
|
1110
|
+
@interval.setter
|
|
1111
|
+
def interval(self, interval):
|
|
1112
|
+
# Force to int since none of the backends actually support fractional
|
|
1113
|
+
# milliseconds, and some error or give warnings.
|
|
1114
|
+
# Some backends also fail when interval == 0, so ensure >= 1 msec
|
|
1115
|
+
interval = max(int(interval), 1)
|
|
1116
|
+
self._interval = interval
|
|
1117
|
+
self._timer_set_interval()
|
|
1118
|
+
|
|
1119
|
+
@property
|
|
1120
|
+
def single_shot(self):
|
|
1121
|
+
"""Whether this timer should stop after a single run."""
|
|
1122
|
+
return self._single
|
|
1123
|
+
|
|
1124
|
+
@single_shot.setter
|
|
1125
|
+
def single_shot(self, ss):
|
|
1126
|
+
self._single = ss
|
|
1127
|
+
self._timer_set_single_shot()
|
|
1128
|
+
|
|
1129
|
+
def add_callback(self, func, *args, **kwargs):
|
|
1130
|
+
"""
|
|
1131
|
+
Register *func* to be called by timer when the event fires. Any
|
|
1132
|
+
additional arguments provided will be passed to *func*.
|
|
1133
|
+
|
|
1134
|
+
This function returns *func*, which makes it possible to use it as a
|
|
1135
|
+
decorator.
|
|
1136
|
+
"""
|
|
1137
|
+
self.callbacks.append((func, args, kwargs))
|
|
1138
|
+
return func
|
|
1139
|
+
|
|
1140
|
+
def remove_callback(self, func, *args, **kwargs):
|
|
1141
|
+
"""
|
|
1142
|
+
Remove *func* from list of callbacks.
|
|
1143
|
+
|
|
1144
|
+
*args* and *kwargs* are optional and used to distinguish between copies
|
|
1145
|
+
of the same function registered to be called with different arguments.
|
|
1146
|
+
This behavior is deprecated. In the future, ``*args, **kwargs`` won't
|
|
1147
|
+
be considered anymore; to keep a specific callback removable by itself,
|
|
1148
|
+
pass it to `add_callback` as a `functools.partial` object.
|
|
1149
|
+
"""
|
|
1150
|
+
if args or kwargs:
|
|
1151
|
+
_api.warn_deprecated(
|
|
1152
|
+
"3.1", message="In a future version, Timer.remove_callback "
|
|
1153
|
+
"will not take *args, **kwargs anymore, but remove all "
|
|
1154
|
+
"callbacks where the callable matches; to keep a specific "
|
|
1155
|
+
"callback removable by itself, pass it to add_callback as a "
|
|
1156
|
+
"functools.partial object.")
|
|
1157
|
+
self.callbacks.remove((func, args, kwargs))
|
|
1158
|
+
else:
|
|
1159
|
+
funcs = [c[0] for c in self.callbacks]
|
|
1160
|
+
if func in funcs:
|
|
1161
|
+
self.callbacks.pop(funcs.index(func))
|
|
1162
|
+
|
|
1163
|
+
def _timer_set_interval(self):
|
|
1164
|
+
"""Used to set interval on underlying timer object."""
|
|
1165
|
+
|
|
1166
|
+
def _timer_set_single_shot(self):
|
|
1167
|
+
"""Used to set single shot on underlying timer object."""
|
|
1168
|
+
|
|
1169
|
+
def _on_timer(self):
|
|
1170
|
+
"""
|
|
1171
|
+
Runs all function that have been registered as callbacks. Functions
|
|
1172
|
+
can return False (or 0) if they should not be called any more. If there
|
|
1173
|
+
are no callbacks, the timer is automatically stopped.
|
|
1174
|
+
"""
|
|
1175
|
+
for func, args, kwargs in self.callbacks:
|
|
1176
|
+
ret = func(*args, **kwargs)
|
|
1177
|
+
# docstring above explains why we use `if ret == 0` here,
|
|
1178
|
+
# instead of `if not ret`.
|
|
1179
|
+
# This will also catch `ret == False` as `False == 0`
|
|
1180
|
+
# but does not annoy the linters
|
|
1181
|
+
# https://docs.python.org/3/library/stdtypes.html#boolean-values
|
|
1182
|
+
if ret == 0:
|
|
1183
|
+
self.callbacks.remove((func, args, kwargs))
|
|
1184
|
+
|
|
1185
|
+
if len(self.callbacks) == 0:
|
|
1186
|
+
self.stop()
|
|
1187
|
+
|
|
1188
|
+
|
|
1189
|
+
class Event:
|
|
1190
|
+
"""
|
|
1191
|
+
A Matplotlib event.
|
|
1192
|
+
|
|
1193
|
+
The following attributes are defined and shown with their default values.
|
|
1194
|
+
Subclasses may define additional attributes.
|
|
1195
|
+
|
|
1196
|
+
Attributes
|
|
1197
|
+
----------
|
|
1198
|
+
name : str
|
|
1199
|
+
The event name.
|
|
1200
|
+
canvas : `FigureCanvasBase`
|
|
1201
|
+
The backend-specific canvas instance generating the event.
|
|
1202
|
+
guiEvent
|
|
1203
|
+
The GUI event that triggered the Matplotlib event.
|
|
1204
|
+
"""
|
|
1205
|
+
|
|
1206
|
+
def __init__(self, name, canvas, guiEvent=None):
|
|
1207
|
+
self.name = name
|
|
1208
|
+
self.canvas = canvas
|
|
1209
|
+
self.guiEvent = guiEvent
|
|
1210
|
+
|
|
1211
|
+
def _process(self):
|
|
1212
|
+
"""Process this event on ``self.canvas``, then unset ``guiEvent``."""
|
|
1213
|
+
self.canvas.callbacks.process(self.name, self)
|
|
1214
|
+
self.guiEvent = None
|
|
1215
|
+
|
|
1216
|
+
|
|
1217
|
+
class DrawEvent(Event):
|
|
1218
|
+
"""
|
|
1219
|
+
An event triggered by a draw operation on the canvas.
|
|
1220
|
+
|
|
1221
|
+
In most backends, callbacks subscribed to this event will be fired after
|
|
1222
|
+
the rendering is complete but before the screen is updated. Any extra
|
|
1223
|
+
artists drawn to the canvas's renderer will be reflected without an
|
|
1224
|
+
explicit call to ``blit``.
|
|
1225
|
+
|
|
1226
|
+
.. warning::
|
|
1227
|
+
|
|
1228
|
+
Calling ``canvas.draw`` and ``canvas.blit`` in these callbacks may
|
|
1229
|
+
not be safe with all backends and may cause infinite recursion.
|
|
1230
|
+
|
|
1231
|
+
A DrawEvent has a number of special attributes in addition to those defined
|
|
1232
|
+
by the parent `Event` class.
|
|
1233
|
+
|
|
1234
|
+
Attributes
|
|
1235
|
+
----------
|
|
1236
|
+
renderer : `RendererBase`
|
|
1237
|
+
The renderer for the draw event.
|
|
1238
|
+
"""
|
|
1239
|
+
def __init__(self, name, canvas, renderer):
|
|
1240
|
+
super().__init__(name, canvas)
|
|
1241
|
+
self.renderer = renderer
|
|
1242
|
+
|
|
1243
|
+
|
|
1244
|
+
class ResizeEvent(Event):
|
|
1245
|
+
"""
|
|
1246
|
+
An event triggered by a canvas resize.
|
|
1247
|
+
|
|
1248
|
+
A ResizeEvent has a number of special attributes in addition to those
|
|
1249
|
+
defined by the parent `Event` class.
|
|
1250
|
+
|
|
1251
|
+
Attributes
|
|
1252
|
+
----------
|
|
1253
|
+
width : int
|
|
1254
|
+
Width of the canvas in pixels.
|
|
1255
|
+
height : int
|
|
1256
|
+
Height of the canvas in pixels.
|
|
1257
|
+
"""
|
|
1258
|
+
|
|
1259
|
+
def __init__(self, name, canvas):
|
|
1260
|
+
super().__init__(name, canvas)
|
|
1261
|
+
self.width, self.height = canvas.get_width_height()
|
|
1262
|
+
|
|
1263
|
+
|
|
1264
|
+
class CloseEvent(Event):
|
|
1265
|
+
"""An event triggered by a figure being closed."""
|
|
1266
|
+
|
|
1267
|
+
|
|
1268
|
+
class LocationEvent(Event):
|
|
1269
|
+
"""
|
|
1270
|
+
An event that has a screen location.
|
|
1271
|
+
|
|
1272
|
+
A LocationEvent has a number of special attributes in addition to those
|
|
1273
|
+
defined by the parent `Event` class.
|
|
1274
|
+
|
|
1275
|
+
Attributes
|
|
1276
|
+
----------
|
|
1277
|
+
x, y : int or None
|
|
1278
|
+
Event location in pixels from bottom left of canvas.
|
|
1279
|
+
inaxes : `~matplotlib.axes.Axes` or None
|
|
1280
|
+
The `~.axes.Axes` instance over which the mouse is, if any.
|
|
1281
|
+
xdata, ydata : float or None
|
|
1282
|
+
Data coordinates of the mouse within *inaxes*, or *None* if the mouse
|
|
1283
|
+
is not over an Axes.
|
|
1284
|
+
modifiers : frozenset[str]
|
|
1285
|
+
The keyboard modifiers currently being pressed (except for KeyEvent).
|
|
1286
|
+
"""
|
|
1287
|
+
|
|
1288
|
+
_last_axes_ref = None
|
|
1289
|
+
|
|
1290
|
+
def __init__(self, name, canvas, x, y, guiEvent=None, *, modifiers=None):
|
|
1291
|
+
super().__init__(name, canvas, guiEvent=guiEvent)
|
|
1292
|
+
# x position - pixels from left of canvas
|
|
1293
|
+
self.x = int(x) if x is not None else x
|
|
1294
|
+
# y position - pixels from right of canvas
|
|
1295
|
+
self.y = int(y) if y is not None else y
|
|
1296
|
+
self.inaxes = None # the Axes instance the mouse is over
|
|
1297
|
+
self.xdata = None # x coord of mouse in data coords
|
|
1298
|
+
self.ydata = None # y coord of mouse in data coords
|
|
1299
|
+
self.modifiers = frozenset(modifiers if modifiers is not None else [])
|
|
1300
|
+
|
|
1301
|
+
if x is None or y is None:
|
|
1302
|
+
# cannot check if event was in Axes if no (x, y) info
|
|
1303
|
+
return
|
|
1304
|
+
|
|
1305
|
+
self._set_inaxes(self.canvas.inaxes((x, y))
|
|
1306
|
+
if self.canvas.mouse_grabber is None else
|
|
1307
|
+
self.canvas.mouse_grabber,
|
|
1308
|
+
(x, y))
|
|
1309
|
+
|
|
1310
|
+
# Splitting _set_inaxes out is useful for the axes_leave_event handler: it
|
|
1311
|
+
# needs to generate synthetic LocationEvents with manually-set inaxes. In
|
|
1312
|
+
# that latter case, xy has already been cast to int so it can directly be
|
|
1313
|
+
# read from self.x, self.y; in the normal case, however, it is more
|
|
1314
|
+
# accurate to pass the untruncated float x, y values passed to the ctor.
|
|
1315
|
+
|
|
1316
|
+
def _set_inaxes(self, inaxes, xy=None):
|
|
1317
|
+
self.inaxes = inaxes
|
|
1318
|
+
if inaxes is not None:
|
|
1319
|
+
try:
|
|
1320
|
+
self.xdata, self.ydata = inaxes.transData.inverted().transform(
|
|
1321
|
+
xy if xy is not None else (self.x, self.y))
|
|
1322
|
+
except ValueError:
|
|
1323
|
+
pass
|
|
1324
|
+
|
|
1325
|
+
|
|
1326
|
+
class MouseButton(IntEnum):
|
|
1327
|
+
LEFT = 1
|
|
1328
|
+
MIDDLE = 2
|
|
1329
|
+
RIGHT = 3
|
|
1330
|
+
BACK = 8
|
|
1331
|
+
FORWARD = 9
|
|
1332
|
+
|
|
1333
|
+
|
|
1334
|
+
class MouseEvent(LocationEvent):
|
|
1335
|
+
"""
|
|
1336
|
+
A mouse event ('button_press_event', 'button_release_event', \
|
|
1337
|
+
'scroll_event', 'motion_notify_event').
|
|
1338
|
+
|
|
1339
|
+
A MouseEvent has a number of special attributes in addition to those
|
|
1340
|
+
defined by the parent `Event` and `LocationEvent` classes.
|
|
1341
|
+
|
|
1342
|
+
Attributes
|
|
1343
|
+
----------
|
|
1344
|
+
button : None or `MouseButton` or {'up', 'down'}
|
|
1345
|
+
The button pressed. 'up' and 'down' are used for scroll events.
|
|
1346
|
+
|
|
1347
|
+
Note that LEFT and RIGHT actually refer to the "primary" and
|
|
1348
|
+
"secondary" buttons, i.e. if the user inverts their left and right
|
|
1349
|
+
buttons ("left-handed setting") then the LEFT button will be the one
|
|
1350
|
+
physically on the right.
|
|
1351
|
+
|
|
1352
|
+
If this is unset, *name* is "scroll_event", and *step* is nonzero, then
|
|
1353
|
+
this will be set to "up" or "down" depending on the sign of *step*.
|
|
1354
|
+
|
|
1355
|
+
buttons : None or frozenset
|
|
1356
|
+
For 'motion_notify_event', the mouse buttons currently being pressed
|
|
1357
|
+
(a set of zero or more MouseButtons);
|
|
1358
|
+
for other events, None.
|
|
1359
|
+
|
|
1360
|
+
.. note::
|
|
1361
|
+
For 'motion_notify_event', this attribute is more accurate than
|
|
1362
|
+
the ``button`` (singular) attribute, which is obtained from the last
|
|
1363
|
+
'button_press_event' or 'button_release_event' that occurred within
|
|
1364
|
+
the canvas (and thus 1. be wrong if the last change in mouse state
|
|
1365
|
+
occurred when the canvas did not have focus, and 2. cannot report
|
|
1366
|
+
when multiple buttons are pressed).
|
|
1367
|
+
|
|
1368
|
+
This attribute is not set for 'button_press_event' and
|
|
1369
|
+
'button_release_event' because GUI toolkits are inconsistent as to
|
|
1370
|
+
whether they report the button state *before* or *after* the
|
|
1371
|
+
press/release occurred.
|
|
1372
|
+
|
|
1373
|
+
.. warning::
|
|
1374
|
+
On macOS, the Tk backends only report a single button even if
|
|
1375
|
+
multiple buttons are pressed.
|
|
1376
|
+
|
|
1377
|
+
key : None or str
|
|
1378
|
+
The key pressed when the mouse event triggered, e.g. 'shift'.
|
|
1379
|
+
See `KeyEvent`.
|
|
1380
|
+
|
|
1381
|
+
.. warning::
|
|
1382
|
+
This key is currently obtained from the last 'key_press_event' or
|
|
1383
|
+
'key_release_event' that occurred within the canvas. Thus, if the
|
|
1384
|
+
last change of keyboard state occurred while the canvas did not have
|
|
1385
|
+
focus, this attribute will be wrong. On the other hand, the
|
|
1386
|
+
``modifiers`` attribute should always be correct, but it can only
|
|
1387
|
+
report on modifier keys.
|
|
1388
|
+
|
|
1389
|
+
step : float
|
|
1390
|
+
The number of scroll steps (positive for 'up', negative for 'down').
|
|
1391
|
+
This applies only to 'scroll_event' and defaults to 0 otherwise.
|
|
1392
|
+
|
|
1393
|
+
dblclick : bool
|
|
1394
|
+
Whether the event is a double-click. This applies only to
|
|
1395
|
+
'button_press_event' and is False otherwise. In particular, it's
|
|
1396
|
+
not used in 'button_release_event'.
|
|
1397
|
+
|
|
1398
|
+
Examples
|
|
1399
|
+
--------
|
|
1400
|
+
::
|
|
1401
|
+
|
|
1402
|
+
def on_press(event):
|
|
1403
|
+
print('you pressed', event.button, event.xdata, event.ydata)
|
|
1404
|
+
|
|
1405
|
+
cid = fig.canvas.mpl_connect('button_press_event', on_press)
|
|
1406
|
+
"""
|
|
1407
|
+
|
|
1408
|
+
def __init__(self, name, canvas, x, y, button=None, key=None,
|
|
1409
|
+
step=0, dblclick=False, guiEvent=None, *,
|
|
1410
|
+
buttons=None, modifiers=None):
|
|
1411
|
+
super().__init__(
|
|
1412
|
+
name, canvas, x, y, guiEvent=guiEvent, modifiers=modifiers)
|
|
1413
|
+
if button in MouseButton.__members__.values():
|
|
1414
|
+
button = MouseButton(button)
|
|
1415
|
+
if name == "scroll_event" and button is None:
|
|
1416
|
+
if step > 0:
|
|
1417
|
+
button = "up"
|
|
1418
|
+
elif step < 0:
|
|
1419
|
+
button = "down"
|
|
1420
|
+
self.button = button
|
|
1421
|
+
if name == "motion_notify_event":
|
|
1422
|
+
self.buttons = frozenset(buttons if buttons is not None else [])
|
|
1423
|
+
else:
|
|
1424
|
+
# We don't support 'buttons' for button_press/release_event because
|
|
1425
|
+
# toolkits are inconsistent as to whether they report the state
|
|
1426
|
+
# before or after the event.
|
|
1427
|
+
if buttons:
|
|
1428
|
+
raise ValueError(
|
|
1429
|
+
"'buttons' is only supported for 'motion_notify_event'")
|
|
1430
|
+
self.buttons = None
|
|
1431
|
+
self.key = key
|
|
1432
|
+
self.step = step
|
|
1433
|
+
self.dblclick = dblclick
|
|
1434
|
+
|
|
1435
|
+
@classmethod
|
|
1436
|
+
def _from_ax_coords(cls, name, ax, xy, *args, **kwargs):
|
|
1437
|
+
"""
|
|
1438
|
+
Generate a synthetic event at a given axes coordinate.
|
|
1439
|
+
|
|
1440
|
+
This method is intended for creating events during testing. The event
|
|
1441
|
+
can be emitted by calling its ``_process()`` method.
|
|
1442
|
+
|
|
1443
|
+
args and kwargs are mapped to `.MouseEvent.__init__` parameters,
|
|
1444
|
+
starting with `button`.
|
|
1445
|
+
"""
|
|
1446
|
+
x, y = ax.transData.transform(xy)
|
|
1447
|
+
event = cls(name, ax.figure.canvas, x, y, *args, **kwargs)
|
|
1448
|
+
event.inaxes = ax
|
|
1449
|
+
event.xdata, event.ydata = xy # Force exact xy to avoid fp roundtrip issues.
|
|
1450
|
+
return event
|
|
1451
|
+
|
|
1452
|
+
def __str__(self):
|
|
1453
|
+
return (f"{self.name}: "
|
|
1454
|
+
f"xy=({self.x}, {self.y}) xydata=({self.xdata}, {self.ydata}) "
|
|
1455
|
+
f"button={self.button} dblclick={self.dblclick} step={self.step} "
|
|
1456
|
+
f"inaxes={self.inaxes}")
|
|
1457
|
+
|
|
1458
|
+
|
|
1459
|
+
class PickEvent(Event):
|
|
1460
|
+
"""
|
|
1461
|
+
A pick event.
|
|
1462
|
+
|
|
1463
|
+
This event is fired when the user picks a location on the canvas
|
|
1464
|
+
sufficiently close to an artist that has been made pickable with
|
|
1465
|
+
`.Artist.set_picker`.
|
|
1466
|
+
|
|
1467
|
+
A PickEvent has a number of special attributes in addition to those defined
|
|
1468
|
+
by the parent `Event` class.
|
|
1469
|
+
|
|
1470
|
+
Attributes
|
|
1471
|
+
----------
|
|
1472
|
+
mouseevent : `MouseEvent`
|
|
1473
|
+
The mouse event that generated the pick.
|
|
1474
|
+
artist : `~matplotlib.artist.Artist`
|
|
1475
|
+
The picked artist. Note that artists are not pickable by default
|
|
1476
|
+
(see `.Artist.set_picker`).
|
|
1477
|
+
other
|
|
1478
|
+
Additional attributes may be present depending on the type of the
|
|
1479
|
+
picked object; e.g., a `.Line2D` pick may define different extra
|
|
1480
|
+
attributes than a `.PatchCollection` pick.
|
|
1481
|
+
|
|
1482
|
+
Examples
|
|
1483
|
+
--------
|
|
1484
|
+
Bind a function ``on_pick()`` to pick events, that prints the coordinates
|
|
1485
|
+
of the picked data point::
|
|
1486
|
+
|
|
1487
|
+
ax.plot(np.rand(100), 'o', picker=5) # 5 points tolerance
|
|
1488
|
+
|
|
1489
|
+
def on_pick(event):
|
|
1490
|
+
line = event.artist
|
|
1491
|
+
xdata, ydata = line.get_data()
|
|
1492
|
+
ind = event.ind
|
|
1493
|
+
print(f'on pick line: {xdata[ind]:.3f}, {ydata[ind]:.3f}')
|
|
1494
|
+
|
|
1495
|
+
cid = fig.canvas.mpl_connect('pick_event', on_pick)
|
|
1496
|
+
"""
|
|
1497
|
+
|
|
1498
|
+
def __init__(self, name, canvas, mouseevent, artist,
|
|
1499
|
+
guiEvent=None, **kwargs):
|
|
1500
|
+
if guiEvent is None:
|
|
1501
|
+
guiEvent = mouseevent.guiEvent
|
|
1502
|
+
super().__init__(name, canvas, guiEvent)
|
|
1503
|
+
self.mouseevent = mouseevent
|
|
1504
|
+
self.artist = artist
|
|
1505
|
+
self.__dict__.update(kwargs)
|
|
1506
|
+
|
|
1507
|
+
|
|
1508
|
+
class KeyEvent(LocationEvent):
|
|
1509
|
+
"""
|
|
1510
|
+
A key event (key press, key release).
|
|
1511
|
+
|
|
1512
|
+
A KeyEvent has a number of special attributes in addition to those defined
|
|
1513
|
+
by the parent `Event` and `LocationEvent` classes.
|
|
1514
|
+
|
|
1515
|
+
Attributes
|
|
1516
|
+
----------
|
|
1517
|
+
key : None or str
|
|
1518
|
+
The key(s) pressed. Could be *None*, a single case sensitive Unicode
|
|
1519
|
+
character ("g", "G", "#", etc.), a special key ("control", "shift",
|
|
1520
|
+
"f1", "up", etc.) or a combination of the above (e.g., "ctrl+alt+g",
|
|
1521
|
+
"ctrl+alt+G").
|
|
1522
|
+
|
|
1523
|
+
Notes
|
|
1524
|
+
-----
|
|
1525
|
+
Modifier keys will be prefixed to the pressed key and will be in the order
|
|
1526
|
+
"ctrl", "alt", "super". The exception to this rule is when the pressed key
|
|
1527
|
+
is itself a modifier key, therefore "ctrl+alt" and "alt+control" can both
|
|
1528
|
+
be valid key values.
|
|
1529
|
+
|
|
1530
|
+
Examples
|
|
1531
|
+
--------
|
|
1532
|
+
::
|
|
1533
|
+
|
|
1534
|
+
def on_key(event):
|
|
1535
|
+
print('you pressed', event.key, event.xdata, event.ydata)
|
|
1536
|
+
|
|
1537
|
+
cid = fig.canvas.mpl_connect('key_press_event', on_key)
|
|
1538
|
+
"""
|
|
1539
|
+
|
|
1540
|
+
def __init__(self, name, canvas, key, x=0, y=0, guiEvent=None):
|
|
1541
|
+
super().__init__(name, canvas, x, y, guiEvent=guiEvent)
|
|
1542
|
+
self.key = key
|
|
1543
|
+
|
|
1544
|
+
@classmethod
|
|
1545
|
+
def _from_ax_coords(cls, name, ax, xy, key, *args, **kwargs):
|
|
1546
|
+
"""
|
|
1547
|
+
Generate a synthetic event at a given axes coordinate.
|
|
1548
|
+
|
|
1549
|
+
This method is intended for creating events during testing. The event
|
|
1550
|
+
can be emitted by calling its ``_process()`` method.
|
|
1551
|
+
"""
|
|
1552
|
+
# Separate from MouseEvent._from_ax_coords instead of being defined in the base
|
|
1553
|
+
# class, due to different parameter order in the constructor signature.
|
|
1554
|
+
x, y = ax.transData.transform(xy)
|
|
1555
|
+
event = cls(name, ax.figure.canvas, key, x, y, *args, **kwargs)
|
|
1556
|
+
event.inaxes = ax
|
|
1557
|
+
event.xdata, event.ydata = xy # Force exact xy to avoid fp roundtrip issues.
|
|
1558
|
+
return event
|
|
1559
|
+
|
|
1560
|
+
|
|
1561
|
+
# Default callback for key events.
|
|
1562
|
+
def _key_handler(event):
|
|
1563
|
+
# Dead reckoning of key.
|
|
1564
|
+
if event.name == "key_press_event":
|
|
1565
|
+
event.canvas._key = event.key
|
|
1566
|
+
elif event.name == "key_release_event":
|
|
1567
|
+
event.canvas._key = None
|
|
1568
|
+
|
|
1569
|
+
|
|
1570
|
+
# Default callback for mouse events.
|
|
1571
|
+
def _mouse_handler(event):
|
|
1572
|
+
# Dead-reckoning of button and key.
|
|
1573
|
+
if event.name == "button_press_event":
|
|
1574
|
+
event.canvas._button = event.button
|
|
1575
|
+
elif event.name == "button_release_event":
|
|
1576
|
+
event.canvas._button = None
|
|
1577
|
+
elif event.name == "motion_notify_event" and event.button is None:
|
|
1578
|
+
event.button = event.canvas._button
|
|
1579
|
+
if event.key is None:
|
|
1580
|
+
event.key = event.canvas._key
|
|
1581
|
+
# Emit axes_enter/axes_leave.
|
|
1582
|
+
if event.name == "motion_notify_event":
|
|
1583
|
+
last_ref = LocationEvent._last_axes_ref
|
|
1584
|
+
last_axes = last_ref() if last_ref else None
|
|
1585
|
+
if last_axes != event.inaxes:
|
|
1586
|
+
if last_axes is not None:
|
|
1587
|
+
# Create a synthetic LocationEvent for the axes_leave_event.
|
|
1588
|
+
# Its inaxes attribute needs to be manually set (because the
|
|
1589
|
+
# cursor is actually *out* of that Axes at that point); this is
|
|
1590
|
+
# done with the internal _set_inaxes method which ensures that
|
|
1591
|
+
# the xdata and ydata attributes are also correct.
|
|
1592
|
+
try:
|
|
1593
|
+
canvas = last_axes.get_figure(root=True).canvas
|
|
1594
|
+
leave_event = LocationEvent(
|
|
1595
|
+
"axes_leave_event", canvas,
|
|
1596
|
+
event.x, event.y, event.guiEvent,
|
|
1597
|
+
modifiers=event.modifiers)
|
|
1598
|
+
leave_event._set_inaxes(last_axes)
|
|
1599
|
+
canvas.callbacks.process("axes_leave_event", leave_event)
|
|
1600
|
+
except Exception:
|
|
1601
|
+
pass # The last canvas may already have been torn down.
|
|
1602
|
+
if event.inaxes is not None:
|
|
1603
|
+
event.canvas.callbacks.process("axes_enter_event", event)
|
|
1604
|
+
LocationEvent._last_axes_ref = (
|
|
1605
|
+
weakref.ref(event.inaxes) if event.inaxes else None)
|
|
1606
|
+
|
|
1607
|
+
|
|
1608
|
+
def _get_renderer(figure, print_method=None):
|
|
1609
|
+
"""
|
|
1610
|
+
Get the renderer that would be used to save a `.Figure`.
|
|
1611
|
+
|
|
1612
|
+
If you need a renderer without any active draw methods use
|
|
1613
|
+
renderer._draw_disabled to temporary patch them out at your call site.
|
|
1614
|
+
"""
|
|
1615
|
+
# This is implemented by triggering a draw, then immediately jumping out of
|
|
1616
|
+
# Figure.draw() by raising an exception.
|
|
1617
|
+
|
|
1618
|
+
class Done(Exception):
|
|
1619
|
+
pass
|
|
1620
|
+
|
|
1621
|
+
def _draw(renderer): raise Done(renderer)
|
|
1622
|
+
|
|
1623
|
+
with cbook._setattr_cm(figure, draw=_draw), ExitStack() as stack:
|
|
1624
|
+
if print_method is None:
|
|
1625
|
+
fmt = figure.canvas.get_default_filetype()
|
|
1626
|
+
# Even for a canvas' default output type, a canvas switch may be
|
|
1627
|
+
# needed, e.g. for FigureCanvasBase.
|
|
1628
|
+
print_method = stack.enter_context(
|
|
1629
|
+
figure.canvas._switch_canvas_and_return_print_method(fmt))
|
|
1630
|
+
try:
|
|
1631
|
+
print_method(io.BytesIO())
|
|
1632
|
+
except Done as exc:
|
|
1633
|
+
renderer, = exc.args
|
|
1634
|
+
return renderer
|
|
1635
|
+
else:
|
|
1636
|
+
raise RuntimeError(f"{print_method} did not call Figure.draw, so "
|
|
1637
|
+
f"no renderer is available")
|
|
1638
|
+
|
|
1639
|
+
|
|
1640
|
+
def _no_output_draw(figure):
|
|
1641
|
+
# _no_output_draw was promoted to the figure level, but
|
|
1642
|
+
# keep this here in case someone was calling it...
|
|
1643
|
+
figure.draw_without_rendering()
|
|
1644
|
+
|
|
1645
|
+
|
|
1646
|
+
def _is_non_interactive_terminal_ipython(ip):
|
|
1647
|
+
"""
|
|
1648
|
+
Return whether we are in a terminal IPython, but non interactive.
|
|
1649
|
+
|
|
1650
|
+
When in _terminal_ IPython, ip.parent will have and `interact` attribute,
|
|
1651
|
+
if this attribute is False we do not setup eventloop integration as the
|
|
1652
|
+
user will _not_ interact with IPython. In all other case (ZMQKernel, or is
|
|
1653
|
+
interactive), we do.
|
|
1654
|
+
"""
|
|
1655
|
+
return (hasattr(ip, 'parent')
|
|
1656
|
+
and (ip.parent is not None)
|
|
1657
|
+
and getattr(ip.parent, 'interact', None) is False)
|
|
1658
|
+
|
|
1659
|
+
|
|
1660
|
+
@contextmanager
|
|
1661
|
+
def _allow_interrupt(prepare_notifier, handle_sigint):
|
|
1662
|
+
"""
|
|
1663
|
+
A context manager that allows terminating a plot by sending a SIGINT. It
|
|
1664
|
+
is necessary because the running backend prevents the Python interpreter
|
|
1665
|
+
from running and processing signals (i.e., to raise a KeyboardInterrupt).
|
|
1666
|
+
To solve this, one needs to somehow wake up the interpreter and make it
|
|
1667
|
+
close the plot window. We do this by using the signal.set_wakeup_fd()
|
|
1668
|
+
function which organizes a write of the signal number into a socketpair.
|
|
1669
|
+
A backend-specific function, *prepare_notifier*, arranges to listen to
|
|
1670
|
+
the pair's read socket while the event loop is running. (If it returns a
|
|
1671
|
+
notifier object, that object is kept alive while the context manager runs.)
|
|
1672
|
+
|
|
1673
|
+
If SIGINT was indeed caught, after exiting the on_signal() function the
|
|
1674
|
+
interpreter reacts to the signal according to the handler function which
|
|
1675
|
+
had been set up by a signal.signal() call; here, we arrange to call the
|
|
1676
|
+
backend-specific *handle_sigint* function, passing the notifier object
|
|
1677
|
+
as returned by prepare_notifier(). Finally, we call the old SIGINT
|
|
1678
|
+
handler with the same arguments that were given to our custom handler.
|
|
1679
|
+
|
|
1680
|
+
We do this only if the old handler for SIGINT was not None, which means
|
|
1681
|
+
that a non-python handler was installed, i.e. in Julia, and not SIG_IGN
|
|
1682
|
+
which means we should ignore the interrupts.
|
|
1683
|
+
|
|
1684
|
+
Parameters
|
|
1685
|
+
----------
|
|
1686
|
+
prepare_notifier : Callable[[socket.socket], object]
|
|
1687
|
+
handle_sigint : Callable[[object], object]
|
|
1688
|
+
"""
|
|
1689
|
+
|
|
1690
|
+
old_sigint_handler = signal.getsignal(signal.SIGINT)
|
|
1691
|
+
if old_sigint_handler in (None, signal.SIG_IGN, signal.SIG_DFL):
|
|
1692
|
+
yield
|
|
1693
|
+
return
|
|
1694
|
+
|
|
1695
|
+
handler_args = None
|
|
1696
|
+
wsock, rsock = socket.socketpair()
|
|
1697
|
+
wsock.setblocking(False)
|
|
1698
|
+
rsock.setblocking(False)
|
|
1699
|
+
old_wakeup_fd = signal.set_wakeup_fd(wsock.fileno())
|
|
1700
|
+
notifier = prepare_notifier(rsock)
|
|
1701
|
+
|
|
1702
|
+
def save_args_and_handle_sigint(*args):
|
|
1703
|
+
nonlocal handler_args, notifier
|
|
1704
|
+
handler_args = args
|
|
1705
|
+
handle_sigint(notifier)
|
|
1706
|
+
notifier = None
|
|
1707
|
+
|
|
1708
|
+
signal.signal(signal.SIGINT, save_args_and_handle_sigint)
|
|
1709
|
+
try:
|
|
1710
|
+
yield
|
|
1711
|
+
finally:
|
|
1712
|
+
wsock.close()
|
|
1713
|
+
rsock.close()
|
|
1714
|
+
signal.set_wakeup_fd(old_wakeup_fd)
|
|
1715
|
+
signal.signal(signal.SIGINT, old_sigint_handler)
|
|
1716
|
+
if handler_args is not None:
|
|
1717
|
+
old_sigint_handler(*handler_args)
|
|
1718
|
+
|
|
1719
|
+
|
|
1720
|
+
class FigureCanvasBase:
|
|
1721
|
+
"""
|
|
1722
|
+
The canvas the figure renders into.
|
|
1723
|
+
|
|
1724
|
+
Attributes
|
|
1725
|
+
----------
|
|
1726
|
+
figure : `~matplotlib.figure.Figure`
|
|
1727
|
+
A high-level figure instance.
|
|
1728
|
+
"""
|
|
1729
|
+
|
|
1730
|
+
# Set to one of {"qt", "gtk3", "gtk4", "wx", "tk", "macosx"} if an
|
|
1731
|
+
# interactive framework is required, or None otherwise.
|
|
1732
|
+
required_interactive_framework = None
|
|
1733
|
+
|
|
1734
|
+
# The manager class instantiated by new_manager.
|
|
1735
|
+
# (This is defined as a classproperty because the manager class is
|
|
1736
|
+
# currently defined *after* the canvas class, but one could also assign
|
|
1737
|
+
# ``FigureCanvasBase.manager_class = FigureManagerBase``
|
|
1738
|
+
# after defining both classes.)
|
|
1739
|
+
manager_class = _api.classproperty(lambda cls: FigureManagerBase)
|
|
1740
|
+
|
|
1741
|
+
events = [
|
|
1742
|
+
'resize_event',
|
|
1743
|
+
'draw_event',
|
|
1744
|
+
'key_press_event',
|
|
1745
|
+
'key_release_event',
|
|
1746
|
+
'button_press_event',
|
|
1747
|
+
'button_release_event',
|
|
1748
|
+
'scroll_event',
|
|
1749
|
+
'motion_notify_event',
|
|
1750
|
+
'pick_event',
|
|
1751
|
+
'figure_enter_event',
|
|
1752
|
+
'figure_leave_event',
|
|
1753
|
+
'axes_enter_event',
|
|
1754
|
+
'axes_leave_event',
|
|
1755
|
+
'close_event'
|
|
1756
|
+
]
|
|
1757
|
+
|
|
1758
|
+
fixed_dpi = None
|
|
1759
|
+
|
|
1760
|
+
filetypes = _default_filetypes
|
|
1761
|
+
|
|
1762
|
+
# global counter to assign unique ids to blit backgrounds
|
|
1763
|
+
# see _get_blit_background_id()
|
|
1764
|
+
_last_blit_background_id = 0
|
|
1765
|
+
|
|
1766
|
+
@_api.classproperty
|
|
1767
|
+
def supports_blit(cls):
|
|
1768
|
+
"""If this Canvas sub-class supports blitting."""
|
|
1769
|
+
return (hasattr(cls, "copy_from_bbox")
|
|
1770
|
+
and hasattr(cls, "restore_region"))
|
|
1771
|
+
|
|
1772
|
+
def __init__(self, figure=None):
|
|
1773
|
+
from matplotlib_rs.figure import Figure
|
|
1774
|
+
self._fix_ipython_backend2gui()
|
|
1775
|
+
self._is_idle_drawing = True
|
|
1776
|
+
self._is_saving = False
|
|
1777
|
+
if figure is None:
|
|
1778
|
+
figure = Figure()
|
|
1779
|
+
figure.set_canvas(self)
|
|
1780
|
+
self.figure = figure
|
|
1781
|
+
self.manager = None
|
|
1782
|
+
self.widgetlock = widgets.LockDraw()
|
|
1783
|
+
self._button = None # the button pressed
|
|
1784
|
+
self._key = None # the key pressed
|
|
1785
|
+
self.mouse_grabber = None # the Axes currently grabbing mouse
|
|
1786
|
+
self.toolbar = None # NavigationToolbar2 will set me
|
|
1787
|
+
self._is_idle_drawing = False
|
|
1788
|
+
# We don't want to scale up the figure DPI more than once.
|
|
1789
|
+
figure._original_dpi = getattr(figure, '_original_dpi', figure.dpi)
|
|
1790
|
+
self._device_pixel_ratio = 1
|
|
1791
|
+
self._blit_backgrounds = {}
|
|
1792
|
+
super().__init__() # Typically the GUI widget init (if any).
|
|
1793
|
+
|
|
1794
|
+
callbacks = property(lambda self: self.figure._canvas_callbacks)
|
|
1795
|
+
button_pick_id = property(lambda self: self.figure._button_pick_id)
|
|
1796
|
+
scroll_pick_id = property(lambda self: self.figure._scroll_pick_id)
|
|
1797
|
+
|
|
1798
|
+
@classmethod
|
|
1799
|
+
@functools.cache
|
|
1800
|
+
def _fix_ipython_backend2gui(cls):
|
|
1801
|
+
# Fix hard-coded module -> toolkit mapping in IPython (used for
|
|
1802
|
+
# `ipython --auto`). This cannot be done at import time due to
|
|
1803
|
+
# ordering issues, so we do it when creating a canvas, and should only
|
|
1804
|
+
# be done once per class (hence the `cache`).
|
|
1805
|
+
|
|
1806
|
+
# This function will not be needed when Python 3.12, the latest version
|
|
1807
|
+
# supported by IPython < 8.24, reaches end-of-life in late 2028.
|
|
1808
|
+
# At that time this function can be made a no-op and deprecated.
|
|
1809
|
+
mod_ipython = sys.modules.get("IPython")
|
|
1810
|
+
if mod_ipython is None or mod_ipython.version_info[:2] >= (8, 24):
|
|
1811
|
+
# Use of backend2gui is not needed for IPython >= 8.24 as the
|
|
1812
|
+
# functionality has been moved to Matplotlib.
|
|
1813
|
+
return
|
|
1814
|
+
|
|
1815
|
+
import IPython
|
|
1816
|
+
ip = IPython.get_ipython()
|
|
1817
|
+
if not ip:
|
|
1818
|
+
return
|
|
1819
|
+
from IPython.core import pylabtools as pt
|
|
1820
|
+
if (not hasattr(pt, "backend2gui")
|
|
1821
|
+
or not hasattr(ip, "enable_matplotlib")):
|
|
1822
|
+
# In case we ever move the patch to IPython and remove these APIs,
|
|
1823
|
+
# don't break on our side.
|
|
1824
|
+
return
|
|
1825
|
+
backend2gui_rif = {
|
|
1826
|
+
"qt": "qt",
|
|
1827
|
+
"gtk3": "gtk3",
|
|
1828
|
+
"gtk4": "gtk4",
|
|
1829
|
+
"wx": "wx",
|
|
1830
|
+
"macosx": "osx",
|
|
1831
|
+
}.get(cls.required_interactive_framework)
|
|
1832
|
+
if backend2gui_rif:
|
|
1833
|
+
if _is_non_interactive_terminal_ipython(ip):
|
|
1834
|
+
ip.enable_gui(backend2gui_rif)
|
|
1835
|
+
|
|
1836
|
+
@classmethod
|
|
1837
|
+
def new_manager(cls, figure, num):
|
|
1838
|
+
"""
|
|
1839
|
+
Create a new figure manager for *figure*, using this canvas class.
|
|
1840
|
+
|
|
1841
|
+
Notes
|
|
1842
|
+
-----
|
|
1843
|
+
This method should not be reimplemented in subclasses. If
|
|
1844
|
+
custom manager creation logic is needed, please reimplement
|
|
1845
|
+
``FigureManager.create_with_canvas``.
|
|
1846
|
+
"""
|
|
1847
|
+
return cls.manager_class.create_with_canvas(cls, figure, num)
|
|
1848
|
+
|
|
1849
|
+
@contextmanager
|
|
1850
|
+
def _idle_draw_cntx(self):
|
|
1851
|
+
self._is_idle_drawing = True
|
|
1852
|
+
try:
|
|
1853
|
+
yield
|
|
1854
|
+
finally:
|
|
1855
|
+
self._is_idle_drawing = False
|
|
1856
|
+
|
|
1857
|
+
def is_saving(self):
|
|
1858
|
+
"""
|
|
1859
|
+
Return whether the renderer is in the process of saving
|
|
1860
|
+
to a file, rather than rendering for an on-screen buffer.
|
|
1861
|
+
"""
|
|
1862
|
+
return self._is_saving
|
|
1863
|
+
|
|
1864
|
+
def blit(self, bbox=None):
|
|
1865
|
+
"""Blit the canvas in bbox (default entire canvas)."""
|
|
1866
|
+
|
|
1867
|
+
@classmethod
|
|
1868
|
+
def _get_blit_background_id(cls):
|
|
1869
|
+
"""
|
|
1870
|
+
Get a globally unique id that can be used to store a blit background.
|
|
1871
|
+
|
|
1872
|
+
Blitting support is canvas-dependent, so blitting mechanisms should
|
|
1873
|
+
store their backgrounds in the canvas, more precisely in
|
|
1874
|
+
``canvas._blit_backgrounds[id]``. The id must be obtained via this
|
|
1875
|
+
function to ensure it is globally unique.
|
|
1876
|
+
|
|
1877
|
+
The content of ``canvas._blit_backgrounds[id]`` is not specified.
|
|
1878
|
+
We leave this freedom to the blitting mechanism.
|
|
1879
|
+
|
|
1880
|
+
Blitting mechanisms must not expect that a background that they
|
|
1881
|
+
have stored is still there at a later time. The canvas may have
|
|
1882
|
+
been switched out, or we may add other mechanisms later that
|
|
1883
|
+
invalidate blit backgrounds (e.g. dpi changes).
|
|
1884
|
+
Therefore, always query as `_blit_backgrounds.get(id)` and be
|
|
1885
|
+
prepared for a None return value.
|
|
1886
|
+
|
|
1887
|
+
Note: The blit background API is still experimental and may change
|
|
1888
|
+
in the future without warning.
|
|
1889
|
+
"""
|
|
1890
|
+
cls._last_blit_background_id += 1
|
|
1891
|
+
return cls._last_blit_background_id
|
|
1892
|
+
|
|
1893
|
+
def _release_blit_background_id(self, bb_id):
|
|
1894
|
+
"""
|
|
1895
|
+
Release a blit background id that is no longer needed.
|
|
1896
|
+
|
|
1897
|
+
This removes the respective entry from the internal storage, i.e.
|
|
1898
|
+
the ``canvas._blit_backgrounds`` dict, and thus allows to free the
|
|
1899
|
+
associated memory.
|
|
1900
|
+
|
|
1901
|
+
After releasing the id you must not use it anymore.
|
|
1902
|
+
|
|
1903
|
+
It is safe to release an id that has not been used with the canvas
|
|
1904
|
+
or that has already been released.
|
|
1905
|
+
|
|
1906
|
+
Note: The blit background API is still experimental and may change
|
|
1907
|
+
in the future without warning.
|
|
1908
|
+
"""
|
|
1909
|
+
if bb_id in self._blit_backgrounds:
|
|
1910
|
+
del self._blit_backgrounds[bb_id]
|
|
1911
|
+
|
|
1912
|
+
def inaxes(self, xy):
|
|
1913
|
+
"""
|
|
1914
|
+
Return the topmost visible `~.axes.Axes` containing the point *xy*.
|
|
1915
|
+
|
|
1916
|
+
Parameters
|
|
1917
|
+
----------
|
|
1918
|
+
xy : (float, float)
|
|
1919
|
+
(x, y) pixel positions from left/bottom of the canvas.
|
|
1920
|
+
|
|
1921
|
+
Returns
|
|
1922
|
+
-------
|
|
1923
|
+
`~matplotlib.axes.Axes` or None
|
|
1924
|
+
The topmost visible Axes containing the point, or None if there
|
|
1925
|
+
is no Axes at the point.
|
|
1926
|
+
"""
|
|
1927
|
+
axes_list = [a for a in self.figure.get_axes()
|
|
1928
|
+
if a.patch.contains_point(xy) and a.get_visible()]
|
|
1929
|
+
if axes_list:
|
|
1930
|
+
axes = cbook._topmost_artist(axes_list)
|
|
1931
|
+
else:
|
|
1932
|
+
axes = None
|
|
1933
|
+
|
|
1934
|
+
return axes
|
|
1935
|
+
|
|
1936
|
+
def grab_mouse(self, ax):
|
|
1937
|
+
"""
|
|
1938
|
+
Set the child `~.axes.Axes` which is grabbing the mouse events.
|
|
1939
|
+
|
|
1940
|
+
Usually called by the widgets themselves. It is an error to call this
|
|
1941
|
+
if the mouse is already grabbed by another Axes.
|
|
1942
|
+
"""
|
|
1943
|
+
if self.mouse_grabber not in (None, ax):
|
|
1944
|
+
raise RuntimeError("Another Axes already grabs mouse input")
|
|
1945
|
+
self.mouse_grabber = ax
|
|
1946
|
+
|
|
1947
|
+
def release_mouse(self, ax):
|
|
1948
|
+
"""
|
|
1949
|
+
Release the mouse grab held by the `~.axes.Axes` *ax*.
|
|
1950
|
+
|
|
1951
|
+
Usually called by the widgets. It is ok to call this even if *ax*
|
|
1952
|
+
doesn't have the mouse grab currently.
|
|
1953
|
+
"""
|
|
1954
|
+
if self.mouse_grabber is ax:
|
|
1955
|
+
self.mouse_grabber = None
|
|
1956
|
+
|
|
1957
|
+
def set_cursor(self, cursor):
|
|
1958
|
+
"""
|
|
1959
|
+
Set the current cursor.
|
|
1960
|
+
|
|
1961
|
+
This may have no effect if the backend does not display anything.
|
|
1962
|
+
|
|
1963
|
+
If required by the backend, this method should trigger an update in
|
|
1964
|
+
the backend event loop after the cursor is set, as this method may be
|
|
1965
|
+
called e.g. before a long-running task during which the GUI is not
|
|
1966
|
+
updated.
|
|
1967
|
+
|
|
1968
|
+
Parameters
|
|
1969
|
+
----------
|
|
1970
|
+
cursor : `.Cursors`
|
|
1971
|
+
The cursor to display over the canvas. Note: some backends may
|
|
1972
|
+
change the cursor for the entire window.
|
|
1973
|
+
"""
|
|
1974
|
+
|
|
1975
|
+
def draw(self, *args, **kwargs):
|
|
1976
|
+
"""
|
|
1977
|
+
Render the `.Figure`.
|
|
1978
|
+
|
|
1979
|
+
This method must walk the artist tree, even if no output is produced,
|
|
1980
|
+
because it triggers deferred work that users may want to access
|
|
1981
|
+
before saving output to disk. For example computing limits,
|
|
1982
|
+
auto-limits, and tick values.
|
|
1983
|
+
"""
|
|
1984
|
+
|
|
1985
|
+
def draw_idle(self, *args, **kwargs):
|
|
1986
|
+
"""
|
|
1987
|
+
Request a widget redraw once control returns to the GUI event loop.
|
|
1988
|
+
|
|
1989
|
+
Even if multiple calls to `draw_idle` occur before control returns
|
|
1990
|
+
to the GUI event loop, the figure will only be rendered once.
|
|
1991
|
+
|
|
1992
|
+
Notes
|
|
1993
|
+
-----
|
|
1994
|
+
Backends may choose to override the method and implement their own
|
|
1995
|
+
strategy to prevent multiple renderings.
|
|
1996
|
+
|
|
1997
|
+
"""
|
|
1998
|
+
if not self._is_idle_drawing:
|
|
1999
|
+
with self._idle_draw_cntx():
|
|
2000
|
+
self.draw(*args, **kwargs)
|
|
2001
|
+
|
|
2002
|
+
@property
|
|
2003
|
+
def device_pixel_ratio(self):
|
|
2004
|
+
"""
|
|
2005
|
+
The ratio of physical to logical pixels used for the canvas on screen.
|
|
2006
|
+
|
|
2007
|
+
By default, this is 1, meaning physical and logical pixels are the same
|
|
2008
|
+
size. Subclasses that support High DPI screens may set this property to
|
|
2009
|
+
indicate that said ratio is different. All Matplotlib interaction,
|
|
2010
|
+
unless working directly with the canvas, remains in logical pixels.
|
|
2011
|
+
|
|
2012
|
+
"""
|
|
2013
|
+
return self._device_pixel_ratio
|
|
2014
|
+
|
|
2015
|
+
def _set_device_pixel_ratio(self, ratio):
|
|
2016
|
+
"""
|
|
2017
|
+
Set the ratio of physical to logical pixels used for the canvas.
|
|
2018
|
+
|
|
2019
|
+
Subclasses that support High DPI screens can set this property to
|
|
2020
|
+
indicate that said ratio is different. The canvas itself will be
|
|
2021
|
+
created at the physical size, while the client side will use the
|
|
2022
|
+
logical size. Thus the DPI of the Figure will change to be scaled by
|
|
2023
|
+
this ratio. Implementations that support High DPI screens should use
|
|
2024
|
+
physical pixels for events so that transforms back to Axes space are
|
|
2025
|
+
correct.
|
|
2026
|
+
|
|
2027
|
+
By default, this is 1, meaning physical and logical pixels are the same
|
|
2028
|
+
size.
|
|
2029
|
+
|
|
2030
|
+
Parameters
|
|
2031
|
+
----------
|
|
2032
|
+
ratio : float
|
|
2033
|
+
The ratio of logical to physical pixels used for the canvas.
|
|
2034
|
+
|
|
2035
|
+
Returns
|
|
2036
|
+
-------
|
|
2037
|
+
bool
|
|
2038
|
+
Whether the ratio has changed. Backends may interpret this as a
|
|
2039
|
+
signal to resize the window, repaint the canvas, or change any
|
|
2040
|
+
other relevant properties.
|
|
2041
|
+
"""
|
|
2042
|
+
if self._device_pixel_ratio == ratio:
|
|
2043
|
+
return False
|
|
2044
|
+
# In cases with mixed resolution displays, we need to be careful if the
|
|
2045
|
+
# device pixel ratio changes - in this case we need to resize the
|
|
2046
|
+
# canvas accordingly. Some backends provide events that indicate a
|
|
2047
|
+
# change in DPI, but those that don't will update this before drawing.
|
|
2048
|
+
dpi = ratio * self.figure._original_dpi
|
|
2049
|
+
self.figure._set_dpi(dpi, forward=False)
|
|
2050
|
+
self._device_pixel_ratio = ratio
|
|
2051
|
+
return True
|
|
2052
|
+
|
|
2053
|
+
def get_width_height(self, *, physical=False):
|
|
2054
|
+
"""
|
|
2055
|
+
Return the figure width and height in integral points or pixels.
|
|
2056
|
+
|
|
2057
|
+
When the figure is used on High DPI screens (and the backend supports
|
|
2058
|
+
it), the truncation to integers occurs after scaling by the device
|
|
2059
|
+
pixel ratio.
|
|
2060
|
+
|
|
2061
|
+
Parameters
|
|
2062
|
+
----------
|
|
2063
|
+
physical : bool, default: False
|
|
2064
|
+
Whether to return true physical pixels or logical pixels. Physical
|
|
2065
|
+
pixels may be used by backends that support HiDPI, but still
|
|
2066
|
+
configure the canvas using its actual size.
|
|
2067
|
+
|
|
2068
|
+
Returns
|
|
2069
|
+
-------
|
|
2070
|
+
width, height : int
|
|
2071
|
+
The size of the figure, in points or pixels, depending on the
|
|
2072
|
+
backend.
|
|
2073
|
+
|
|
2074
|
+
Notes
|
|
2075
|
+
-----
|
|
2076
|
+
This method normally truncates the height/width to remove any fractional pixel.
|
|
2077
|
+
However, if the height/width is extremely close to the integer pixel (within
|
|
2078
|
+
1e-8 pixel), the height/width is instead rounded up to account for
|
|
2079
|
+
floating-point precision effects.
|
|
2080
|
+
"""
|
|
2081
|
+
# The tolerance of 1e-8 covers a floating-point tick for even 100,000 pixels
|
|
2082
|
+
return tuple(int(size / (1 if physical else self.device_pixel_ratio) + 1e-8)
|
|
2083
|
+
for size in self.figure.bbox.max)
|
|
2084
|
+
|
|
2085
|
+
@classmethod
|
|
2086
|
+
def get_supported_filetypes(cls):
|
|
2087
|
+
"""Return dict of savefig file formats supported by this backend."""
|
|
2088
|
+
return cls.filetypes
|
|
2089
|
+
|
|
2090
|
+
@classmethod
|
|
2091
|
+
def get_supported_filetypes_grouped(cls):
|
|
2092
|
+
"""
|
|
2093
|
+
Return a dict of savefig file formats supported by this backend,
|
|
2094
|
+
where the keys are a file type name, such as 'Joint Photographic
|
|
2095
|
+
Experts Group', and the values are a list of filename extensions used
|
|
2096
|
+
for that filetype, such as ['jpg', 'jpeg'].
|
|
2097
|
+
"""
|
|
2098
|
+
groupings = {}
|
|
2099
|
+
for ext, name in cls.filetypes.items():
|
|
2100
|
+
groupings.setdefault(name, []).append(ext)
|
|
2101
|
+
groupings[name].sort()
|
|
2102
|
+
return groupings
|
|
2103
|
+
|
|
2104
|
+
@contextmanager
|
|
2105
|
+
def _switch_canvas_and_return_print_method(self, fmt, backend=None):
|
|
2106
|
+
"""
|
|
2107
|
+
Context manager temporarily setting the canvas for saving the figure::
|
|
2108
|
+
|
|
2109
|
+
with (canvas._switch_canvas_and_return_print_method(fmt, backend)
|
|
2110
|
+
as print_method):
|
|
2111
|
+
# ``print_method`` is a suitable ``print_{fmt}`` method, and
|
|
2112
|
+
# the figure's canvas is temporarily switched to the method's
|
|
2113
|
+
# canvas within the with... block. ``print_method`` is also
|
|
2114
|
+
# wrapped to suppress extra kwargs passed by ``print_figure``.
|
|
2115
|
+
|
|
2116
|
+
Parameters
|
|
2117
|
+
----------
|
|
2118
|
+
fmt : str
|
|
2119
|
+
If *backend* is None, then determine a suitable canvas class for
|
|
2120
|
+
saving to format *fmt* -- either the current canvas class, if it
|
|
2121
|
+
supports *fmt*, or whatever `get_registered_canvas_class` returns;
|
|
2122
|
+
switch the figure canvas to that canvas class.
|
|
2123
|
+
backend : str or None, default: None
|
|
2124
|
+
If not None, switch the figure canvas to the ``FigureCanvas`` class
|
|
2125
|
+
of the given backend.
|
|
2126
|
+
"""
|
|
2127
|
+
canvas = None
|
|
2128
|
+
if backend is not None:
|
|
2129
|
+
# Return a specific canvas class, if requested.
|
|
2130
|
+
from .backends.registry import backend_registry
|
|
2131
|
+
canvas_class = backend_registry.load_backend_module(backend).FigureCanvas
|
|
2132
|
+
if not hasattr(canvas_class, f"print_{fmt}"):
|
|
2133
|
+
raise ValueError(
|
|
2134
|
+
f"The {backend!r} backend does not support {fmt} output")
|
|
2135
|
+
canvas = canvas_class(self.figure)
|
|
2136
|
+
elif hasattr(self, f"print_{fmt}"):
|
|
2137
|
+
# Return the current canvas if it supports the requested format.
|
|
2138
|
+
canvas = self
|
|
2139
|
+
else:
|
|
2140
|
+
# Return a default canvas for the requested format, if it exists.
|
|
2141
|
+
canvas_class = get_registered_canvas_class(fmt)
|
|
2142
|
+
if canvas_class is None:
|
|
2143
|
+
raise ValueError(
|
|
2144
|
+
"Format {!r} is not supported (supported formats: {})".format(
|
|
2145
|
+
fmt, ", ".join(sorted(self.get_supported_filetypes()))))
|
|
2146
|
+
canvas = canvas_class(self.figure)
|
|
2147
|
+
canvas._is_saving = self._is_saving
|
|
2148
|
+
meth = getattr(canvas, f"print_{fmt}")
|
|
2149
|
+
mod = (meth.func.__module__
|
|
2150
|
+
if hasattr(meth, "func") # partialmethod, e.g. backend_wx.
|
|
2151
|
+
else meth.__module__)
|
|
2152
|
+
if mod.startswith(("matplotlib.", "matplotlib_rs.", "mpl_toolkits.")):
|
|
2153
|
+
optional_kws = { # Passed by print_figure for other renderers.
|
|
2154
|
+
"dpi", "facecolor", "edgecolor", "orientation",
|
|
2155
|
+
"bbox_inches_restore"}
|
|
2156
|
+
skip = optional_kws - {*inspect.signature(meth).parameters}
|
|
2157
|
+
print_method = functools.wraps(meth)(lambda *args, **kwargs: meth(
|
|
2158
|
+
*args, **{k: v for k, v in kwargs.items() if k not in skip}))
|
|
2159
|
+
else: # Let third-parties do as they see fit.
|
|
2160
|
+
print_method = meth
|
|
2161
|
+
try:
|
|
2162
|
+
yield print_method
|
|
2163
|
+
finally:
|
|
2164
|
+
self.figure.canvas = self
|
|
2165
|
+
|
|
2166
|
+
def print_figure(
|
|
2167
|
+
self, filename, dpi=None, facecolor=None, edgecolor=None,
|
|
2168
|
+
orientation='portrait', format=None, *,
|
|
2169
|
+
bbox_inches=None, pad_inches=None, bbox_extra_artists=None,
|
|
2170
|
+
backend=None, **kwargs):
|
|
2171
|
+
"""
|
|
2172
|
+
Render the figure to hardcopy. Set the figure patch face and edge
|
|
2173
|
+
colors. This is useful because some of the GUIs have a gray figure
|
|
2174
|
+
face color background and you'll probably want to override this on
|
|
2175
|
+
hardcopy.
|
|
2176
|
+
|
|
2177
|
+
Parameters
|
|
2178
|
+
----------
|
|
2179
|
+
filename : str or path-like or file-like
|
|
2180
|
+
The file where the figure is saved.
|
|
2181
|
+
|
|
2182
|
+
dpi : float, default: :rc:`savefig.dpi`
|
|
2183
|
+
The dots per inch to save the figure in.
|
|
2184
|
+
|
|
2185
|
+
facecolor : :mpltype:`color` or 'auto', default: :rc:`savefig.facecolor`
|
|
2186
|
+
The facecolor of the figure. If 'auto', use the current figure
|
|
2187
|
+
facecolor.
|
|
2188
|
+
|
|
2189
|
+
edgecolor : :mpltype:`color` or 'auto', default: :rc:`savefig.edgecolor`
|
|
2190
|
+
The edgecolor of the figure. If 'auto', use the current figure
|
|
2191
|
+
edgecolor.
|
|
2192
|
+
|
|
2193
|
+
orientation : {'landscape', 'portrait'}, default: 'portrait'
|
|
2194
|
+
Only currently applies to PostScript printing.
|
|
2195
|
+
|
|
2196
|
+
format : str, optional
|
|
2197
|
+
Force a specific file format. If not given, the format is inferred
|
|
2198
|
+
from the *filename* extension, and if that fails from
|
|
2199
|
+
:rc:`savefig.format`.
|
|
2200
|
+
|
|
2201
|
+
bbox_inches : 'tight' or `.Bbox`, default: :rc:`savefig.bbox`
|
|
2202
|
+
Bounding box in inches: only the given portion of the figure is
|
|
2203
|
+
saved. If 'tight', try to figure out the tight bbox of the figure.
|
|
2204
|
+
|
|
2205
|
+
pad_inches : float or 'layout', default: :rc:`savefig.pad_inches`
|
|
2206
|
+
Amount of padding in inches around the figure when bbox_inches is
|
|
2207
|
+
'tight'. If 'layout' use the padding from the constrained or
|
|
2208
|
+
compressed layout engine; ignored if one of those engines is not in
|
|
2209
|
+
use.
|
|
2210
|
+
|
|
2211
|
+
bbox_extra_artists : list of `~matplotlib.artist.Artist`, optional
|
|
2212
|
+
A list of extra artists that will be considered when the
|
|
2213
|
+
tight bbox is calculated.
|
|
2214
|
+
|
|
2215
|
+
backend : str, optional
|
|
2216
|
+
Use a non-default backend to render the file, e.g. to render a
|
|
2217
|
+
png file with the "cairo" backend rather than the default "agg",
|
|
2218
|
+
or a pdf file with the "pgf" backend rather than the default
|
|
2219
|
+
"pdf". Note that the default backend is normally sufficient. See
|
|
2220
|
+
:ref:`the-builtin-backends` for a list of valid backends for each
|
|
2221
|
+
file format. Custom backends can be referenced as "module://...".
|
|
2222
|
+
"""
|
|
2223
|
+
if format is None:
|
|
2224
|
+
# get format from filename, or from backend's default filetype
|
|
2225
|
+
if isinstance(filename, os.PathLike):
|
|
2226
|
+
filename = os.fspath(filename)
|
|
2227
|
+
if isinstance(filename, str):
|
|
2228
|
+
format = os.path.splitext(filename)[1][1:]
|
|
2229
|
+
if format is None or format == '':
|
|
2230
|
+
format = self.get_default_filetype()
|
|
2231
|
+
if isinstance(filename, str):
|
|
2232
|
+
filename = filename.rstrip('.') + '.' + format
|
|
2233
|
+
format = format.lower()
|
|
2234
|
+
|
|
2235
|
+
dpi = mpl._val_or_rc(dpi, 'savefig.dpi')
|
|
2236
|
+
if dpi == 'figure':
|
|
2237
|
+
dpi = getattr(self.figure, '_original_dpi', self.figure.dpi)
|
|
2238
|
+
|
|
2239
|
+
# Remove the figure manager, if any, to avoid resizing the GUI widget.
|
|
2240
|
+
with (cbook._setattr_cm(self, manager=None),
|
|
2241
|
+
self._switch_canvas_and_return_print_method(format, backend)
|
|
2242
|
+
as print_method,
|
|
2243
|
+
cbook._setattr_cm(self.figure, dpi=dpi),
|
|
2244
|
+
cbook._setattr_cm(self.figure.canvas, _device_pixel_ratio=1),
|
|
2245
|
+
cbook._setattr_cm(self.figure.canvas, _is_saving=True),
|
|
2246
|
+
ExitStack() as stack):
|
|
2247
|
+
|
|
2248
|
+
for prop, color in [("facecolor", facecolor), ("edgecolor", edgecolor)]:
|
|
2249
|
+
color = mpl._val_or_rc(color, f"savefig.{prop}")
|
|
2250
|
+
if not cbook._str_equal(color, "auto"):
|
|
2251
|
+
stack.enter_context(self.figure._cm_set(**{prop: color}))
|
|
2252
|
+
|
|
2253
|
+
bbox_inches = mpl._val_or_rc(bbox_inches, 'savefig.bbox')
|
|
2254
|
+
|
|
2255
|
+
layout_engine = self.figure.get_layout_engine()
|
|
2256
|
+
if layout_engine is not None or bbox_inches == "tight":
|
|
2257
|
+
# we need to trigger a draw before printing to make sure
|
|
2258
|
+
# CL works. "tight" also needs a draw to get the right
|
|
2259
|
+
# locations:
|
|
2260
|
+
renderer = _get_renderer(
|
|
2261
|
+
self.figure,
|
|
2262
|
+
functools.partial(
|
|
2263
|
+
print_method, orientation=orientation)
|
|
2264
|
+
)
|
|
2265
|
+
# we do this instead of `self.figure.draw_without_rendering`
|
|
2266
|
+
# so that we can inject the orientation
|
|
2267
|
+
with getattr(renderer, "_draw_disabled", nullcontext)():
|
|
2268
|
+
self.figure.draw(renderer)
|
|
2269
|
+
else:
|
|
2270
|
+
renderer = None
|
|
2271
|
+
|
|
2272
|
+
if bbox_inches:
|
|
2273
|
+
if bbox_inches == "tight":
|
|
2274
|
+
bbox_inches = self.figure.get_tightbbox(
|
|
2275
|
+
renderer, bbox_extra_artists=bbox_extra_artists)
|
|
2276
|
+
if (isinstance(layout_engine, ConstrainedLayoutEngine) and
|
|
2277
|
+
pad_inches == "layout"):
|
|
2278
|
+
h_pad = layout_engine.get()["h_pad"]
|
|
2279
|
+
w_pad = layout_engine.get()["w_pad"]
|
|
2280
|
+
else:
|
|
2281
|
+
if pad_inches in [None, "layout"]:
|
|
2282
|
+
pad_inches = rcParams['savefig.pad_inches']
|
|
2283
|
+
h_pad = w_pad = pad_inches
|
|
2284
|
+
bbox_inches = bbox_inches.padded(w_pad, h_pad)
|
|
2285
|
+
|
|
2286
|
+
# call adjust_bbox to save only the given area
|
|
2287
|
+
restore_bbox = _tight_bbox.adjust_bbox(
|
|
2288
|
+
self.figure, bbox_inches, renderer, self.figure.canvas.fixed_dpi)
|
|
2289
|
+
|
|
2290
|
+
_bbox_inches_restore = (bbox_inches, restore_bbox)
|
|
2291
|
+
else:
|
|
2292
|
+
_bbox_inches_restore = None
|
|
2293
|
+
|
|
2294
|
+
# we have already done layout above, so turn it off:
|
|
2295
|
+
stack.enter_context(self.figure._cm_set(layout_engine='none'))
|
|
2296
|
+
try:
|
|
2297
|
+
# _get_renderer may change the figure dpi (as vector formats
|
|
2298
|
+
# force the figure dpi to 72), so we need to set it again here.
|
|
2299
|
+
with cbook._setattr_cm(self.figure, dpi=dpi):
|
|
2300
|
+
result = print_method(
|
|
2301
|
+
filename,
|
|
2302
|
+
facecolor=facecolor,
|
|
2303
|
+
edgecolor=edgecolor,
|
|
2304
|
+
orientation=orientation,
|
|
2305
|
+
bbox_inches_restore=_bbox_inches_restore,
|
|
2306
|
+
**kwargs)
|
|
2307
|
+
finally:
|
|
2308
|
+
if bbox_inches and restore_bbox:
|
|
2309
|
+
restore_bbox()
|
|
2310
|
+
|
|
2311
|
+
return result
|
|
2312
|
+
|
|
2313
|
+
@classmethod
|
|
2314
|
+
def get_default_filetype(cls):
|
|
2315
|
+
"""
|
|
2316
|
+
Return the default savefig file format as specified in
|
|
2317
|
+
:rc:`savefig.format`.
|
|
2318
|
+
|
|
2319
|
+
The returned string does not include a period. This method is
|
|
2320
|
+
overridden in backends that only support a single file type.
|
|
2321
|
+
"""
|
|
2322
|
+
return rcParams['savefig.format']
|
|
2323
|
+
|
|
2324
|
+
def get_default_filename(self):
|
|
2325
|
+
"""
|
|
2326
|
+
Return a suitable default filename, including the extension.
|
|
2327
|
+
"""
|
|
2328
|
+
default_basename = (
|
|
2329
|
+
self.manager.get_window_title()
|
|
2330
|
+
if self.manager is not None
|
|
2331
|
+
else ''
|
|
2332
|
+
)
|
|
2333
|
+
default_basename = default_basename or 'image'
|
|
2334
|
+
# Characters to be avoided in a NT path:
|
|
2335
|
+
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#naming_conventions
|
|
2336
|
+
# plus ' '
|
|
2337
|
+
removed_chars = '<>:"/\\|?*\0 '
|
|
2338
|
+
default_basename = default_basename.translate(
|
|
2339
|
+
{ord(c): "_" for c in removed_chars})
|
|
2340
|
+
default_filetype = self.get_default_filetype()
|
|
2341
|
+
return f'{default_basename}.{default_filetype}'
|
|
2342
|
+
|
|
2343
|
+
def mpl_connect(self, s, func):
|
|
2344
|
+
"""
|
|
2345
|
+
Bind function *func* to event *s*.
|
|
2346
|
+
|
|
2347
|
+
Parameters
|
|
2348
|
+
----------
|
|
2349
|
+
s : str
|
|
2350
|
+
One of the following events ids:
|
|
2351
|
+
|
|
2352
|
+
- 'button_press_event'
|
|
2353
|
+
- 'button_release_event'
|
|
2354
|
+
- 'draw_event'
|
|
2355
|
+
- 'key_press_event'
|
|
2356
|
+
- 'key_release_event'
|
|
2357
|
+
- 'motion_notify_event'
|
|
2358
|
+
- 'pick_event'
|
|
2359
|
+
- 'resize_event'
|
|
2360
|
+
- 'scroll_event'
|
|
2361
|
+
- 'figure_enter_event',
|
|
2362
|
+
- 'figure_leave_event',
|
|
2363
|
+
- 'axes_enter_event',
|
|
2364
|
+
- 'axes_leave_event'
|
|
2365
|
+
- 'close_event'.
|
|
2366
|
+
|
|
2367
|
+
func : callable
|
|
2368
|
+
The callback function to be executed, which must have the
|
|
2369
|
+
signature::
|
|
2370
|
+
|
|
2371
|
+
def func(event: Event) -> Any
|
|
2372
|
+
|
|
2373
|
+
For the location events (button and key press/release), if the
|
|
2374
|
+
mouse is over the Axes, the ``inaxes`` attribute of the event will
|
|
2375
|
+
be set to the `~matplotlib.axes.Axes` the event occurs is over, and
|
|
2376
|
+
additionally, the variables ``xdata`` and ``ydata`` attributes will
|
|
2377
|
+
be set to the mouse location in data coordinates. See `.KeyEvent`
|
|
2378
|
+
and `.MouseEvent` for more info.
|
|
2379
|
+
|
|
2380
|
+
.. note::
|
|
2381
|
+
|
|
2382
|
+
If func is a method, this only stores a weak reference to the
|
|
2383
|
+
method. Thus, the figure does not influence the lifetime of
|
|
2384
|
+
the associated object. Usually, you want to make sure that the
|
|
2385
|
+
object is kept alive throughout the lifetime of the figure by
|
|
2386
|
+
holding a reference to it.
|
|
2387
|
+
|
|
2388
|
+
Returns
|
|
2389
|
+
-------
|
|
2390
|
+
cid
|
|
2391
|
+
A connection id that can be used with
|
|
2392
|
+
`.FigureCanvasBase.mpl_disconnect`.
|
|
2393
|
+
|
|
2394
|
+
Examples
|
|
2395
|
+
--------
|
|
2396
|
+
::
|
|
2397
|
+
|
|
2398
|
+
def on_press(event):
|
|
2399
|
+
print('you pressed', event.button, event.xdata, event.ydata)
|
|
2400
|
+
|
|
2401
|
+
cid = canvas.mpl_connect('button_press_event', on_press)
|
|
2402
|
+
"""
|
|
2403
|
+
|
|
2404
|
+
return self.callbacks.connect(s, func)
|
|
2405
|
+
|
|
2406
|
+
def mpl_disconnect(self, cid):
|
|
2407
|
+
"""
|
|
2408
|
+
Disconnect the callback with id *cid*.
|
|
2409
|
+
|
|
2410
|
+
Examples
|
|
2411
|
+
--------
|
|
2412
|
+
::
|
|
2413
|
+
|
|
2414
|
+
cid = canvas.mpl_connect('button_press_event', on_press)
|
|
2415
|
+
# ... later
|
|
2416
|
+
canvas.mpl_disconnect(cid)
|
|
2417
|
+
"""
|
|
2418
|
+
self.callbacks.disconnect(cid)
|
|
2419
|
+
|
|
2420
|
+
# Internal subclasses can override _timer_cls instead of new_timer, though
|
|
2421
|
+
# this is not a public API for third-party subclasses.
|
|
2422
|
+
_timer_cls = TimerBase
|
|
2423
|
+
|
|
2424
|
+
def new_timer(self, interval=None, callbacks=None):
|
|
2425
|
+
"""
|
|
2426
|
+
Create a new backend-specific subclass of `.TimerBase`.
|
|
2427
|
+
|
|
2428
|
+
This is useful for getting periodic events through the backend's native
|
|
2429
|
+
event loop. Implemented only for backends with GUIs.
|
|
2430
|
+
|
|
2431
|
+
Parameters
|
|
2432
|
+
----------
|
|
2433
|
+
interval : int
|
|
2434
|
+
Timer interval in milliseconds.
|
|
2435
|
+
|
|
2436
|
+
callbacks : list[tuple[callable, tuple, dict]]
|
|
2437
|
+
Sequence of (func, args, kwargs) where ``func(*args, **kwargs)``
|
|
2438
|
+
will be executed by the timer every *interval*.
|
|
2439
|
+
|
|
2440
|
+
Callbacks which return ``False`` or ``0`` will be removed from the
|
|
2441
|
+
timer.
|
|
2442
|
+
|
|
2443
|
+
Examples
|
|
2444
|
+
--------
|
|
2445
|
+
>>> timer = fig.canvas.new_timer(callbacks=[(f1, (1,), {'a': 3})])
|
|
2446
|
+
"""
|
|
2447
|
+
return self._timer_cls(interval=interval, callbacks=callbacks)
|
|
2448
|
+
|
|
2449
|
+
def flush_events(self):
|
|
2450
|
+
"""
|
|
2451
|
+
Flush the GUI events for the figure.
|
|
2452
|
+
|
|
2453
|
+
Interactive backends need to reimplement this method.
|
|
2454
|
+
"""
|
|
2455
|
+
|
|
2456
|
+
def start_event_loop(self, timeout=0):
|
|
2457
|
+
"""
|
|
2458
|
+
Start a blocking event loop.
|
|
2459
|
+
|
|
2460
|
+
Such an event loop is used by interactive functions, such as
|
|
2461
|
+
`~.Figure.ginput` and `~.Figure.waitforbuttonpress`, to wait for
|
|
2462
|
+
events.
|
|
2463
|
+
|
|
2464
|
+
The event loop blocks until a callback function triggers
|
|
2465
|
+
`stop_event_loop`, or *timeout* is reached.
|
|
2466
|
+
|
|
2467
|
+
If *timeout* is 0 or negative, never timeout.
|
|
2468
|
+
|
|
2469
|
+
Only interactive backends need to reimplement this method and it relies
|
|
2470
|
+
on `flush_events` being properly implemented.
|
|
2471
|
+
|
|
2472
|
+
Interactive backends should implement this in a more native way.
|
|
2473
|
+
"""
|
|
2474
|
+
if timeout <= 0:
|
|
2475
|
+
timeout = np.inf
|
|
2476
|
+
timestep = 0.01
|
|
2477
|
+
counter = 0
|
|
2478
|
+
self._looping = True
|
|
2479
|
+
while self._looping and counter * timestep < timeout:
|
|
2480
|
+
self.flush_events()
|
|
2481
|
+
time.sleep(timestep)
|
|
2482
|
+
counter += 1
|
|
2483
|
+
|
|
2484
|
+
def stop_event_loop(self):
|
|
2485
|
+
"""
|
|
2486
|
+
Stop the current blocking event loop.
|
|
2487
|
+
|
|
2488
|
+
Interactive backends need to reimplement this to match
|
|
2489
|
+
`start_event_loop`
|
|
2490
|
+
"""
|
|
2491
|
+
self._looping = False
|
|
2492
|
+
|
|
2493
|
+
|
|
2494
|
+
def key_press_handler(event, canvas=None, toolbar=None):
|
|
2495
|
+
"""
|
|
2496
|
+
Implement the default Matplotlib key bindings for the canvas and toolbar
|
|
2497
|
+
described at :ref:`key-event-handling`.
|
|
2498
|
+
|
|
2499
|
+
Parameters
|
|
2500
|
+
----------
|
|
2501
|
+
event : `KeyEvent`
|
|
2502
|
+
A key press/release event.
|
|
2503
|
+
canvas : `FigureCanvasBase`, default: ``event.canvas``
|
|
2504
|
+
The backend-specific canvas instance. This parameter is kept for
|
|
2505
|
+
back-compatibility, but, if set, should always be equal to
|
|
2506
|
+
``event.canvas``.
|
|
2507
|
+
toolbar : `NavigationToolbar2`, default: ``event.canvas.toolbar``
|
|
2508
|
+
The navigation cursor toolbar. This parameter is kept for
|
|
2509
|
+
back-compatibility, but, if set, should always be equal to
|
|
2510
|
+
``event.canvas.toolbar``.
|
|
2511
|
+
"""
|
|
2512
|
+
if event.key is None:
|
|
2513
|
+
return
|
|
2514
|
+
if canvas is None:
|
|
2515
|
+
canvas = event.canvas
|
|
2516
|
+
if toolbar is None:
|
|
2517
|
+
toolbar = canvas.toolbar
|
|
2518
|
+
|
|
2519
|
+
# toggle fullscreen mode (default key 'f', 'ctrl + f')
|
|
2520
|
+
if event.key in rcParams['keymap.fullscreen']:
|
|
2521
|
+
try:
|
|
2522
|
+
canvas.manager.full_screen_toggle()
|
|
2523
|
+
except AttributeError:
|
|
2524
|
+
pass
|
|
2525
|
+
|
|
2526
|
+
# quit the figure (default key 'ctrl+w')
|
|
2527
|
+
if event.key in rcParams['keymap.quit']:
|
|
2528
|
+
Gcf.destroy_fig(canvas.figure)
|
|
2529
|
+
if event.key in rcParams['keymap.quit_all']:
|
|
2530
|
+
Gcf.destroy_all()
|
|
2531
|
+
|
|
2532
|
+
if toolbar is not None:
|
|
2533
|
+
# home or reset mnemonic (default key 'h', 'home' and 'r')
|
|
2534
|
+
if event.key in rcParams['keymap.home']:
|
|
2535
|
+
toolbar.home()
|
|
2536
|
+
# forward / backward keys to enable left handed quick navigation
|
|
2537
|
+
# (default key for backward: 'left', 'backspace' and 'c')
|
|
2538
|
+
elif event.key in rcParams['keymap.back']:
|
|
2539
|
+
toolbar.back()
|
|
2540
|
+
# (default key for forward: 'right' and 'v')
|
|
2541
|
+
elif event.key in rcParams['keymap.forward']:
|
|
2542
|
+
toolbar.forward()
|
|
2543
|
+
# pan mnemonic (default key 'p')
|
|
2544
|
+
elif event.key in rcParams['keymap.pan']:
|
|
2545
|
+
toolbar.pan()
|
|
2546
|
+
toolbar._update_cursor(event)
|
|
2547
|
+
# zoom mnemonic (default key 'o')
|
|
2548
|
+
elif event.key in rcParams['keymap.zoom']:
|
|
2549
|
+
toolbar.zoom()
|
|
2550
|
+
toolbar._update_cursor(event)
|
|
2551
|
+
# saving current figure (default key 's')
|
|
2552
|
+
elif event.key in rcParams['keymap.save']:
|
|
2553
|
+
toolbar.save_figure()
|
|
2554
|
+
|
|
2555
|
+
if event.inaxes is None:
|
|
2556
|
+
return
|
|
2557
|
+
|
|
2558
|
+
# these bindings require the mouse to be over an Axes to trigger
|
|
2559
|
+
def _get_uniform_gridstate(ticks):
|
|
2560
|
+
# Return True/False if all grid lines are on or off, None if they are
|
|
2561
|
+
# not all in the same state.
|
|
2562
|
+
return (True if all(tick.gridline.get_visible() for tick in ticks) else
|
|
2563
|
+
False if not any(tick.gridline.get_visible() for tick in ticks) else
|
|
2564
|
+
None)
|
|
2565
|
+
|
|
2566
|
+
ax = event.inaxes
|
|
2567
|
+
# toggle major grids in current Axes (default key 'g')
|
|
2568
|
+
# Both here and below (for 'G'), we do nothing if *any* grid (major or
|
|
2569
|
+
# minor, x or y) is not in a uniform state, to avoid messing up user
|
|
2570
|
+
# customization.
|
|
2571
|
+
if (event.key in rcParams['keymap.grid']
|
|
2572
|
+
# Exclude minor grids not in a uniform state.
|
|
2573
|
+
and None not in [_get_uniform_gridstate(ax.xaxis.minorTicks),
|
|
2574
|
+
_get_uniform_gridstate(ax.yaxis.minorTicks)]):
|
|
2575
|
+
x_state = _get_uniform_gridstate(ax.xaxis.majorTicks)
|
|
2576
|
+
y_state = _get_uniform_gridstate(ax.yaxis.majorTicks)
|
|
2577
|
+
cycle = [(False, False), (True, False), (True, True), (False, True)]
|
|
2578
|
+
try:
|
|
2579
|
+
x_state, y_state = (
|
|
2580
|
+
cycle[(cycle.index((x_state, y_state)) + 1) % len(cycle)])
|
|
2581
|
+
except ValueError:
|
|
2582
|
+
# Exclude major grids not in a uniform state.
|
|
2583
|
+
pass
|
|
2584
|
+
else:
|
|
2585
|
+
# If turning major grids off, also turn minor grids off.
|
|
2586
|
+
ax.grid(x_state, which="major" if x_state else "both", axis="x")
|
|
2587
|
+
ax.grid(y_state, which="major" if y_state else "both", axis="y")
|
|
2588
|
+
canvas.draw_idle()
|
|
2589
|
+
# toggle major and minor grids in current Axes (default key 'G')
|
|
2590
|
+
if (event.key in rcParams['keymap.grid_minor']
|
|
2591
|
+
# Exclude major grids not in a uniform state.
|
|
2592
|
+
and None not in [_get_uniform_gridstate(ax.xaxis.majorTicks),
|
|
2593
|
+
_get_uniform_gridstate(ax.yaxis.majorTicks)]):
|
|
2594
|
+
x_state = _get_uniform_gridstate(ax.xaxis.minorTicks)
|
|
2595
|
+
y_state = _get_uniform_gridstate(ax.yaxis.minorTicks)
|
|
2596
|
+
cycle = [(False, False), (True, False), (True, True), (False, True)]
|
|
2597
|
+
try:
|
|
2598
|
+
x_state, y_state = (
|
|
2599
|
+
cycle[(cycle.index((x_state, y_state)) + 1) % len(cycle)])
|
|
2600
|
+
except ValueError:
|
|
2601
|
+
# Exclude minor grids not in a uniform state.
|
|
2602
|
+
pass
|
|
2603
|
+
else:
|
|
2604
|
+
ax.grid(x_state, which="both", axis="x")
|
|
2605
|
+
ax.grid(y_state, which="both", axis="y")
|
|
2606
|
+
canvas.draw_idle()
|
|
2607
|
+
# toggle scaling of y-axes between 'log and 'linear' (default key 'l')
|
|
2608
|
+
elif event.key in rcParams['keymap.yscale']:
|
|
2609
|
+
scale = ax.get_yscale()
|
|
2610
|
+
if scale == 'log':
|
|
2611
|
+
ax.set_yscale('linear')
|
|
2612
|
+
ax.get_figure(root=True).canvas.draw_idle()
|
|
2613
|
+
elif scale == 'linear':
|
|
2614
|
+
try:
|
|
2615
|
+
ax.set_yscale('log')
|
|
2616
|
+
except ValueError as exc:
|
|
2617
|
+
_log.warning(str(exc))
|
|
2618
|
+
ax.set_yscale('linear')
|
|
2619
|
+
ax.get_figure(root=True).canvas.draw_idle()
|
|
2620
|
+
# toggle scaling of x-axes between 'log and 'linear' (default key 'k')
|
|
2621
|
+
elif event.key in rcParams['keymap.xscale']:
|
|
2622
|
+
scalex = ax.get_xscale()
|
|
2623
|
+
if scalex == 'log':
|
|
2624
|
+
ax.set_xscale('linear')
|
|
2625
|
+
ax.get_figure(root=True).canvas.draw_idle()
|
|
2626
|
+
elif scalex == 'linear':
|
|
2627
|
+
try:
|
|
2628
|
+
ax.set_xscale('log')
|
|
2629
|
+
except ValueError as exc:
|
|
2630
|
+
_log.warning(str(exc))
|
|
2631
|
+
ax.set_xscale('linear')
|
|
2632
|
+
ax.get_figure(root=True).canvas.draw_idle()
|
|
2633
|
+
|
|
2634
|
+
|
|
2635
|
+
def button_press_handler(event, canvas=None, toolbar=None):
|
|
2636
|
+
"""
|
|
2637
|
+
The default Matplotlib button actions for extra mouse buttons.
|
|
2638
|
+
|
|
2639
|
+
Parameters are as for `key_press_handler`, except that *event* is a
|
|
2640
|
+
`MouseEvent`.
|
|
2641
|
+
"""
|
|
2642
|
+
if canvas is None:
|
|
2643
|
+
canvas = event.canvas
|
|
2644
|
+
if toolbar is None:
|
|
2645
|
+
toolbar = canvas.toolbar
|
|
2646
|
+
if toolbar is not None:
|
|
2647
|
+
button_name = str(MouseButton(event.button))
|
|
2648
|
+
if button_name in rcParams['keymap.back']:
|
|
2649
|
+
toolbar.back()
|
|
2650
|
+
elif button_name in rcParams['keymap.forward']:
|
|
2651
|
+
toolbar.forward()
|
|
2652
|
+
|
|
2653
|
+
|
|
2654
|
+
def scroll_handler(event, canvas=None, toolbar=None):
|
|
2655
|
+
ax = event.inaxes
|
|
2656
|
+
if ax is None:
|
|
2657
|
+
return
|
|
2658
|
+
if ax.name != "rectilinear":
|
|
2659
|
+
# zooming is currently only supported on rectilinear axes
|
|
2660
|
+
return
|
|
2661
|
+
|
|
2662
|
+
if toolbar is None:
|
|
2663
|
+
toolbar = (canvas or event.canvas).toolbar
|
|
2664
|
+
|
|
2665
|
+
if toolbar is None:
|
|
2666
|
+
# technically we do not need a toolbar, but until wheel zoom was
|
|
2667
|
+
# introduced, any interactive modification was only possible through
|
|
2668
|
+
# the toolbar tools. For now, we keep the restriction that a toolbar
|
|
2669
|
+
# is required for interactive navigation.
|
|
2670
|
+
return
|
|
2671
|
+
|
|
2672
|
+
if event.key in {"control", "x", "y"}: # zoom towards the mouse position
|
|
2673
|
+
toolbar.push_current()
|
|
2674
|
+
|
|
2675
|
+
xmin, xmax = ax.get_xlim()
|
|
2676
|
+
ymin, ymax = ax.get_ylim()
|
|
2677
|
+
(xmin, ymin), (xmax, ymax) = ax.transScale.transform(
|
|
2678
|
+
[(xmin, ymin), (xmax, ymax)])
|
|
2679
|
+
|
|
2680
|
+
# mouse position in scaled (e.g., log) data coordinates
|
|
2681
|
+
x, y = ax.transScale.transform((event.xdata, event.ydata))
|
|
2682
|
+
|
|
2683
|
+
scale_factor = 0.85 ** event.step
|
|
2684
|
+
# Determine which axes to scale based on key
|
|
2685
|
+
zoom_x = event.key in {"control", "x"}
|
|
2686
|
+
zoom_y = event.key in {"control", "y"}
|
|
2687
|
+
|
|
2688
|
+
if zoom_x:
|
|
2689
|
+
new_xmin = x - (x - xmin) * scale_factor
|
|
2690
|
+
new_xmax = x + (xmax - x) * scale_factor
|
|
2691
|
+
else:
|
|
2692
|
+
new_xmin, new_xmax = xmin, xmax
|
|
2693
|
+
|
|
2694
|
+
if zoom_y:
|
|
2695
|
+
new_ymin = y - (y - ymin) * scale_factor
|
|
2696
|
+
new_ymax = y + (ymax - y) * scale_factor
|
|
2697
|
+
else:
|
|
2698
|
+
new_ymin, new_ymax = ymin, ymax
|
|
2699
|
+
|
|
2700
|
+
inv_scale = ax.transScale.inverted()
|
|
2701
|
+
(new_xmin, new_ymin), (new_xmax, new_ymax) = inv_scale.transform(
|
|
2702
|
+
[(new_xmin, new_ymin), (new_xmax, new_ymax)])
|
|
2703
|
+
|
|
2704
|
+
ax.set_xlim(new_xmin, new_xmax)
|
|
2705
|
+
ax.set_ylim(new_ymin, new_ymax)
|
|
2706
|
+
|
|
2707
|
+
ax.figure.canvas.draw_idle()
|
|
2708
|
+
|
|
2709
|
+
|
|
2710
|
+
class NonGuiException(Exception):
|
|
2711
|
+
"""Raised when trying show a figure in a non-GUI backend."""
|
|
2712
|
+
pass
|
|
2713
|
+
|
|
2714
|
+
|
|
2715
|
+
class FigureManagerBase:
|
|
2716
|
+
"""
|
|
2717
|
+
A backend-independent abstraction of a figure container and controller.
|
|
2718
|
+
|
|
2719
|
+
The figure manager is used by pyplot to interact with the window in a
|
|
2720
|
+
backend-independent way. It's an adapter for the real (GUI) framework that
|
|
2721
|
+
represents the visual figure on screen.
|
|
2722
|
+
|
|
2723
|
+
The figure manager is connected to a specific canvas instance, which in turn
|
|
2724
|
+
is connected to a specific figure instance. To access a figure manager for
|
|
2725
|
+
a given figure in user code, you typically use ``fig.canvas.manager``.
|
|
2726
|
+
|
|
2727
|
+
GUI backends derive from this class to translate common operations such
|
|
2728
|
+
as *show* or *resize* to the GUI-specific code. Non-GUI backends do not
|
|
2729
|
+
support these operations and can just use the base class.
|
|
2730
|
+
|
|
2731
|
+
This following basic operations are accessible:
|
|
2732
|
+
|
|
2733
|
+
**Window operations**
|
|
2734
|
+
|
|
2735
|
+
- `~.FigureManagerBase.show`
|
|
2736
|
+
- `~.FigureManagerBase.destroy`
|
|
2737
|
+
- `~.FigureManagerBase.full_screen_toggle`
|
|
2738
|
+
- `~.FigureManagerBase.resize`
|
|
2739
|
+
- `~.FigureManagerBase.get_window_title`
|
|
2740
|
+
- `~.FigureManagerBase.set_window_title`
|
|
2741
|
+
|
|
2742
|
+
**Key and mouse button press handling**
|
|
2743
|
+
|
|
2744
|
+
The figure manager sets up default key and mouse button press handling by
|
|
2745
|
+
hooking up the `.key_press_handler` to the matplotlib event system. This
|
|
2746
|
+
ensures the same shortcuts and mouse actions across backends.
|
|
2747
|
+
|
|
2748
|
+
**Other operations**
|
|
2749
|
+
|
|
2750
|
+
Subclasses will have additional attributes and functions to access
|
|
2751
|
+
additional functionality. This is of course backend-specific. For example,
|
|
2752
|
+
most GUI backends have ``window`` and ``toolbar`` attributes that give
|
|
2753
|
+
access to the native GUI widgets of the respective framework.
|
|
2754
|
+
|
|
2755
|
+
Attributes
|
|
2756
|
+
----------
|
|
2757
|
+
canvas : `FigureCanvasBase`
|
|
2758
|
+
The backend-specific canvas instance.
|
|
2759
|
+
|
|
2760
|
+
num : int or str
|
|
2761
|
+
The figure number.
|
|
2762
|
+
|
|
2763
|
+
key_press_handler_id : int
|
|
2764
|
+
The default key handler cid, when using the toolmanager.
|
|
2765
|
+
To disable the default key press handling use::
|
|
2766
|
+
|
|
2767
|
+
figure.canvas.mpl_disconnect(
|
|
2768
|
+
figure.canvas.manager.key_press_handler_id)
|
|
2769
|
+
|
|
2770
|
+
button_press_handler_id : int
|
|
2771
|
+
The default mouse button handler cid, when using the toolmanager.
|
|
2772
|
+
To disable the default button press handling use::
|
|
2773
|
+
|
|
2774
|
+
figure.canvas.mpl_disconnect(
|
|
2775
|
+
figure.canvas.manager.button_press_handler_id)
|
|
2776
|
+
"""
|
|
2777
|
+
|
|
2778
|
+
_toolbar2_class = None
|
|
2779
|
+
_toolmanager_toolbar_class = None
|
|
2780
|
+
|
|
2781
|
+
def __init__(self, canvas, num):
|
|
2782
|
+
self.canvas = canvas
|
|
2783
|
+
canvas.manager = self # store a pointer to parent
|
|
2784
|
+
self.num = num
|
|
2785
|
+
self.set_window_title(f"Figure {num:d}")
|
|
2786
|
+
|
|
2787
|
+
self.key_press_handler_id = None
|
|
2788
|
+
self.button_press_handler_id = None
|
|
2789
|
+
self.scroll_handler_id = None
|
|
2790
|
+
if rcParams['toolbar'] != 'toolmanager':
|
|
2791
|
+
self.key_press_handler_id = self.canvas.mpl_connect(
|
|
2792
|
+
'key_press_event', key_press_handler)
|
|
2793
|
+
self.button_press_handler_id = self.canvas.mpl_connect(
|
|
2794
|
+
'button_press_event', button_press_handler)
|
|
2795
|
+
self.scroll_handler_id = self.canvas.mpl_connect(
|
|
2796
|
+
'scroll_event', scroll_handler)
|
|
2797
|
+
|
|
2798
|
+
self.toolmanager = (ToolManager(canvas.figure)
|
|
2799
|
+
if mpl.rcParams['toolbar'] == 'toolmanager'
|
|
2800
|
+
else None)
|
|
2801
|
+
if (mpl.rcParams["toolbar"] == "toolbar2"
|
|
2802
|
+
and self._toolbar2_class):
|
|
2803
|
+
self.toolbar = self._toolbar2_class(self.canvas)
|
|
2804
|
+
elif (mpl.rcParams["toolbar"] == "toolmanager"
|
|
2805
|
+
and self._toolmanager_toolbar_class):
|
|
2806
|
+
self.toolbar = self._toolmanager_toolbar_class(self.toolmanager)
|
|
2807
|
+
else:
|
|
2808
|
+
self.toolbar = None
|
|
2809
|
+
|
|
2810
|
+
if self.toolmanager:
|
|
2811
|
+
tools.add_tools_to_manager(self.toolmanager)
|
|
2812
|
+
if self.toolbar:
|
|
2813
|
+
tools.add_tools_to_container(self.toolbar)
|
|
2814
|
+
|
|
2815
|
+
@self.canvas.figure.add_axobserver
|
|
2816
|
+
def notify_axes_change(fig):
|
|
2817
|
+
# Called whenever the current Axes is changed.
|
|
2818
|
+
if self.toolmanager is None and self.toolbar is not None:
|
|
2819
|
+
self.toolbar.update()
|
|
2820
|
+
|
|
2821
|
+
@classmethod
|
|
2822
|
+
def create_with_canvas(cls, canvas_class, figure, num):
|
|
2823
|
+
"""
|
|
2824
|
+
Create a manager for a given *figure* using a specific *canvas_class*.
|
|
2825
|
+
|
|
2826
|
+
Backends should override this method if they have specific needs for
|
|
2827
|
+
setting up the canvas or the manager.
|
|
2828
|
+
"""
|
|
2829
|
+
return cls(canvas_class(figure), num)
|
|
2830
|
+
|
|
2831
|
+
@classmethod
|
|
2832
|
+
def start_main_loop(cls):
|
|
2833
|
+
"""
|
|
2834
|
+
Start the main event loop.
|
|
2835
|
+
|
|
2836
|
+
This method is called by `.FigureManagerBase.pyplot_show`, which is the
|
|
2837
|
+
implementation of `.pyplot.show`. To customize the behavior of
|
|
2838
|
+
`.pyplot.show`, interactive backends should usually override
|
|
2839
|
+
`~.FigureManagerBase.start_main_loop`; if more customized logic is
|
|
2840
|
+
necessary, `~.FigureManagerBase.pyplot_show` can also be overridden.
|
|
2841
|
+
"""
|
|
2842
|
+
|
|
2843
|
+
@classmethod
|
|
2844
|
+
def pyplot_show(cls, *, block=None):
|
|
2845
|
+
"""
|
|
2846
|
+
Show all figures. This method is the implementation of `.pyplot.show`.
|
|
2847
|
+
|
|
2848
|
+
To customize the behavior of `.pyplot.show`, interactive backends
|
|
2849
|
+
should usually override `~.FigureManagerBase.start_main_loop`; if more
|
|
2850
|
+
customized logic is necessary, `~.FigureManagerBase.pyplot_show` can
|
|
2851
|
+
also be overridden.
|
|
2852
|
+
|
|
2853
|
+
Parameters
|
|
2854
|
+
----------
|
|
2855
|
+
block : bool, optional
|
|
2856
|
+
Whether to block by calling ``start_main_loop``. The default,
|
|
2857
|
+
None, means to block if we are neither in IPython's ``%pylab`` mode
|
|
2858
|
+
nor in ``interactive`` mode.
|
|
2859
|
+
"""
|
|
2860
|
+
managers = Gcf.get_all_fig_managers()
|
|
2861
|
+
if not managers:
|
|
2862
|
+
return
|
|
2863
|
+
for manager in managers:
|
|
2864
|
+
try:
|
|
2865
|
+
manager.show() # Emits a warning for non-interactive backend.
|
|
2866
|
+
except NonGuiException as exc:
|
|
2867
|
+
_api.warn_external(str(exc))
|
|
2868
|
+
if block is None:
|
|
2869
|
+
# Hack: Are we in IPython's %pylab mode? In pylab mode, IPython
|
|
2870
|
+
# (>= 0.10) tacks a _needmain attribute onto pyplot.show (always
|
|
2871
|
+
# set to False).
|
|
2872
|
+
pyplot_show = getattr(sys.modules.get("matplotlib_rs.pyplot"), "show", None)
|
|
2873
|
+
ipython_pylab = hasattr(pyplot_show, "_needmain")
|
|
2874
|
+
block = not ipython_pylab and not is_interactive()
|
|
2875
|
+
if block:
|
|
2876
|
+
cls.start_main_loop()
|
|
2877
|
+
|
|
2878
|
+
def show(self):
|
|
2879
|
+
"""
|
|
2880
|
+
For GUI backends, show the figure window and redraw.
|
|
2881
|
+
For non-GUI backends, raise an exception, unless running headless (i.e.
|
|
2882
|
+
on Linux with an unset DISPLAY); this exception is converted to a
|
|
2883
|
+
warning in `.Figure.show`.
|
|
2884
|
+
"""
|
|
2885
|
+
# This should be overridden in GUI backends.
|
|
2886
|
+
if sys.platform == "linux" and not os.environ.get("DISPLAY"):
|
|
2887
|
+
# We cannot check _get_running_interactive_framework() ==
|
|
2888
|
+
# "headless" because that would also suppress the warning when
|
|
2889
|
+
# $DISPLAY exists but is invalid, which is more likely an error and
|
|
2890
|
+
# thus warrants a warning.
|
|
2891
|
+
return
|
|
2892
|
+
raise NonGuiException(
|
|
2893
|
+
f"{type(self.canvas).__name__} is non-interactive, and thus cannot be "
|
|
2894
|
+
f"shown")
|
|
2895
|
+
|
|
2896
|
+
def destroy(self):
|
|
2897
|
+
# managers may have swapped the canvas to a GUI-framework specific one.
|
|
2898
|
+
# restore the base canvas when the manager is destroyed.
|
|
2899
|
+
self.canvas.figure._set_base_canvas()
|
|
2900
|
+
|
|
2901
|
+
def full_screen_toggle(self):
|
|
2902
|
+
pass
|
|
2903
|
+
|
|
2904
|
+
def resize(self, w, h):
|
|
2905
|
+
"""For GUI backends, resize the window (in physical pixels)."""
|
|
2906
|
+
|
|
2907
|
+
def get_window_title(self):
|
|
2908
|
+
"""Return the title text of the window containing the figure."""
|
|
2909
|
+
return self._window_title
|
|
2910
|
+
|
|
2911
|
+
def set_window_title(self, title):
|
|
2912
|
+
"""
|
|
2913
|
+
Set the title text of the window containing the figure.
|
|
2914
|
+
|
|
2915
|
+
Examples
|
|
2916
|
+
--------
|
|
2917
|
+
>>> fig = plt.figure()
|
|
2918
|
+
>>> fig.canvas.manager.set_window_title('My figure')
|
|
2919
|
+
"""
|
|
2920
|
+
# This attribute is not defined in __init__ (but __init__ calls this
|
|
2921
|
+
# setter), as derived classes (real GUI managers) will store this
|
|
2922
|
+
# information directly on the widget; only the base (non-GUI) manager
|
|
2923
|
+
# class needs a specific attribute for it (so that filename escaping
|
|
2924
|
+
# can be checked in the test suite).
|
|
2925
|
+
self._window_title = title
|
|
2926
|
+
|
|
2927
|
+
|
|
2928
|
+
cursors = tools.cursors
|
|
2929
|
+
|
|
2930
|
+
|
|
2931
|
+
class _Mode(str, Enum):
|
|
2932
|
+
NONE = ""
|
|
2933
|
+
PAN = "pan/zoom"
|
|
2934
|
+
ZOOM = "zoom rect"
|
|
2935
|
+
|
|
2936
|
+
def __str__(self):
|
|
2937
|
+
return self.value
|
|
2938
|
+
|
|
2939
|
+
|
|
2940
|
+
class NavigationToolbar2:
|
|
2941
|
+
"""
|
|
2942
|
+
Base class for the navigation cursor, version 2.
|
|
2943
|
+
|
|
2944
|
+
Backends must implement a canvas that handles connections for
|
|
2945
|
+
'button_press_event' and 'button_release_event'. See
|
|
2946
|
+
:meth:`FigureCanvasBase.mpl_connect` for more information.
|
|
2947
|
+
|
|
2948
|
+
They must also define
|
|
2949
|
+
|
|
2950
|
+
:meth:`save_figure`
|
|
2951
|
+
Save the current figure.
|
|
2952
|
+
|
|
2953
|
+
:meth:`draw_rubberband` (optional)
|
|
2954
|
+
Draw the zoom to rect "rubberband" rectangle.
|
|
2955
|
+
|
|
2956
|
+
:meth:`set_message` (optional)
|
|
2957
|
+
Display message.
|
|
2958
|
+
|
|
2959
|
+
:meth:`set_history_buttons` (optional)
|
|
2960
|
+
You can change the history back / forward buttons to indicate disabled / enabled
|
|
2961
|
+
state.
|
|
2962
|
+
|
|
2963
|
+
and override ``__init__`` to set up the toolbar -- without forgetting to
|
|
2964
|
+
call the base-class init. Typically, ``__init__`` needs to set up toolbar
|
|
2965
|
+
buttons connected to the `home`, `back`, `forward`, `pan`, `zoom`, and
|
|
2966
|
+
`save_figure` methods and using standard icons in the "images" subdirectory
|
|
2967
|
+
of the data path.
|
|
2968
|
+
|
|
2969
|
+
That's it, we'll do the rest!
|
|
2970
|
+
"""
|
|
2971
|
+
|
|
2972
|
+
# list of toolitems to add to the toolbar, format is:
|
|
2973
|
+
# (
|
|
2974
|
+
# text, # the text of the button (often not visible to users)
|
|
2975
|
+
# tooltip_text, # the tooltip shown on hover (where possible)
|
|
2976
|
+
# image_file, # name of the image for the button (without the extension)
|
|
2977
|
+
# name_of_method, # name of the method in NavigationToolbar2 to call
|
|
2978
|
+
# )
|
|
2979
|
+
toolitems = (
|
|
2980
|
+
('Home', 'Reset original view', 'home', 'home'),
|
|
2981
|
+
('Back', 'Back to previous view', 'back', 'back'),
|
|
2982
|
+
('Forward', 'Forward to next view', 'forward', 'forward'),
|
|
2983
|
+
(None, None, None, None),
|
|
2984
|
+
('Pan',
|
|
2985
|
+
'Left button pans, Right button zooms\n'
|
|
2986
|
+
'x/y fixes axis, CTRL fixes aspect',
|
|
2987
|
+
'move', 'pan'),
|
|
2988
|
+
('Zoom', 'Zoom to rectangle\nx/y fixes axis', 'zoom_to_rect', 'zoom'),
|
|
2989
|
+
('Subplots', 'Configure subplots', 'subplots', 'configure_subplots'),
|
|
2990
|
+
(None, None, None, None),
|
|
2991
|
+
('Save', 'Save the figure', 'filesave', 'save_figure'),
|
|
2992
|
+
)
|
|
2993
|
+
|
|
2994
|
+
UNKNOWN_SAVED_STATUS = object()
|
|
2995
|
+
|
|
2996
|
+
def __init__(self, canvas):
|
|
2997
|
+
self.canvas = canvas
|
|
2998
|
+
canvas.toolbar = self
|
|
2999
|
+
self._nav_stack = cbook._Stack()
|
|
3000
|
+
# This cursor will be set after the initial draw.
|
|
3001
|
+
self._last_cursor = tools.Cursors.POINTER
|
|
3002
|
+
|
|
3003
|
+
self._id_press = self.canvas.mpl_connect(
|
|
3004
|
+
'button_press_event', self._zoom_pan_handler)
|
|
3005
|
+
self._id_release = self.canvas.mpl_connect(
|
|
3006
|
+
'button_release_event', self._zoom_pan_handler)
|
|
3007
|
+
self._id_drag = self.canvas.mpl_connect(
|
|
3008
|
+
'motion_notify_event', self.mouse_move)
|
|
3009
|
+
self._pan_info = None
|
|
3010
|
+
self._zoom_info = None
|
|
3011
|
+
|
|
3012
|
+
self.mode = _Mode.NONE # a mode string for the status bar
|
|
3013
|
+
self.set_history_buttons()
|
|
3014
|
+
|
|
3015
|
+
def set_message(self, s):
|
|
3016
|
+
"""Display a message on toolbar or in status bar."""
|
|
3017
|
+
|
|
3018
|
+
def draw_rubberband(self, event, x0, y0, x1, y1):
|
|
3019
|
+
"""
|
|
3020
|
+
Draw a rectangle rubberband to indicate zoom limits.
|
|
3021
|
+
|
|
3022
|
+
Note that it is not guaranteed that ``x0 <= x1`` and ``y0 <= y1``.
|
|
3023
|
+
"""
|
|
3024
|
+
|
|
3025
|
+
def remove_rubberband(self):
|
|
3026
|
+
"""Remove the rubberband."""
|
|
3027
|
+
|
|
3028
|
+
def home(self, *args):
|
|
3029
|
+
"""
|
|
3030
|
+
Restore the original view.
|
|
3031
|
+
|
|
3032
|
+
For convenience of being directly connected as a GUI callback, which
|
|
3033
|
+
often get passed additional parameters, this method accepts arbitrary
|
|
3034
|
+
parameters, but does not use them.
|
|
3035
|
+
"""
|
|
3036
|
+
self._nav_stack.home()
|
|
3037
|
+
self.set_history_buttons()
|
|
3038
|
+
self._update_view()
|
|
3039
|
+
|
|
3040
|
+
def back(self, *args):
|
|
3041
|
+
"""
|
|
3042
|
+
Move back up the view lim stack.
|
|
3043
|
+
|
|
3044
|
+
For convenience of being directly connected as a GUI callback, which
|
|
3045
|
+
often get passed additional parameters, this method accepts arbitrary
|
|
3046
|
+
parameters, but does not use them.
|
|
3047
|
+
"""
|
|
3048
|
+
self._nav_stack.back()
|
|
3049
|
+
self.set_history_buttons()
|
|
3050
|
+
self._update_view()
|
|
3051
|
+
|
|
3052
|
+
def forward(self, *args):
|
|
3053
|
+
"""
|
|
3054
|
+
Move forward in the view lim stack.
|
|
3055
|
+
|
|
3056
|
+
For convenience of being directly connected as a GUI callback, which
|
|
3057
|
+
often get passed additional parameters, this method accepts arbitrary
|
|
3058
|
+
parameters, but does not use them.
|
|
3059
|
+
"""
|
|
3060
|
+
self._nav_stack.forward()
|
|
3061
|
+
self.set_history_buttons()
|
|
3062
|
+
self._update_view()
|
|
3063
|
+
|
|
3064
|
+
def _update_cursor(self, event):
|
|
3065
|
+
"""
|
|
3066
|
+
Update the cursor after a mouse move event or a tool (de)activation.
|
|
3067
|
+
"""
|
|
3068
|
+
if self.mode and event.inaxes and event.inaxes.get_navigate():
|
|
3069
|
+
if (self.mode == _Mode.ZOOM
|
|
3070
|
+
and self._last_cursor != tools.Cursors.SELECT_REGION):
|
|
3071
|
+
self.canvas.set_cursor(tools.Cursors.SELECT_REGION)
|
|
3072
|
+
self._last_cursor = tools.Cursors.SELECT_REGION
|
|
3073
|
+
elif (self.mode == _Mode.PAN
|
|
3074
|
+
and self._last_cursor != tools.Cursors.MOVE):
|
|
3075
|
+
self.canvas.set_cursor(tools.Cursors.MOVE)
|
|
3076
|
+
self._last_cursor = tools.Cursors.MOVE
|
|
3077
|
+
elif self._last_cursor != tools.Cursors.POINTER:
|
|
3078
|
+
self.canvas.set_cursor(tools.Cursors.POINTER)
|
|
3079
|
+
self._last_cursor = tools.Cursors.POINTER
|
|
3080
|
+
|
|
3081
|
+
@contextmanager
|
|
3082
|
+
def _wait_cursor_for_draw_cm(self):
|
|
3083
|
+
"""
|
|
3084
|
+
Set the cursor to a wait cursor when drawing the canvas.
|
|
3085
|
+
|
|
3086
|
+
In order to avoid constantly changing the cursor when the canvas
|
|
3087
|
+
changes frequently, do nothing if this context was triggered during the
|
|
3088
|
+
last second. (Optimally we'd prefer only setting the wait cursor if
|
|
3089
|
+
the *current* draw takes too long, but the current draw blocks the GUI
|
|
3090
|
+
thread).
|
|
3091
|
+
"""
|
|
3092
|
+
self._draw_time, last_draw_time = (
|
|
3093
|
+
time.time(), getattr(self, "_draw_time", -np.inf))
|
|
3094
|
+
if self._draw_time - last_draw_time > 1:
|
|
3095
|
+
try:
|
|
3096
|
+
self.canvas.set_cursor(tools.Cursors.WAIT)
|
|
3097
|
+
yield
|
|
3098
|
+
finally:
|
|
3099
|
+
self.canvas.set_cursor(self._last_cursor)
|
|
3100
|
+
else:
|
|
3101
|
+
yield
|
|
3102
|
+
|
|
3103
|
+
@staticmethod
|
|
3104
|
+
def _mouse_event_to_message(event):
|
|
3105
|
+
if event.inaxes and event.inaxes.get_navigate():
|
|
3106
|
+
try:
|
|
3107
|
+
s = event.inaxes.format_coord(event.xdata, event.ydata)
|
|
3108
|
+
except (ValueError, OverflowError):
|
|
3109
|
+
pass
|
|
3110
|
+
else:
|
|
3111
|
+
s = s.rstrip()
|
|
3112
|
+
artists = [a for a in event.inaxes._mouseover_set
|
|
3113
|
+
if a.contains(event)[0] and a.get_visible()]
|
|
3114
|
+
if artists:
|
|
3115
|
+
a = cbook._topmost_artist(artists)
|
|
3116
|
+
if a is not event.inaxes.patch:
|
|
3117
|
+
data = a.get_cursor_data(event)
|
|
3118
|
+
if data is not None:
|
|
3119
|
+
data_str = a.format_cursor_data(data).rstrip()
|
|
3120
|
+
if data_str:
|
|
3121
|
+
s = s + '\n' + data_str
|
|
3122
|
+
return s
|
|
3123
|
+
return ""
|
|
3124
|
+
|
|
3125
|
+
def mouse_move(self, event):
|
|
3126
|
+
self._update_cursor(event)
|
|
3127
|
+
self.set_message(self._mouse_event_to_message(event))
|
|
3128
|
+
|
|
3129
|
+
def _zoom_pan_handler(self, event):
|
|
3130
|
+
if self.mode == _Mode.PAN:
|
|
3131
|
+
if event.name == "button_press_event":
|
|
3132
|
+
self.press_pan(event)
|
|
3133
|
+
elif event.name == "button_release_event":
|
|
3134
|
+
self.release_pan(event)
|
|
3135
|
+
if self.mode == _Mode.ZOOM:
|
|
3136
|
+
if event.name == "button_press_event":
|
|
3137
|
+
self.press_zoom(event)
|
|
3138
|
+
elif event.name == "button_release_event":
|
|
3139
|
+
self.release_zoom(event)
|
|
3140
|
+
|
|
3141
|
+
def _start_event_axes_interaction(self, event, *, method):
|
|
3142
|
+
|
|
3143
|
+
def _ax_filter(ax):
|
|
3144
|
+
return (ax.in_axes(event) and
|
|
3145
|
+
ax.get_navigate() and
|
|
3146
|
+
getattr(ax, f"can_{method}")()
|
|
3147
|
+
)
|
|
3148
|
+
|
|
3149
|
+
def _capture_events(ax):
|
|
3150
|
+
f = ax.get_forward_navigation_events()
|
|
3151
|
+
if f == "auto": # (capture = patch visibility)
|
|
3152
|
+
f = not ax.patch.get_visible()
|
|
3153
|
+
return not f
|
|
3154
|
+
|
|
3155
|
+
# get all relevant axes for the event
|
|
3156
|
+
axes = list(filter(_ax_filter, self.canvas.figure.get_axes()))
|
|
3157
|
+
|
|
3158
|
+
if len(axes) == 0:
|
|
3159
|
+
return []
|
|
3160
|
+
|
|
3161
|
+
if self._nav_stack() is None:
|
|
3162
|
+
self.push_current() # Set the home button to this view.
|
|
3163
|
+
|
|
3164
|
+
# group axes by zorder (reverse to trigger later axes first)
|
|
3165
|
+
grps = dict()
|
|
3166
|
+
for ax in reversed(axes):
|
|
3167
|
+
grps.setdefault(ax.get_zorder(), []).append(ax)
|
|
3168
|
+
|
|
3169
|
+
axes_to_trigger = []
|
|
3170
|
+
# go through zorders in reverse until we hit a capturing axes
|
|
3171
|
+
for zorder in sorted(grps, reverse=True):
|
|
3172
|
+
for ax in grps[zorder]:
|
|
3173
|
+
axes_to_trigger.append(ax)
|
|
3174
|
+
# NOTE: shared axes are automatically triggered, but twin-axes not!
|
|
3175
|
+
axes_to_trigger.extend(ax._twinned_axes.get_siblings(ax))
|
|
3176
|
+
|
|
3177
|
+
if _capture_events(ax):
|
|
3178
|
+
break # break if we hit a capturing axes
|
|
3179
|
+
else:
|
|
3180
|
+
# If the inner loop finished without an explicit break,
|
|
3181
|
+
# (e.g. no capturing axes was found) continue the
|
|
3182
|
+
# outer loop to the next zorder.
|
|
3183
|
+
continue
|
|
3184
|
+
|
|
3185
|
+
# If the inner loop was terminated with an explicit break,
|
|
3186
|
+
# terminate the outer loop as well.
|
|
3187
|
+
break
|
|
3188
|
+
|
|
3189
|
+
# avoid duplicated triggers (but keep order of list)
|
|
3190
|
+
axes_to_trigger = list(dict.fromkeys(axes_to_trigger))
|
|
3191
|
+
|
|
3192
|
+
return axes_to_trigger
|
|
3193
|
+
|
|
3194
|
+
def pan(self, *args):
|
|
3195
|
+
"""
|
|
3196
|
+
Toggle the pan/zoom tool.
|
|
3197
|
+
|
|
3198
|
+
Pan with left button, zoom with right.
|
|
3199
|
+
"""
|
|
3200
|
+
if not self.canvas.widgetlock.available(self):
|
|
3201
|
+
self.set_message("pan unavailable")
|
|
3202
|
+
return
|
|
3203
|
+
if self.mode == _Mode.PAN:
|
|
3204
|
+
self.mode = _Mode.NONE
|
|
3205
|
+
self.canvas.widgetlock.release(self)
|
|
3206
|
+
else:
|
|
3207
|
+
self.mode = _Mode.PAN
|
|
3208
|
+
self.canvas.widgetlock(self)
|
|
3209
|
+
|
|
3210
|
+
_PanInfo = namedtuple("_PanInfo", "button axes cid")
|
|
3211
|
+
|
|
3212
|
+
def press_pan(self, event):
|
|
3213
|
+
"""Callback for mouse button press in pan/zoom mode."""
|
|
3214
|
+
if (event.button not in [MouseButton.LEFT, MouseButton.RIGHT]
|
|
3215
|
+
or event.x is None or event.y is None):
|
|
3216
|
+
return
|
|
3217
|
+
|
|
3218
|
+
axes = self._start_event_axes_interaction(event, method="pan")
|
|
3219
|
+
if not axes:
|
|
3220
|
+
return
|
|
3221
|
+
|
|
3222
|
+
# call "ax.start_pan(..)" on all relevant axes of an event
|
|
3223
|
+
for ax in axes:
|
|
3224
|
+
ax.start_pan(event.x, event.y, event.button)
|
|
3225
|
+
|
|
3226
|
+
self.canvas.mpl_disconnect(self._id_drag)
|
|
3227
|
+
id_drag = self.canvas.mpl_connect("motion_notify_event", self.drag_pan)
|
|
3228
|
+
|
|
3229
|
+
self._pan_info = self._PanInfo(
|
|
3230
|
+
button=event.button, axes=axes, cid=id_drag)
|
|
3231
|
+
|
|
3232
|
+
def drag_pan(self, event):
|
|
3233
|
+
"""Callback for dragging in pan/zoom mode."""
|
|
3234
|
+
if event.buttons != {self._pan_info.button}:
|
|
3235
|
+
# Zoom ended while canvas not in focus (it did not receive a
|
|
3236
|
+
# button_release_event); cancel it.
|
|
3237
|
+
self.release_pan(None) # release_pan doesn't actually use event.
|
|
3238
|
+
return
|
|
3239
|
+
for ax in self._pan_info.axes:
|
|
3240
|
+
# Using the recorded button at the press is safer than the current
|
|
3241
|
+
# button, as multiple buttons can get pressed during motion.
|
|
3242
|
+
ax.drag_pan(self._pan_info.button, event.key, event.x, event.y)
|
|
3243
|
+
self.canvas.draw_idle()
|
|
3244
|
+
|
|
3245
|
+
def release_pan(self, event):
|
|
3246
|
+
"""Callback for mouse button release in pan/zoom mode."""
|
|
3247
|
+
if self._pan_info is None:
|
|
3248
|
+
return
|
|
3249
|
+
self.canvas.mpl_disconnect(self._pan_info.cid)
|
|
3250
|
+
self._id_drag = self.canvas.mpl_connect(
|
|
3251
|
+
'motion_notify_event', self.mouse_move)
|
|
3252
|
+
for ax in self._pan_info.axes:
|
|
3253
|
+
ax.end_pan()
|
|
3254
|
+
self.canvas.draw_idle()
|
|
3255
|
+
self._pan_info = None
|
|
3256
|
+
self.push_current()
|
|
3257
|
+
|
|
3258
|
+
def zoom(self, *args):
|
|
3259
|
+
if not self.canvas.widgetlock.available(self):
|
|
3260
|
+
self.set_message("zoom unavailable")
|
|
3261
|
+
return
|
|
3262
|
+
"""Toggle zoom to rect mode."""
|
|
3263
|
+
if self.mode == _Mode.ZOOM:
|
|
3264
|
+
self.mode = _Mode.NONE
|
|
3265
|
+
self.canvas.widgetlock.release(self)
|
|
3266
|
+
else:
|
|
3267
|
+
self.mode = _Mode.ZOOM
|
|
3268
|
+
self.canvas.widgetlock(self)
|
|
3269
|
+
|
|
3270
|
+
_ZoomInfo = namedtuple("_ZoomInfo", "button start_xy axes cid cbar")
|
|
3271
|
+
|
|
3272
|
+
def press_zoom(self, event):
|
|
3273
|
+
"""Callback for mouse button press in zoom to rect mode."""
|
|
3274
|
+
if (event.button not in [MouseButton.LEFT, MouseButton.RIGHT]
|
|
3275
|
+
or event.x is None or event.y is None):
|
|
3276
|
+
return
|
|
3277
|
+
|
|
3278
|
+
axes = self._start_event_axes_interaction(event, method="zoom")
|
|
3279
|
+
if not axes:
|
|
3280
|
+
return
|
|
3281
|
+
|
|
3282
|
+
id_zoom = self.canvas.mpl_connect(
|
|
3283
|
+
"motion_notify_event", self.drag_zoom)
|
|
3284
|
+
|
|
3285
|
+
# A colorbar is one-dimensional, so we extend the zoom rectangle out
|
|
3286
|
+
# to the edge of the Axes bbox in the other dimension. To do that we
|
|
3287
|
+
# store the orientation of the colorbar for later.
|
|
3288
|
+
parent_ax = axes[0]
|
|
3289
|
+
if hasattr(parent_ax, "_colorbar"):
|
|
3290
|
+
cbar = parent_ax._colorbar.orientation
|
|
3291
|
+
else:
|
|
3292
|
+
cbar = None
|
|
3293
|
+
|
|
3294
|
+
self._zoom_info = self._ZoomInfo(
|
|
3295
|
+
button=event.button, start_xy=(event.x, event.y), axes=axes,
|
|
3296
|
+
cid=id_zoom, cbar=cbar)
|
|
3297
|
+
|
|
3298
|
+
def drag_zoom(self, event):
|
|
3299
|
+
"""Callback for dragging in zoom mode."""
|
|
3300
|
+
if event.buttons != {self._zoom_info.button}:
|
|
3301
|
+
# Zoom ended while canvas not in focus (it did not receive a
|
|
3302
|
+
# button_release_event); cancel it.
|
|
3303
|
+
self._cleanup_post_zoom()
|
|
3304
|
+
return
|
|
3305
|
+
|
|
3306
|
+
start_xy = self._zoom_info.start_xy
|
|
3307
|
+
ax = self._zoom_info.axes[0]
|
|
3308
|
+
(x1, y1), (x2, y2) = np.clip(
|
|
3309
|
+
[start_xy, [event.x, event.y]], ax.bbox.min, ax.bbox.max)
|
|
3310
|
+
key = event.key
|
|
3311
|
+
# Force the key on colorbars to extend the short-axis bbox
|
|
3312
|
+
if self._zoom_info.cbar == "horizontal":
|
|
3313
|
+
key = "x"
|
|
3314
|
+
elif self._zoom_info.cbar == "vertical":
|
|
3315
|
+
key = "y"
|
|
3316
|
+
if key == "x":
|
|
3317
|
+
y1, y2 = ax.bbox.intervaly
|
|
3318
|
+
elif key == "y":
|
|
3319
|
+
x1, x2 = ax.bbox.intervalx
|
|
3320
|
+
|
|
3321
|
+
self.draw_rubberband(event, x1, y1, x2, y2)
|
|
3322
|
+
|
|
3323
|
+
def release_zoom(self, event):
|
|
3324
|
+
"""Callback for mouse button release in zoom to rect mode."""
|
|
3325
|
+
if self._zoom_info is None:
|
|
3326
|
+
return
|
|
3327
|
+
|
|
3328
|
+
# We don't check the event button here, so that zooms can be cancelled
|
|
3329
|
+
# by (pressing and) releasing another mouse button.
|
|
3330
|
+
self.canvas.mpl_disconnect(self._zoom_info.cid)
|
|
3331
|
+
self.remove_rubberband()
|
|
3332
|
+
|
|
3333
|
+
start_x, start_y = self._zoom_info.start_xy
|
|
3334
|
+
direction = "in" if self._zoom_info.button == 1 else "out"
|
|
3335
|
+
key = event.key
|
|
3336
|
+
# Force the key on colorbars to ignore the zoom-cancel on the
|
|
3337
|
+
# short-axis side
|
|
3338
|
+
if self._zoom_info.cbar == "horizontal":
|
|
3339
|
+
key = "x"
|
|
3340
|
+
elif self._zoom_info.cbar == "vertical":
|
|
3341
|
+
key = "y"
|
|
3342
|
+
# Ignore single clicks: 5 pixels is a threshold that allows the user to
|
|
3343
|
+
# "cancel" a zoom action by zooming by less than 5 pixels.
|
|
3344
|
+
if ((abs(event.x - start_x) < 5 and key != "y") or
|
|
3345
|
+
(abs(event.y - start_y) < 5 and key != "x")):
|
|
3346
|
+
self._cleanup_post_zoom()
|
|
3347
|
+
return
|
|
3348
|
+
|
|
3349
|
+
for i, ax in enumerate(self._zoom_info.axes):
|
|
3350
|
+
# Detect whether this Axes is twinned with an earlier Axes in the
|
|
3351
|
+
# list of zoomed Axes, to avoid double zooming.
|
|
3352
|
+
twinx = any(ax.get_shared_x_axes().joined(ax, prev)
|
|
3353
|
+
for prev in self._zoom_info.axes[:i])
|
|
3354
|
+
twiny = any(ax.get_shared_y_axes().joined(ax, prev)
|
|
3355
|
+
for prev in self._zoom_info.axes[:i])
|
|
3356
|
+
ax._set_view_from_bbox(
|
|
3357
|
+
(start_x, start_y, event.x, event.y),
|
|
3358
|
+
direction, key, twinx, twiny)
|
|
3359
|
+
|
|
3360
|
+
self._cleanup_post_zoom()
|
|
3361
|
+
self.push_current()
|
|
3362
|
+
|
|
3363
|
+
def _cleanup_post_zoom(self):
|
|
3364
|
+
# We don't check the event button here, so that zooms can be cancelled
|
|
3365
|
+
# by (pressing and) releasing another mouse button.
|
|
3366
|
+
self.canvas.mpl_disconnect(self._zoom_info.cid)
|
|
3367
|
+
self.remove_rubberband()
|
|
3368
|
+
self.canvas.draw_idle()
|
|
3369
|
+
self._zoom_info = None
|
|
3370
|
+
|
|
3371
|
+
def push_current(self):
|
|
3372
|
+
"""Push the current view limits and position onto the stack."""
|
|
3373
|
+
self._nav_stack.push(
|
|
3374
|
+
WeakKeyDictionary(
|
|
3375
|
+
{ax: (ax._get_view(),
|
|
3376
|
+
# Store both the original and modified positions.
|
|
3377
|
+
(ax.get_position(True).frozen(),
|
|
3378
|
+
ax.get_position().frozen()))
|
|
3379
|
+
for ax in self.canvas.figure.axes}))
|
|
3380
|
+
self.set_history_buttons()
|
|
3381
|
+
|
|
3382
|
+
def _update_view(self):
|
|
3383
|
+
"""
|
|
3384
|
+
Update the viewlim and position from the view and position stack for
|
|
3385
|
+
each Axes.
|
|
3386
|
+
"""
|
|
3387
|
+
nav_info = self._nav_stack()
|
|
3388
|
+
if nav_info is None:
|
|
3389
|
+
return
|
|
3390
|
+
# Retrieve all items at once to avoid any risk of GC deleting an Axes
|
|
3391
|
+
# while in the middle of the loop below.
|
|
3392
|
+
items = list(nav_info.items())
|
|
3393
|
+
for ax, (view, (pos_orig, pos_active)) in items:
|
|
3394
|
+
ax._set_view(view)
|
|
3395
|
+
# Restore both the original and modified positions
|
|
3396
|
+
ax._set_position(pos_orig, 'original')
|
|
3397
|
+
ax._set_position(pos_active, 'active')
|
|
3398
|
+
self.canvas.draw_idle()
|
|
3399
|
+
|
|
3400
|
+
def configure_subplots(self, *args):
|
|
3401
|
+
if hasattr(self, "subplot_tool"):
|
|
3402
|
+
self.subplot_tool.figure.canvas.manager.show()
|
|
3403
|
+
return self.subplot_tool
|
|
3404
|
+
# This import needs to happen here due to circular imports.
|
|
3405
|
+
from matplotlib_rs.figure import Figure
|
|
3406
|
+
with mpl.rc_context({"toolbar": "none"}): # No navbar for the toolfig.
|
|
3407
|
+
manager = type(self.canvas).new_manager(Figure(figsize=(6, 3)), -1)
|
|
3408
|
+
manager.set_window_title("Subplot configuration tool")
|
|
3409
|
+
tool_fig = manager.canvas.figure
|
|
3410
|
+
tool_fig.subplots_adjust(top=0.9)
|
|
3411
|
+
self.subplot_tool = widgets.SubplotTool(self.canvas.figure, tool_fig)
|
|
3412
|
+
cid = self.canvas.mpl_connect(
|
|
3413
|
+
"close_event", lambda e: manager.destroy())
|
|
3414
|
+
|
|
3415
|
+
def on_tool_fig_close(e):
|
|
3416
|
+
self.canvas.mpl_disconnect(cid)
|
|
3417
|
+
del self.subplot_tool
|
|
3418
|
+
|
|
3419
|
+
tool_fig.canvas.mpl_connect("close_event", on_tool_fig_close)
|
|
3420
|
+
manager.show()
|
|
3421
|
+
return self.subplot_tool
|
|
3422
|
+
|
|
3423
|
+
def save_figure(self, *args):
|
|
3424
|
+
"""
|
|
3425
|
+
Save the current figure.
|
|
3426
|
+
|
|
3427
|
+
Backend implementations may choose to return
|
|
3428
|
+
the absolute path of the saved file, if any, as
|
|
3429
|
+
a string.
|
|
3430
|
+
|
|
3431
|
+
If no file is created then `None` is returned.
|
|
3432
|
+
|
|
3433
|
+
If the backend does not implement this functionality
|
|
3434
|
+
then `NavigationToolbar2.UNKNOWN_SAVED_STATUS` is returned.
|
|
3435
|
+
|
|
3436
|
+
Returns
|
|
3437
|
+
-------
|
|
3438
|
+
str or `NavigationToolbar2.UNKNOWN_SAVED_STATUS` or `None`
|
|
3439
|
+
The filepath of the saved figure.
|
|
3440
|
+
Returns `None` if figure is not saved.
|
|
3441
|
+
Returns `NavigationToolbar2.UNKNOWN_SAVED_STATUS` when
|
|
3442
|
+
the backend does not provide the information.
|
|
3443
|
+
"""
|
|
3444
|
+
raise NotImplementedError
|
|
3445
|
+
|
|
3446
|
+
def update(self):
|
|
3447
|
+
"""Reset the Axes stack."""
|
|
3448
|
+
self._nav_stack.clear()
|
|
3449
|
+
self.set_history_buttons()
|
|
3450
|
+
|
|
3451
|
+
def set_history_buttons(self):
|
|
3452
|
+
"""Enable or disable the back/forward button."""
|
|
3453
|
+
|
|
3454
|
+
|
|
3455
|
+
class ToolContainerBase:
|
|
3456
|
+
"""
|
|
3457
|
+
Base class for all tool containers, e.g. toolbars.
|
|
3458
|
+
|
|
3459
|
+
Attributes
|
|
3460
|
+
----------
|
|
3461
|
+
toolmanager : `.ToolManager`
|
|
3462
|
+
The tools with which this `ToolContainerBase` wants to communicate.
|
|
3463
|
+
"""
|
|
3464
|
+
|
|
3465
|
+
_icon_extension = '.png'
|
|
3466
|
+
"""
|
|
3467
|
+
Toolcontainer button icon image format extension
|
|
3468
|
+
|
|
3469
|
+
**String**: Image extension
|
|
3470
|
+
"""
|
|
3471
|
+
|
|
3472
|
+
def __init__(self, toolmanager):
|
|
3473
|
+
self.toolmanager = toolmanager
|
|
3474
|
+
toolmanager.toolmanager_connect(
|
|
3475
|
+
'tool_message_event',
|
|
3476
|
+
lambda event: self.set_message(event.message))
|
|
3477
|
+
toolmanager.toolmanager_connect(
|
|
3478
|
+
'tool_removed_event',
|
|
3479
|
+
lambda event: self.remove_toolitem(event.tool.name))
|
|
3480
|
+
|
|
3481
|
+
def _tool_toggled_cbk(self, event):
|
|
3482
|
+
"""
|
|
3483
|
+
Capture the 'tool_trigger_[name]'
|
|
3484
|
+
|
|
3485
|
+
This only gets used for toggled tools.
|
|
3486
|
+
"""
|
|
3487
|
+
self.toggle_toolitem(event.tool.name, event.tool.toggled)
|
|
3488
|
+
|
|
3489
|
+
def add_tool(self, tool, group, position=-1):
|
|
3490
|
+
"""
|
|
3491
|
+
Add a tool to this container.
|
|
3492
|
+
|
|
3493
|
+
Parameters
|
|
3494
|
+
----------
|
|
3495
|
+
tool : tool_like
|
|
3496
|
+
The tool to add, see `.ToolManager.get_tool`.
|
|
3497
|
+
group : str
|
|
3498
|
+
The name of the group to add this tool to.
|
|
3499
|
+
position : int, default: -1
|
|
3500
|
+
The position within the group to place this tool.
|
|
3501
|
+
"""
|
|
3502
|
+
tool = self.toolmanager.get_tool(tool)
|
|
3503
|
+
image = self._get_image_filename(tool)
|
|
3504
|
+
toggle = getattr(tool, 'toggled', None) is not None
|
|
3505
|
+
self.add_toolitem(tool.name, group, position,
|
|
3506
|
+
image, tool.description, toggle)
|
|
3507
|
+
if toggle:
|
|
3508
|
+
self.toolmanager.toolmanager_connect('tool_trigger_%s' % tool.name,
|
|
3509
|
+
self._tool_toggled_cbk)
|
|
3510
|
+
# If initially toggled
|
|
3511
|
+
if tool.toggled:
|
|
3512
|
+
self.toggle_toolitem(tool.name, True)
|
|
3513
|
+
|
|
3514
|
+
def _get_image_filename(self, tool):
|
|
3515
|
+
"""Resolve a tool icon's filename."""
|
|
3516
|
+
if not tool.image:
|
|
3517
|
+
return None
|
|
3518
|
+
if os.path.isabs(tool.image):
|
|
3519
|
+
filename = tool.image
|
|
3520
|
+
else:
|
|
3521
|
+
if "image" in getattr(tool, "__dict__", {}):
|
|
3522
|
+
raise ValueError("If 'tool.image' is an instance variable, "
|
|
3523
|
+
"it must be an absolute path")
|
|
3524
|
+
for cls in type(tool).__mro__:
|
|
3525
|
+
if "image" in vars(cls):
|
|
3526
|
+
try:
|
|
3527
|
+
src = inspect.getfile(cls)
|
|
3528
|
+
break
|
|
3529
|
+
except (OSError, TypeError):
|
|
3530
|
+
raise ValueError("Failed to locate source file "
|
|
3531
|
+
"where 'tool.image' is defined") from None
|
|
3532
|
+
else:
|
|
3533
|
+
raise ValueError("Failed to find parent class defining 'tool.image'")
|
|
3534
|
+
filename = str(pathlib.Path(src).parent / tool.image)
|
|
3535
|
+
for filename in [filename, filename + self._icon_extension]:
|
|
3536
|
+
if os.path.isfile(filename):
|
|
3537
|
+
return os.path.abspath(filename)
|
|
3538
|
+
|
|
3539
|
+
def trigger_tool(self, name):
|
|
3540
|
+
"""
|
|
3541
|
+
Trigger the tool.
|
|
3542
|
+
|
|
3543
|
+
Parameters
|
|
3544
|
+
----------
|
|
3545
|
+
name : str
|
|
3546
|
+
Name (id) of the tool triggered from within the container.
|
|
3547
|
+
"""
|
|
3548
|
+
self.toolmanager.trigger_tool(name, sender=self)
|
|
3549
|
+
|
|
3550
|
+
def add_toolitem(self, name, group, position, image, description, toggle):
|
|
3551
|
+
"""
|
|
3552
|
+
A hook to add a toolitem to the container.
|
|
3553
|
+
|
|
3554
|
+
This hook must be implemented in each backend and contains the
|
|
3555
|
+
backend-specific code to add an element to the toolbar.
|
|
3556
|
+
|
|
3557
|
+
.. warning::
|
|
3558
|
+
This is part of the backend implementation and should
|
|
3559
|
+
not be called by end-users. They should instead call
|
|
3560
|
+
`.ToolContainerBase.add_tool`.
|
|
3561
|
+
|
|
3562
|
+
The callback associated with the button click event
|
|
3563
|
+
must be *exactly* ``self.trigger_tool(name)``.
|
|
3564
|
+
|
|
3565
|
+
Parameters
|
|
3566
|
+
----------
|
|
3567
|
+
name : str
|
|
3568
|
+
Name of the tool to add, this gets used as the tool's ID and as the
|
|
3569
|
+
default label of the buttons.
|
|
3570
|
+
group : str
|
|
3571
|
+
Name of the group that this tool belongs to.
|
|
3572
|
+
position : int
|
|
3573
|
+
Position of the tool within its group, if -1 it goes at the end.
|
|
3574
|
+
image : str
|
|
3575
|
+
Filename of the image for the button or `None`.
|
|
3576
|
+
description : str
|
|
3577
|
+
Description of the tool, used for the tooltips.
|
|
3578
|
+
toggle : bool
|
|
3579
|
+
* `True` : The button is a toggle (change the pressed/unpressed
|
|
3580
|
+
state between consecutive clicks).
|
|
3581
|
+
* `False` : The button is a normal button (returns to unpressed
|
|
3582
|
+
state after release).
|
|
3583
|
+
"""
|
|
3584
|
+
raise NotImplementedError
|
|
3585
|
+
|
|
3586
|
+
def toggle_toolitem(self, name, toggled):
|
|
3587
|
+
"""
|
|
3588
|
+
A hook to toggle a toolitem without firing an event.
|
|
3589
|
+
|
|
3590
|
+
This hook must be implemented in each backend and contains the
|
|
3591
|
+
backend-specific code to silently toggle a toolbar element.
|
|
3592
|
+
|
|
3593
|
+
.. warning::
|
|
3594
|
+
This is part of the backend implementation and should
|
|
3595
|
+
not be called by end-users. They should instead call
|
|
3596
|
+
`.ToolManager.trigger_tool` or `.ToolContainerBase.trigger_tool`
|
|
3597
|
+
(which are equivalent).
|
|
3598
|
+
|
|
3599
|
+
Parameters
|
|
3600
|
+
----------
|
|
3601
|
+
name : str
|
|
3602
|
+
Id of the tool to toggle.
|
|
3603
|
+
toggled : bool
|
|
3604
|
+
Whether to set this tool as toggled or not.
|
|
3605
|
+
"""
|
|
3606
|
+
raise NotImplementedError
|
|
3607
|
+
|
|
3608
|
+
def remove_toolitem(self, name):
|
|
3609
|
+
"""
|
|
3610
|
+
A hook to remove a toolitem from the container.
|
|
3611
|
+
|
|
3612
|
+
This hook must be implemented in each backend and contains the
|
|
3613
|
+
backend-specific code to remove an element from the toolbar; it is
|
|
3614
|
+
called when `.ToolManager` emits a ``tool_removed_event``.
|
|
3615
|
+
|
|
3616
|
+
Because some tools are present only on the `.ToolManager` but not on
|
|
3617
|
+
the `ToolContainerBase`, this method must be a no-op when called on a tool
|
|
3618
|
+
absent from the container.
|
|
3619
|
+
|
|
3620
|
+
.. warning::
|
|
3621
|
+
This is part of the backend implementation and should
|
|
3622
|
+
not be called by end-users. They should instead call
|
|
3623
|
+
`.ToolManager.remove_tool`.
|
|
3624
|
+
|
|
3625
|
+
Parameters
|
|
3626
|
+
----------
|
|
3627
|
+
name : str
|
|
3628
|
+
Name of the tool to remove.
|
|
3629
|
+
"""
|
|
3630
|
+
raise NotImplementedError
|
|
3631
|
+
|
|
3632
|
+
def set_message(self, s):
|
|
3633
|
+
"""
|
|
3634
|
+
Display a message on the toolbar.
|
|
3635
|
+
|
|
3636
|
+
Parameters
|
|
3637
|
+
----------
|
|
3638
|
+
s : str
|
|
3639
|
+
Message text.
|
|
3640
|
+
"""
|
|
3641
|
+
raise NotImplementedError
|
|
3642
|
+
|
|
3643
|
+
|
|
3644
|
+
class _Backend:
|
|
3645
|
+
# A backend can be defined by using the following pattern:
|
|
3646
|
+
#
|
|
3647
|
+
# @_Backend.export
|
|
3648
|
+
# class FooBackend(_Backend):
|
|
3649
|
+
# # override the attributes and methods documented below.
|
|
3650
|
+
|
|
3651
|
+
# `backend_version` may be overridden by the subclass.
|
|
3652
|
+
backend_version = "unknown"
|
|
3653
|
+
|
|
3654
|
+
# The `FigureCanvas` class must be defined.
|
|
3655
|
+
FigureCanvas = None
|
|
3656
|
+
|
|
3657
|
+
# For interactive backends, the `FigureManager` class must be overridden.
|
|
3658
|
+
FigureManager = FigureManagerBase
|
|
3659
|
+
|
|
3660
|
+
# For interactive backends, `mainloop` should be a function taking no
|
|
3661
|
+
# argument and starting the backend main loop. It should be left as None
|
|
3662
|
+
# for non-interactive backends.
|
|
3663
|
+
mainloop = None
|
|
3664
|
+
|
|
3665
|
+
# The following methods will be automatically defined and exported, but
|
|
3666
|
+
# can be overridden.
|
|
3667
|
+
|
|
3668
|
+
@classmethod
|
|
3669
|
+
def new_figure_manager(cls, num, *args, **kwargs):
|
|
3670
|
+
"""Create a new figure manager instance."""
|
|
3671
|
+
# This import needs to happen here due to circular imports.
|
|
3672
|
+
from matplotlib_rs.figure import Figure
|
|
3673
|
+
fig_cls = kwargs.pop('FigureClass', Figure)
|
|
3674
|
+
fig = fig_cls(*args, **kwargs)
|
|
3675
|
+
return cls.new_figure_manager_given_figure(num, fig)
|
|
3676
|
+
|
|
3677
|
+
@classmethod
|
|
3678
|
+
def new_figure_manager_given_figure(cls, num, figure):
|
|
3679
|
+
"""Create a new figure manager instance for the given figure."""
|
|
3680
|
+
return cls.FigureCanvas.new_manager(figure, num)
|
|
3681
|
+
|
|
3682
|
+
@classmethod
|
|
3683
|
+
def draw_if_interactive(cls):
|
|
3684
|
+
manager_class = cls.FigureCanvas.manager_class
|
|
3685
|
+
# Interactive backends reimplement start_main_loop or pyplot_show.
|
|
3686
|
+
backend_is_interactive = (
|
|
3687
|
+
manager_class.start_main_loop != FigureManagerBase.start_main_loop
|
|
3688
|
+
or manager_class.pyplot_show != FigureManagerBase.pyplot_show)
|
|
3689
|
+
if backend_is_interactive and is_interactive():
|
|
3690
|
+
manager = Gcf.get_active()
|
|
3691
|
+
if manager:
|
|
3692
|
+
manager.canvas.draw_idle()
|
|
3693
|
+
|
|
3694
|
+
@classmethod
|
|
3695
|
+
def show(cls, *, block=None):
|
|
3696
|
+
"""
|
|
3697
|
+
Show all figures.
|
|
3698
|
+
|
|
3699
|
+
`show` blocks by calling `mainloop` if *block* is ``True``, or if it is
|
|
3700
|
+
``None`` and we are not in `interactive` mode and if IPython's
|
|
3701
|
+
``%matplotlib`` integration has not been activated.
|
|
3702
|
+
"""
|
|
3703
|
+
managers = Gcf.get_all_fig_managers()
|
|
3704
|
+
if not managers:
|
|
3705
|
+
return
|
|
3706
|
+
for manager in managers:
|
|
3707
|
+
try:
|
|
3708
|
+
manager.show() # Emits a warning for non-interactive backend.
|
|
3709
|
+
except NonGuiException as exc:
|
|
3710
|
+
_api.warn_external(str(exc))
|
|
3711
|
+
if cls.mainloop is None:
|
|
3712
|
+
return
|
|
3713
|
+
if block is None:
|
|
3714
|
+
# Hack: Is IPython's %matplotlib integration activated? If so,
|
|
3715
|
+
# IPython's activate_matplotlib (>= 0.10) tacks a _needmain
|
|
3716
|
+
# attribute onto pyplot.show (always set to False).
|
|
3717
|
+
pyplot_show = getattr(sys.modules.get("matplotlib_rs.pyplot"), "show", None)
|
|
3718
|
+
ipython_pylab = hasattr(pyplot_show, "_needmain")
|
|
3719
|
+
block = not ipython_pylab and not is_interactive()
|
|
3720
|
+
if block:
|
|
3721
|
+
cls.mainloop()
|
|
3722
|
+
|
|
3723
|
+
# This method is the one actually exporting the required methods.
|
|
3724
|
+
|
|
3725
|
+
@staticmethod
|
|
3726
|
+
def export(cls):
|
|
3727
|
+
for name in [
|
|
3728
|
+
"backend_version",
|
|
3729
|
+
"FigureCanvas",
|
|
3730
|
+
"FigureManager",
|
|
3731
|
+
"new_figure_manager",
|
|
3732
|
+
"new_figure_manager_given_figure",
|
|
3733
|
+
"draw_if_interactive",
|
|
3734
|
+
"show",
|
|
3735
|
+
]:
|
|
3736
|
+
setattr(sys.modules[cls.__module__], name, getattr(cls, name))
|
|
3737
|
+
|
|
3738
|
+
# For back-compatibility, generate a shim `Show` class.
|
|
3739
|
+
|
|
3740
|
+
class Show(ShowBase):
|
|
3741
|
+
def mainloop(self):
|
|
3742
|
+
return cls.mainloop()
|
|
3743
|
+
|
|
3744
|
+
setattr(sys.modules[cls.__module__], "Show", Show)
|
|
3745
|
+
return cls
|
|
3746
|
+
|
|
3747
|
+
|
|
3748
|
+
class ShowBase(_Backend):
|
|
3749
|
+
"""
|
|
3750
|
+
Simple base class to generate a ``show()`` function in backends.
|
|
3751
|
+
|
|
3752
|
+
Subclass must override ``mainloop()`` method.
|
|
3753
|
+
"""
|
|
3754
|
+
|
|
3755
|
+
def __call__(self, block=None):
|
|
3756
|
+
return self.show(block=block)
|
|
3757
|
+
|
|
3758
|
+
|
|
3759
|
+
_default_backends = {k: v.replace('matplotlib.', 'matplotlib_rs.', 1)
|
|
3760
|
+
for k, v in _default_backends.items()}
|