matplotlib-rs 0.0.8__cp315-cp315-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.cp315-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
matplotlib_rs/colors.py
ADDED
|
@@ -0,0 +1,4278 @@
|
|
|
1
|
+
# Vendored from matplotlib 3.11 (see licenses/LICENSE_MATPLOTLIB), adapted for matplotlib_rs.
|
|
2
|
+
"""
|
|
3
|
+
A module for converting numbers or color arguments to *RGB* or *RGBA*.
|
|
4
|
+
|
|
5
|
+
*RGB* and *RGBA* are sequences of, respectively, 3 or 4 floats in the
|
|
6
|
+
range 0-1.
|
|
7
|
+
|
|
8
|
+
This module includes functions and classes for color specification conversions,
|
|
9
|
+
and for mapping numbers to colors in a 1-D array of colors called a colormap.
|
|
10
|
+
|
|
11
|
+
Mapping data onto colors using a colormap typically involves two steps: a data
|
|
12
|
+
array is first mapped onto the range 0-1 using a subclass of `Normalize`,
|
|
13
|
+
then this number is mapped to a color using a subclass of `Colormap`. Two
|
|
14
|
+
subclasses of `Colormap` provided here: `LinearSegmentedColormap`, which uses
|
|
15
|
+
piecewise-linear interpolation to define colormaps, and `ListedColormap`, which
|
|
16
|
+
makes a colormap from a list of colors.
|
|
17
|
+
|
|
18
|
+
.. seealso::
|
|
19
|
+
|
|
20
|
+
:ref:`colormap-manipulation` for examples of how to
|
|
21
|
+
make colormaps and
|
|
22
|
+
|
|
23
|
+
:ref:`colormaps` for a list of built-in colormaps.
|
|
24
|
+
|
|
25
|
+
:ref:`colormapnorms` for more details about data
|
|
26
|
+
normalization
|
|
27
|
+
|
|
28
|
+
More colormaps are available at palettable_.
|
|
29
|
+
|
|
30
|
+
The module also provides functions for checking whether an object can be
|
|
31
|
+
interpreted as a color (`is_color_like`), for converting such an object
|
|
32
|
+
to an RGBA tuple (`to_rgba`) or to an HTML-like hex string in the
|
|
33
|
+
"#rrggbb" format (`to_hex`), and a sequence of colors to an (n, 4)
|
|
34
|
+
RGBA array (`to_rgba_array`). Caching is used for efficiency.
|
|
35
|
+
|
|
36
|
+
Colors that Matplotlib recognizes are listed at
|
|
37
|
+
:ref:`colors_def`.
|
|
38
|
+
|
|
39
|
+
.. _palettable: https://jiffyclub.github.io/palettable/
|
|
40
|
+
.. _xkcd color survey: https://xkcd.com/color/rgb/
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
import base64
|
|
44
|
+
from collections.abc import Sequence, Mapping
|
|
45
|
+
from abc import ABC, abstractmethod
|
|
46
|
+
import functools
|
|
47
|
+
import importlib
|
|
48
|
+
import inspect
|
|
49
|
+
import io
|
|
50
|
+
import itertools
|
|
51
|
+
from numbers import Real
|
|
52
|
+
import re
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
import matplotlib_rs as mpl
|
|
56
|
+
import numpy as np
|
|
57
|
+
from . import _api, _cm, _colormap, cbook, scale
|
|
58
|
+
from ._color_data import BASE_COLORS, TABLEAU_COLORS, CSS4_COLORS, XKCD_COLORS
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class _ColorMapping(dict):
|
|
62
|
+
def __init__(self, mapping):
|
|
63
|
+
super().__init__(mapping)
|
|
64
|
+
self.cache = {}
|
|
65
|
+
|
|
66
|
+
def __setitem__(self, key, value):
|
|
67
|
+
super().__setitem__(key, value)
|
|
68
|
+
self.cache.clear()
|
|
69
|
+
|
|
70
|
+
def __delitem__(self, key):
|
|
71
|
+
super().__delitem__(key)
|
|
72
|
+
self.cache.clear()
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
_colors_full_map = {}
|
|
76
|
+
# Set by reverse priority order.
|
|
77
|
+
_colors_full_map.update(XKCD_COLORS)
|
|
78
|
+
_colors_full_map.update({k.replace('grey', 'gray'): v
|
|
79
|
+
for k, v in XKCD_COLORS.items()
|
|
80
|
+
if 'grey' in k})
|
|
81
|
+
_colors_full_map.update(CSS4_COLORS)
|
|
82
|
+
_colors_full_map.update(TABLEAU_COLORS)
|
|
83
|
+
_colors_full_map.update({k.replace('gray', 'grey'): v
|
|
84
|
+
for k, v in TABLEAU_COLORS.items()
|
|
85
|
+
if 'gray' in k})
|
|
86
|
+
_colors_full_map.update(BASE_COLORS)
|
|
87
|
+
_colors_full_map = _ColorMapping(_colors_full_map)
|
|
88
|
+
|
|
89
|
+
_REPR_PNG_SIZE = (512, 64)
|
|
90
|
+
_BIVAR_REPR_PNG_SIZE = 256
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def get_named_colors_mapping():
|
|
94
|
+
"""Return the global mapping of names to named colors."""
|
|
95
|
+
return _colors_full_map
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class ColorSequenceRegistry(Mapping):
|
|
99
|
+
r"""
|
|
100
|
+
Container for sequences of colors that are known to Matplotlib by name.
|
|
101
|
+
|
|
102
|
+
The universal registry instance is `matplotlib.color_sequences`. There
|
|
103
|
+
should be no need for users to instantiate `.ColorSequenceRegistry`
|
|
104
|
+
themselves.
|
|
105
|
+
|
|
106
|
+
Read access uses a dict-like interface mapping names to lists of colors::
|
|
107
|
+
|
|
108
|
+
import matplotlib_rs as mpl
|
|
109
|
+
colors = mpl.color_sequences['tab10']
|
|
110
|
+
|
|
111
|
+
For a list of built in color sequences, see :doc:`/gallery/color/color_sequences`.
|
|
112
|
+
The returned lists are copies, so that their modification does not change
|
|
113
|
+
the global definition of the color sequence.
|
|
114
|
+
|
|
115
|
+
Additional color sequences can be added via
|
|
116
|
+
`.ColorSequenceRegistry.register`::
|
|
117
|
+
|
|
118
|
+
mpl.color_sequences.register('rgb', ['r', 'g', 'b'])
|
|
119
|
+
"""
|
|
120
|
+
|
|
121
|
+
_BUILTIN_COLOR_SEQUENCES = {
|
|
122
|
+
'tab10': _cm._tab10_data,
|
|
123
|
+
'tab20': _cm._tab20_data,
|
|
124
|
+
'tab20b': _cm._tab20b_data,
|
|
125
|
+
'tab20c': _cm._tab20c_data,
|
|
126
|
+
'Pastel1': _cm._Pastel1_data,
|
|
127
|
+
'Pastel2': _cm._Pastel2_data,
|
|
128
|
+
'Paired': _cm._Paired_data,
|
|
129
|
+
'Accent': _cm._Accent_data,
|
|
130
|
+
'okabe_ito': _cm._okabe_ito_data,
|
|
131
|
+
'Dark2': _cm._Dark2_data,
|
|
132
|
+
'Set1': _cm._Set1_data,
|
|
133
|
+
'Set2': _cm._Set2_data,
|
|
134
|
+
'Set3': _cm._Set3_data,
|
|
135
|
+
'petroff6': _cm._petroff6_data,
|
|
136
|
+
'petroff8': _cm._petroff8_data,
|
|
137
|
+
'petroff10': _cm._petroff10_data,
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
def __init__(self):
|
|
141
|
+
self._color_sequences = {**self._BUILTIN_COLOR_SEQUENCES}
|
|
142
|
+
|
|
143
|
+
def __getitem__(self, item):
|
|
144
|
+
return list(_api.getitem_checked(self._color_sequences, _error_cls=KeyError,
|
|
145
|
+
sequence_name=item))
|
|
146
|
+
|
|
147
|
+
def __iter__(self):
|
|
148
|
+
return iter(self._color_sequences)
|
|
149
|
+
|
|
150
|
+
def __len__(self):
|
|
151
|
+
return len(self._color_sequences)
|
|
152
|
+
|
|
153
|
+
def __str__(self):
|
|
154
|
+
return ('ColorSequenceRegistry; available colormaps:\n' +
|
|
155
|
+
', '.join(f"'{name}'" for name in self))
|
|
156
|
+
|
|
157
|
+
def register(self, name, color_list):
|
|
158
|
+
"""
|
|
159
|
+
Register a new color sequence.
|
|
160
|
+
|
|
161
|
+
The color sequence registry stores a copy of the given *color_list*, so
|
|
162
|
+
that future changes to the original list do not affect the registered
|
|
163
|
+
color sequence. Think of this as the registry taking a snapshot
|
|
164
|
+
of *color_list* at registration.
|
|
165
|
+
|
|
166
|
+
Parameters
|
|
167
|
+
----------
|
|
168
|
+
name : str
|
|
169
|
+
The name for the color sequence.
|
|
170
|
+
|
|
171
|
+
color_list : list of :mpltype:`color`
|
|
172
|
+
An iterable returning valid Matplotlib colors when iterating over.
|
|
173
|
+
Note however that the returned color sequence will always be a
|
|
174
|
+
list regardless of the input type.
|
|
175
|
+
|
|
176
|
+
"""
|
|
177
|
+
if name in self._BUILTIN_COLOR_SEQUENCES:
|
|
178
|
+
raise ValueError(f"{name!r} is a reserved name for a builtin "
|
|
179
|
+
"color sequence")
|
|
180
|
+
|
|
181
|
+
color_list = list(color_list) # force copy and coerce type to list
|
|
182
|
+
for color in color_list:
|
|
183
|
+
try:
|
|
184
|
+
to_rgba(color)
|
|
185
|
+
except ValueError:
|
|
186
|
+
raise ValueError(
|
|
187
|
+
f"{color!r} is not a valid color specification")
|
|
188
|
+
|
|
189
|
+
self._color_sequences[name] = color_list
|
|
190
|
+
|
|
191
|
+
def unregister(self, name):
|
|
192
|
+
"""
|
|
193
|
+
Remove a sequence from the registry.
|
|
194
|
+
|
|
195
|
+
You cannot remove built-in color sequences.
|
|
196
|
+
|
|
197
|
+
If the name is not registered, returns with no error.
|
|
198
|
+
"""
|
|
199
|
+
if name in self._BUILTIN_COLOR_SEQUENCES:
|
|
200
|
+
raise ValueError(
|
|
201
|
+
f"Cannot unregister builtin color sequence {name!r}")
|
|
202
|
+
self._color_sequences.pop(name, None)
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
_color_sequences = ColorSequenceRegistry()
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _sanitize_extrema(ex):
|
|
209
|
+
if ex is None:
|
|
210
|
+
return ex
|
|
211
|
+
try:
|
|
212
|
+
ret = ex.item()
|
|
213
|
+
except AttributeError:
|
|
214
|
+
ret = float(ex)
|
|
215
|
+
return ret
|
|
216
|
+
|
|
217
|
+
_nth_color_re = re.compile(r"\AC[0-9]+\Z")
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def _is_nth_color(c):
|
|
221
|
+
"""Return whether *c* can be interpreted as an item in the color cycle."""
|
|
222
|
+
return isinstance(c, str) and _nth_color_re.match(c)
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def is_color_like(c):
|
|
226
|
+
"""Return whether *c* as a valid Matplotlib :mpltype:`color` specifier."""
|
|
227
|
+
# Special-case nth color syntax because it cannot be parsed during setup.
|
|
228
|
+
if _is_nth_color(c):
|
|
229
|
+
return True
|
|
230
|
+
try:
|
|
231
|
+
to_rgba(c)
|
|
232
|
+
except (TypeError, ValueError):
|
|
233
|
+
return False
|
|
234
|
+
else:
|
|
235
|
+
return True
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _has_alpha_channel(c):
|
|
239
|
+
"""
|
|
240
|
+
Return whether *c* is a color with an alpha channel.
|
|
241
|
+
|
|
242
|
+
If *c* is not a valid color specifier, then the result is undefined.
|
|
243
|
+
"""
|
|
244
|
+
# The following logic uses the assumption that c is a valid color spec.
|
|
245
|
+
# For speed and simplicity, we intentionally don't care about other inputs.
|
|
246
|
+
# Anything can happen with them.
|
|
247
|
+
|
|
248
|
+
# if c is a hex, it has an alpha channel when it has 4 (or 8) digits after '#'
|
|
249
|
+
if isinstance(c, str):
|
|
250
|
+
if c[0] == '#' and (len(c) == 5 or len(c) == 9):
|
|
251
|
+
# example: '#fff8' or '#0f0f0f80'
|
|
252
|
+
return True
|
|
253
|
+
else:
|
|
254
|
+
# if c isn't a string, it can be an RGB(A) or a color-alpha tuple
|
|
255
|
+
# if it has length 4, it has an alpha channel
|
|
256
|
+
if len(c) == 4:
|
|
257
|
+
# example: [0.5, 0.5, 0.5, 0.5]
|
|
258
|
+
return True
|
|
259
|
+
|
|
260
|
+
# if it has length 2, it's a color/alpha tuple
|
|
261
|
+
# if the second element isn't None or the first element has length = 4
|
|
262
|
+
if len(c) == 2 and (c[1] is not None or _has_alpha_channel(c[0])):
|
|
263
|
+
# example: ([0.5, 0.5, 0.5, 0.5], None) or ('r', 0.5)
|
|
264
|
+
return True
|
|
265
|
+
|
|
266
|
+
# otherwise it doesn't have an alpha channel
|
|
267
|
+
return False
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _check_color_like(**kwargs):
|
|
271
|
+
"""
|
|
272
|
+
For each *key, value* pair in *kwargs*, check that *value* is color-like.
|
|
273
|
+
"""
|
|
274
|
+
for k, v in kwargs.items():
|
|
275
|
+
if not is_color_like(v):
|
|
276
|
+
raise ValueError(
|
|
277
|
+
f"{v!r} is not a valid value for {k}: supported inputs are "
|
|
278
|
+
f"(r, g, b) and (r, g, b, a) 0-1 float tuples; "
|
|
279
|
+
f"'#rrggbb', '#rrggbbaa', '#rgb', '#rgba' strings; "
|
|
280
|
+
f"named color strings; "
|
|
281
|
+
f"string reprs of 0-1 floats for grayscale values; "
|
|
282
|
+
f"'C0', 'C1', ... strings for colors of the color cycle; "
|
|
283
|
+
f"and pairs combining one of the above with an alpha value")
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def same_color(c1, c2):
|
|
287
|
+
"""
|
|
288
|
+
Return whether the colors *c1* and *c2* are the same.
|
|
289
|
+
|
|
290
|
+
Parameters
|
|
291
|
+
----------
|
|
292
|
+
c1, c2 : :mpltype:`color` or list of :mpltype:`color` or RGB(A) array
|
|
293
|
+
If passing multiple colors, *c1* and *c2* must be of the same length. RGB(A)
|
|
294
|
+
arrays must be of shape (ncolors, 3) or (ncolors, 4).
|
|
295
|
+
|
|
296
|
+
Returns
|
|
297
|
+
-------
|
|
298
|
+
bool
|
|
299
|
+
"""
|
|
300
|
+
c1 = to_rgba_array(c1)
|
|
301
|
+
c2 = to_rgba_array(c2)
|
|
302
|
+
n1 = max(c1.shape[0], 1) # 'none' results in shape (0, 4), but is 1-elem
|
|
303
|
+
n2 = max(c2.shape[0], 1) # 'none' results in shape (0, 4), but is 1-elem
|
|
304
|
+
|
|
305
|
+
if n1 != n2:
|
|
306
|
+
raise ValueError('Different number of elements passed.')
|
|
307
|
+
# The following shape test is needed to correctly handle comparisons with
|
|
308
|
+
# 'none', which results in a shape (0, 4) array and thus cannot be tested
|
|
309
|
+
# via value comparison.
|
|
310
|
+
return c1.shape == c2.shape and (c1 == c2).all()
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def to_rgba(c, alpha=None):
|
|
314
|
+
"""
|
|
315
|
+
Convert *c* to an RGBA color.
|
|
316
|
+
|
|
317
|
+
Parameters
|
|
318
|
+
----------
|
|
319
|
+
c : :mpltype:`color` or ``np.ma.masked``
|
|
320
|
+
|
|
321
|
+
alpha : float, optional
|
|
322
|
+
If *alpha* is given, force the alpha value of the returned RGBA tuple
|
|
323
|
+
to *alpha*.
|
|
324
|
+
|
|
325
|
+
If None, the alpha value from *c* is used. If *c* does not have an
|
|
326
|
+
alpha channel, then alpha defaults to 1.
|
|
327
|
+
|
|
328
|
+
*alpha* is ignored for the color value ``"none"`` (case-insensitive),
|
|
329
|
+
which always maps to ``(0, 0, 0, 0)``.
|
|
330
|
+
|
|
331
|
+
Returns
|
|
332
|
+
-------
|
|
333
|
+
tuple
|
|
334
|
+
Tuple of floats ``(r, g, b, a)``, where each channel (red, green, blue,
|
|
335
|
+
alpha) can assume values between 0 and 1.
|
|
336
|
+
"""
|
|
337
|
+
if isinstance(c, tuple) and len(c) == 2:
|
|
338
|
+
if alpha is None:
|
|
339
|
+
c, alpha = c
|
|
340
|
+
else:
|
|
341
|
+
c = c[0]
|
|
342
|
+
# Special-case nth color syntax because it should not be cached.
|
|
343
|
+
if _is_nth_color(c):
|
|
344
|
+
prop_cycler = mpl.rcParams['axes.prop_cycle']
|
|
345
|
+
colors = prop_cycler.by_key().get('color', ['k'])
|
|
346
|
+
c = colors[int(c[1:]) % len(colors)]
|
|
347
|
+
try:
|
|
348
|
+
rgba = _colors_full_map.cache[c, alpha]
|
|
349
|
+
except (KeyError, TypeError): # Not in cache, or unhashable.
|
|
350
|
+
rgba = None
|
|
351
|
+
if rgba is None: # Suppress exception chaining of cache lookup failure.
|
|
352
|
+
rgba = _to_rgba_no_colorcycle(c, alpha)
|
|
353
|
+
try:
|
|
354
|
+
_colors_full_map.cache[c, alpha] = rgba
|
|
355
|
+
except TypeError:
|
|
356
|
+
pass
|
|
357
|
+
return rgba
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def _to_rgba_no_colorcycle(c, alpha=None):
|
|
361
|
+
"""
|
|
362
|
+
Convert *c* to an RGBA color, with no support for color-cycle syntax.
|
|
363
|
+
|
|
364
|
+
If *alpha* is given, force the alpha value of the returned RGBA tuple
|
|
365
|
+
to *alpha*. Otherwise, the alpha value from *c* is used, if it has alpha
|
|
366
|
+
information, or defaults to 1.
|
|
367
|
+
|
|
368
|
+
*alpha* is ignored for the color value ``"none"`` (case-insensitive),
|
|
369
|
+
which always maps to ``(0, 0, 0, 0)``.
|
|
370
|
+
"""
|
|
371
|
+
if alpha is not None and not 0 <= alpha <= 1:
|
|
372
|
+
raise ValueError("'alpha' must be between 0 and 1, inclusive")
|
|
373
|
+
orig_c = c
|
|
374
|
+
if c is np.ma.masked:
|
|
375
|
+
return (0., 0., 0., 0.)
|
|
376
|
+
if isinstance(c, str):
|
|
377
|
+
if c.lower() == "none":
|
|
378
|
+
return (0., 0., 0., 0.)
|
|
379
|
+
# Named color.
|
|
380
|
+
try:
|
|
381
|
+
# This may turn c into a non-string, so we check again below.
|
|
382
|
+
c = _colors_full_map[c]
|
|
383
|
+
except KeyError:
|
|
384
|
+
if len(c) != 1:
|
|
385
|
+
try:
|
|
386
|
+
c = _colors_full_map[c.lower()]
|
|
387
|
+
except KeyError:
|
|
388
|
+
pass
|
|
389
|
+
if isinstance(c, str):
|
|
390
|
+
if re.fullmatch("#[a-fA-F0-9]+", c):
|
|
391
|
+
if len(c) == 7: # #rrggbb hex format.
|
|
392
|
+
return (*[n / 0xff for n in bytes.fromhex(c[1:])],
|
|
393
|
+
alpha if alpha is not None else 1.)
|
|
394
|
+
elif len(c) == 4: # #rgb hex format, shorthand for #rrggbb.
|
|
395
|
+
return (*[int(n, 16) / 0xf for n in c[1:]],
|
|
396
|
+
alpha if alpha is not None else 1.)
|
|
397
|
+
elif len(c) == 9: # #rrggbbaa hex format.
|
|
398
|
+
color = [n / 0xff for n in bytes.fromhex(c[1:])]
|
|
399
|
+
if alpha is not None:
|
|
400
|
+
color[-1] = alpha
|
|
401
|
+
return tuple(color)
|
|
402
|
+
elif len(c) == 5: # #rgba hex format, shorthand for #rrggbbaa.
|
|
403
|
+
color = [int(n, 16) / 0xf for n in c[1:]]
|
|
404
|
+
if alpha is not None:
|
|
405
|
+
color[-1] = alpha
|
|
406
|
+
return tuple(color)
|
|
407
|
+
else:
|
|
408
|
+
raise ValueError(f"Invalid hex color specifier: {orig_c!r}")
|
|
409
|
+
# string gray.
|
|
410
|
+
try:
|
|
411
|
+
c = float(c)
|
|
412
|
+
except ValueError:
|
|
413
|
+
pass
|
|
414
|
+
else:
|
|
415
|
+
if not (0 <= c <= 1):
|
|
416
|
+
raise ValueError(
|
|
417
|
+
f"Invalid string grayscale value {orig_c!r}. "
|
|
418
|
+
f"Value must be within 0-1 range")
|
|
419
|
+
return c, c, c, alpha if alpha is not None else 1.
|
|
420
|
+
raise ValueError(f"Invalid RGBA argument: {orig_c!r}")
|
|
421
|
+
# turn 2-D array into 1-D array
|
|
422
|
+
if isinstance(c, np.ndarray):
|
|
423
|
+
if c.ndim == 2 and c.shape[0] == 1:
|
|
424
|
+
c = c.reshape(-1)
|
|
425
|
+
# tuple color.
|
|
426
|
+
if not np.iterable(c):
|
|
427
|
+
raise ValueError(f"Invalid RGBA argument: {orig_c!r}")
|
|
428
|
+
if len(c) not in [3, 4]:
|
|
429
|
+
raise ValueError("RGBA sequence should have length 3 or 4")
|
|
430
|
+
if not all(isinstance(x, Real) for x in c):
|
|
431
|
+
# Checks that don't work: `map(float, ...)`, `np.array(..., float)` and
|
|
432
|
+
# `np.array(...).astype(float)` would all convert "0.5" to 0.5.
|
|
433
|
+
raise ValueError(f"Invalid RGBA argument: {orig_c!r}")
|
|
434
|
+
# Return a tuple to prevent the cached value from being modified.
|
|
435
|
+
c = tuple(map(float, c))
|
|
436
|
+
if len(c) == 3 and alpha is None:
|
|
437
|
+
alpha = 1
|
|
438
|
+
if alpha is not None:
|
|
439
|
+
c = c[:3] + (alpha,)
|
|
440
|
+
if any(elem < 0 or elem > 1 for elem in c):
|
|
441
|
+
raise ValueError("RGBA values should be within 0-1 range")
|
|
442
|
+
return c
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
def to_rgba_array(c, alpha=None):
|
|
446
|
+
"""
|
|
447
|
+
Convert *c* to a (n, 4) array of RGBA colors.
|
|
448
|
+
|
|
449
|
+
Parameters
|
|
450
|
+
----------
|
|
451
|
+
c : :mpltype:`color` or list of :mpltype:`color` or RGB(A) array
|
|
452
|
+
If *c* is a masked array, an `~numpy.ndarray` is returned with a
|
|
453
|
+
(0, 0, 0, 0) row for each masked value or row in *c*.
|
|
454
|
+
|
|
455
|
+
alpha : float or sequence of floats, optional
|
|
456
|
+
If *alpha* is given, force the alpha value of the returned RGBA tuple
|
|
457
|
+
to *alpha*.
|
|
458
|
+
|
|
459
|
+
If None, the alpha value from *c* is used. If *c* does not have an
|
|
460
|
+
alpha channel, then alpha defaults to 1.
|
|
461
|
+
|
|
462
|
+
*alpha* is ignored for the color value ``"none"`` (case-insensitive),
|
|
463
|
+
which always maps to ``(0, 0, 0, 0)``.
|
|
464
|
+
|
|
465
|
+
If *alpha* is a sequence and *c* is a single color, *c* will be
|
|
466
|
+
repeated to match the length of *alpha*.
|
|
467
|
+
|
|
468
|
+
Returns
|
|
469
|
+
-------
|
|
470
|
+
array
|
|
471
|
+
(n, 4) array of RGBA colors, where each channel (red, green, blue,
|
|
472
|
+
alpha) can assume values between 0 and 1.
|
|
473
|
+
"""
|
|
474
|
+
if isinstance(c, tuple) and len(c) == 2 and isinstance(c[1], Real):
|
|
475
|
+
if alpha is None:
|
|
476
|
+
c, alpha = c
|
|
477
|
+
else:
|
|
478
|
+
c = c[0]
|
|
479
|
+
# Special-case inputs that are already arrays, for performance. (If the
|
|
480
|
+
# array has the wrong kind or shape, raise the error during one-at-a-time
|
|
481
|
+
# conversion.)
|
|
482
|
+
if np.iterable(alpha):
|
|
483
|
+
alpha = np.asarray(alpha).ravel()
|
|
484
|
+
if (isinstance(c, np.ndarray) and c.dtype.kind in "if"
|
|
485
|
+
and c.ndim == 2 and c.shape[1] in [3, 4]):
|
|
486
|
+
mask = c.mask.any(axis=1) if np.ma.is_masked(c) else None
|
|
487
|
+
c = np.ma.getdata(c)
|
|
488
|
+
if np.iterable(alpha):
|
|
489
|
+
if c.shape[0] == 1 and alpha.shape[0] > 1:
|
|
490
|
+
c = np.tile(c, (alpha.shape[0], 1))
|
|
491
|
+
elif c.shape[0] != alpha.shape[0]:
|
|
492
|
+
raise ValueError("The number of colors must match the number"
|
|
493
|
+
" of alpha values if there are more than one"
|
|
494
|
+
" of each.")
|
|
495
|
+
if c.shape[1] == 3:
|
|
496
|
+
result = np.column_stack([c, np.zeros(len(c))])
|
|
497
|
+
result[:, -1] = alpha if alpha is not None else 1.
|
|
498
|
+
elif c.shape[1] == 4:
|
|
499
|
+
result = c.copy()
|
|
500
|
+
if alpha is not None:
|
|
501
|
+
result[:, -1] = alpha
|
|
502
|
+
if mask is not None:
|
|
503
|
+
result[mask] = 0
|
|
504
|
+
if np.any((result < 0) | (result > 1)):
|
|
505
|
+
raise ValueError("RGBA values should be within 0-1 range")
|
|
506
|
+
return result
|
|
507
|
+
# Handle single values.
|
|
508
|
+
# Note that this occurs *after* handling inputs that are already arrays, as
|
|
509
|
+
# `to_rgba(c, alpha)` (below) is expensive for such inputs, due to the need
|
|
510
|
+
# to format the array in the ValueError message(!).
|
|
511
|
+
if cbook._str_lower_equal(c, "none"):
|
|
512
|
+
return np.zeros((0, 4), float)
|
|
513
|
+
try:
|
|
514
|
+
if np.iterable(alpha):
|
|
515
|
+
return np.array([to_rgba(c, a) for a in alpha], float)
|
|
516
|
+
else:
|
|
517
|
+
return np.array([to_rgba(c, alpha)], float)
|
|
518
|
+
except TypeError:
|
|
519
|
+
pass
|
|
520
|
+
except ValueError as e:
|
|
521
|
+
if e.args == ("'alpha' must be between 0 and 1, inclusive", ):
|
|
522
|
+
# ValueError is from _to_rgba_no_colorcycle().
|
|
523
|
+
raise e
|
|
524
|
+
if isinstance(c, str):
|
|
525
|
+
raise ValueError(f"{c!r} is not a valid color value.")
|
|
526
|
+
|
|
527
|
+
if len(c) == 0:
|
|
528
|
+
return np.zeros((0, 4), float)
|
|
529
|
+
|
|
530
|
+
# Quick path if the whole sequence can be directly converted to a numpy
|
|
531
|
+
# array in one shot.
|
|
532
|
+
if isinstance(c, Sequence):
|
|
533
|
+
lens = {len(cc) if isinstance(cc, (list, tuple)) else -1 for cc in c}
|
|
534
|
+
if lens == {3}:
|
|
535
|
+
rgba = np.column_stack([c, np.ones(len(c))])
|
|
536
|
+
elif lens == {4}:
|
|
537
|
+
rgba = np.array(c)
|
|
538
|
+
else:
|
|
539
|
+
rgba = np.array([to_rgba(cc) for cc in c])
|
|
540
|
+
else:
|
|
541
|
+
rgba = np.array([to_rgba(cc) for cc in c])
|
|
542
|
+
|
|
543
|
+
if alpha is not None:
|
|
544
|
+
rgba[:, 3] = alpha
|
|
545
|
+
if isinstance(c, Sequence):
|
|
546
|
+
# ensure that an explicit alpha does not overwrite full transparency
|
|
547
|
+
# for "none"
|
|
548
|
+
none_mask = [cbook._str_equal(cc, "none") for cc in c]
|
|
549
|
+
rgba[:, 3][none_mask] = 0
|
|
550
|
+
return rgba
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
def to_rgb(c):
|
|
554
|
+
"""
|
|
555
|
+
Convert the :mpltype:`color` *c* to an RGB color tuple.
|
|
556
|
+
|
|
557
|
+
If c has an alpha channel value specified, that is silently dropped.
|
|
558
|
+
"""
|
|
559
|
+
return to_rgba(c)[:3]
|
|
560
|
+
|
|
561
|
+
|
|
562
|
+
def to_hex(c, keep_alpha=False):
|
|
563
|
+
"""
|
|
564
|
+
Convert *c* to a hex color.
|
|
565
|
+
|
|
566
|
+
Parameters
|
|
567
|
+
----------
|
|
568
|
+
c : :mpltype:`color` or `numpy.ma.masked`
|
|
569
|
+
|
|
570
|
+
keep_alpha : bool, default: False
|
|
571
|
+
If False, use the ``#rrggbb`` format, otherwise use ``#rrggbbaa``.
|
|
572
|
+
|
|
573
|
+
Returns
|
|
574
|
+
-------
|
|
575
|
+
str
|
|
576
|
+
``#rrggbb`` or ``#rrggbbaa`` hex color string
|
|
577
|
+
"""
|
|
578
|
+
c = to_rgba(c)
|
|
579
|
+
if not keep_alpha:
|
|
580
|
+
c = c[:3]
|
|
581
|
+
return "#" + "".join(format(round(val * 255), "02x") for val in c)
|
|
582
|
+
|
|
583
|
+
|
|
584
|
+
### Backwards-compatible color-conversion API
|
|
585
|
+
|
|
586
|
+
|
|
587
|
+
cnames = CSS4_COLORS #: :meta private:
|
|
588
|
+
hexColorPattern = re.compile(r"\A#[a-fA-F0-9]{6}\Z") #: :meta private:
|
|
589
|
+
rgb2hex = to_hex #: :meta private:
|
|
590
|
+
hex2color = to_rgb #: :meta private:
|
|
591
|
+
|
|
592
|
+
|
|
593
|
+
class ColorConverter:
|
|
594
|
+
"""
|
|
595
|
+
A class only kept for backwards compatibility.
|
|
596
|
+
|
|
597
|
+
Its functionality is entirely provided by module-level functions.
|
|
598
|
+
|
|
599
|
+
:meta private:
|
|
600
|
+
"""
|
|
601
|
+
colors = _colors_full_map
|
|
602
|
+
cache = _colors_full_map.cache
|
|
603
|
+
to_rgb = staticmethod(to_rgb)
|
|
604
|
+
to_rgba = staticmethod(to_rgba)
|
|
605
|
+
to_rgba_array = staticmethod(to_rgba_array)
|
|
606
|
+
|
|
607
|
+
|
|
608
|
+
colorConverter = ColorConverter()
|
|
609
|
+
|
|
610
|
+
|
|
611
|
+
### End of backwards-compatible color-conversion API
|
|
612
|
+
|
|
613
|
+
|
|
614
|
+
def _create_lookup_table(N, data, gamma=1.0):
|
|
615
|
+
r"""
|
|
616
|
+
Create an *N* -element 1D lookup table.
|
|
617
|
+
|
|
618
|
+
This assumes a mapping :math:`f : [0, 1] \rightarrow [0, 1]`. The returned
|
|
619
|
+
data is an array of N values :math:`y = f(x)` where x is sampled from
|
|
620
|
+
[0, 1].
|
|
621
|
+
|
|
622
|
+
By default (*gamma* = 1) x is equidistantly sampled from [0, 1]. The
|
|
623
|
+
*gamma* correction factor :math:`\gamma` distorts this equidistant
|
|
624
|
+
sampling by :math:`x \rightarrow x^\gamma`.
|
|
625
|
+
|
|
626
|
+
Parameters
|
|
627
|
+
----------
|
|
628
|
+
N : int
|
|
629
|
+
The number of elements of the created lookup table; at least 1.
|
|
630
|
+
|
|
631
|
+
data : (M, 3) array-like or callable
|
|
632
|
+
Defines the mapping :math:`f`.
|
|
633
|
+
|
|
634
|
+
If a (M, 3) array-like, the rows define values (x, y0, y1). The x
|
|
635
|
+
values must start with x=0, end with x=1, and all x values be in
|
|
636
|
+
increasing order.
|
|
637
|
+
|
|
638
|
+
A value between :math:`x_i` and :math:`x_{i+1}` is mapped to the range
|
|
639
|
+
:math:`y^1_{i-1} \ldots y^0_i` by linear interpolation.
|
|
640
|
+
|
|
641
|
+
For the simple case of a y-continuous mapping, y0 and y1 are identical.
|
|
642
|
+
|
|
643
|
+
The two values of y are to allow for discontinuous mapping functions.
|
|
644
|
+
E.g. a sawtooth with a period of 0.2 and an amplitude of 1 would be::
|
|
645
|
+
|
|
646
|
+
[(0, 1, 0), (0.2, 1, 0), (0.4, 1, 0), ..., [(1, 1, 0)]
|
|
647
|
+
|
|
648
|
+
In the special case of ``N == 1``, by convention the returned value
|
|
649
|
+
is y0 for x == 1.
|
|
650
|
+
|
|
651
|
+
If *data* is a callable, it must accept and return numpy arrays::
|
|
652
|
+
|
|
653
|
+
data(x : ndarray) -> ndarray
|
|
654
|
+
|
|
655
|
+
and map values between 0 - 1 to 0 - 1.
|
|
656
|
+
|
|
657
|
+
gamma : float
|
|
658
|
+
Gamma correction factor for input distribution x of the mapping.
|
|
659
|
+
|
|
660
|
+
See also https://en.wikipedia.org/wiki/Gamma_correction.
|
|
661
|
+
|
|
662
|
+
Returns
|
|
663
|
+
-------
|
|
664
|
+
array
|
|
665
|
+
The lookup table where ``lut[x * (N-1)]`` gives the closest value
|
|
666
|
+
for values of x between 0 and 1.
|
|
667
|
+
|
|
668
|
+
Notes
|
|
669
|
+
-----
|
|
670
|
+
This function is internally used for `.LinearSegmentedColormap`.
|
|
671
|
+
"""
|
|
672
|
+
|
|
673
|
+
if callable(data):
|
|
674
|
+
xind = np.linspace(0, 1, N) ** gamma
|
|
675
|
+
lut = np.clip(np.array(data(xind), dtype=float), 0, 1)
|
|
676
|
+
return lut
|
|
677
|
+
|
|
678
|
+
try:
|
|
679
|
+
adata = np.array(data)
|
|
680
|
+
except Exception as err:
|
|
681
|
+
raise TypeError("data must be convertible to an array") from err
|
|
682
|
+
_api.check_shape((None, 3), data=adata)
|
|
683
|
+
|
|
684
|
+
x = adata[:, 0]
|
|
685
|
+
y0 = adata[:, 1]
|
|
686
|
+
y1 = adata[:, 2]
|
|
687
|
+
|
|
688
|
+
if x[0] != 0. or x[-1] != 1.0:
|
|
689
|
+
raise ValueError(
|
|
690
|
+
"data mapping points must start with x=0 and end with x=1")
|
|
691
|
+
if (np.diff(x) < 0).any():
|
|
692
|
+
raise ValueError("data mapping points must have x in increasing order")
|
|
693
|
+
# begin generation of lookup table
|
|
694
|
+
if N == 1:
|
|
695
|
+
# convention: use the y = f(x=1) value for a 1-element lookup table
|
|
696
|
+
lut = np.array(y0[-1])
|
|
697
|
+
else:
|
|
698
|
+
x = x * (N - 1)
|
|
699
|
+
xind = (N - 1) * np.linspace(0, 1, N) ** gamma
|
|
700
|
+
ind = np.searchsorted(x, xind)[1:-1]
|
|
701
|
+
|
|
702
|
+
distance = (xind[1:-1] - x[ind - 1]) / (x[ind] - x[ind - 1])
|
|
703
|
+
lut = np.concatenate([
|
|
704
|
+
[y1[0]],
|
|
705
|
+
distance * (y0[ind] - y1[ind - 1]) + y1[ind - 1],
|
|
706
|
+
[y0[-1]],
|
|
707
|
+
])
|
|
708
|
+
# ensure that the lut is confined to values between 0 and 1 by clipping it
|
|
709
|
+
return np.clip(lut, 0.0, 1.0)
|
|
710
|
+
|
|
711
|
+
|
|
712
|
+
def _save_repr_png(fh, pixels, title, author):
|
|
713
|
+
"""Write the PNG of a colormap's ``_repr_png_`` (by the Rust core)."""
|
|
714
|
+
from matplotlib_rs import _png
|
|
715
|
+
_png.write(fh, pixels, text=_png.text_chunks({
|
|
716
|
+
'Title': title, 'Description': title, 'Author': author, 'Software': author}))
|
|
717
|
+
|
|
718
|
+
|
|
719
|
+
class Colormap:
|
|
720
|
+
"""
|
|
721
|
+
Baseclass for all scalar to RGBA mappings.
|
|
722
|
+
|
|
723
|
+
Typically, Colormap instances are used to convert data values (floats)
|
|
724
|
+
from the interval ``[0, 1]`` to the RGBA color that the respective
|
|
725
|
+
Colormap represents. For scaling of data into the ``[0, 1]`` interval see
|
|
726
|
+
`matplotlib.colors.Normalize`. Subclasses of `matplotlib.cm.ScalarMappable`
|
|
727
|
+
make heavy use of this ``data -> normalize -> map-to-color`` processing
|
|
728
|
+
chain.
|
|
729
|
+
"""
|
|
730
|
+
|
|
731
|
+
def __init__(self, name, N=256, *, bad=None, under=None, over=None):
|
|
732
|
+
"""
|
|
733
|
+
Parameters
|
|
734
|
+
----------
|
|
735
|
+
name : str
|
|
736
|
+
The name of the colormap.
|
|
737
|
+
N : int
|
|
738
|
+
The number of RGB quantization levels.
|
|
739
|
+
bad : :mpltype:`color`, default: transparent
|
|
740
|
+
The color for invalid values (NaN or masked).
|
|
741
|
+
|
|
742
|
+
.. versionadded:: 3.11
|
|
743
|
+
|
|
744
|
+
under : :mpltype:`color`, default: color of the lowest value
|
|
745
|
+
The color for low out-of-range values.
|
|
746
|
+
|
|
747
|
+
.. versionadded:: 3.11
|
|
748
|
+
|
|
749
|
+
over : :mpltype:`color`, default: color of the highest value
|
|
750
|
+
The color for high out-of-range values.
|
|
751
|
+
|
|
752
|
+
.. versionadded:: 3.11
|
|
753
|
+
"""
|
|
754
|
+
self.name = name
|
|
755
|
+
self.N = int(N) # ensure that N is always int
|
|
756
|
+
self._rgba_bad = (0.0, 0.0, 0.0, 0.0) if bad is None else to_rgba(bad)
|
|
757
|
+
self._rgba_under = None if under is None else to_rgba(under)
|
|
758
|
+
self._rgba_over = None if over is None else to_rgba(over)
|
|
759
|
+
self._i_under = self.N
|
|
760
|
+
self._i_over = self.N + 1
|
|
761
|
+
self._i_bad = self.N + 2
|
|
762
|
+
self._isinit = False
|
|
763
|
+
self.n_variates = 1
|
|
764
|
+
#: When this colormap exists on a scalar mappable and colorbar_extend
|
|
765
|
+
#: is not False, colorbar creation will pick up ``colorbar_extend`` as
|
|
766
|
+
#: the default value for the ``extend`` keyword in the
|
|
767
|
+
#: `matplotlib.colorbar.Colorbar` constructor.
|
|
768
|
+
self.colorbar_extend = False
|
|
769
|
+
|
|
770
|
+
def __call__(self, X, alpha=None, bytes=False):
|
|
771
|
+
r"""
|
|
772
|
+
Parameters
|
|
773
|
+
----------
|
|
774
|
+
X : float or int or array-like
|
|
775
|
+
The data value(s) to convert to RGBA.
|
|
776
|
+
For floats, *X* should be in the interval ``[0.0, 1.0]`` to
|
|
777
|
+
return the RGBA values ``X*100`` percent along the Colormap line.
|
|
778
|
+
For integers, *X* should be in the interval ``[0, Colormap.N)`` to
|
|
779
|
+
return RGBA values *indexed* from the Colormap with index ``X``.
|
|
780
|
+
alpha : float or array-like or None
|
|
781
|
+
Alpha must be a scalar between 0 and 1, a sequence of such
|
|
782
|
+
floats with shape matching X, or None.
|
|
783
|
+
bytes : bool, default: False
|
|
784
|
+
If False (default), the returned RGBA values will be floats in the
|
|
785
|
+
interval ``[0, 1]`` otherwise they will be `numpy.uint8`\s in the
|
|
786
|
+
interval ``[0, 255]``.
|
|
787
|
+
|
|
788
|
+
Returns
|
|
789
|
+
-------
|
|
790
|
+
Tuple of RGBA values if X is scalar, otherwise an array of
|
|
791
|
+
RGBA values with a shape of ``X.shape + (4, )``.
|
|
792
|
+
"""
|
|
793
|
+
rgba, mask = self._get_rgba_and_mask(X, alpha=alpha, bytes=bytes)
|
|
794
|
+
if not np.iterable(X):
|
|
795
|
+
rgba = tuple(rgba)
|
|
796
|
+
return rgba
|
|
797
|
+
|
|
798
|
+
def _get_rgba_and_mask(self, X, alpha=None, bytes=False):
|
|
799
|
+
r"""
|
|
800
|
+
Parameters
|
|
801
|
+
----------
|
|
802
|
+
X : float or int or array-like
|
|
803
|
+
The data value(s) to convert to RGBA.
|
|
804
|
+
For floats, *X* should be in the interval ``[0.0, 1.0]`` to
|
|
805
|
+
return the RGBA values ``X*100`` percent along the Colormap line.
|
|
806
|
+
For integers, *X* should be in the interval ``[0, Colormap.N)`` to
|
|
807
|
+
return RGBA values *indexed* from the Colormap with index ``X``.
|
|
808
|
+
alpha : float or array-like or None
|
|
809
|
+
Alpha must be a scalar between 0 and 1, a sequence of such
|
|
810
|
+
floats with shape matching X, or None.
|
|
811
|
+
bytes : bool, default: False
|
|
812
|
+
If False (default), the returned RGBA values will be floats in the
|
|
813
|
+
interval ``[0, 1]`` otherwise they will be `numpy.uint8`\s in the
|
|
814
|
+
interval ``[0, 255]``.
|
|
815
|
+
|
|
816
|
+
Returns
|
|
817
|
+
-------
|
|
818
|
+
colors : np.ndarray
|
|
819
|
+
Array of RGBA values with a shape of ``X.shape + (4, )``.
|
|
820
|
+
mask : np.ndarray
|
|
821
|
+
Boolean array with True where the input is ``np.nan`` or masked.
|
|
822
|
+
"""
|
|
823
|
+
self._ensure_inited()
|
|
824
|
+
|
|
825
|
+
# matplotlib_rs: large float arrays looked up in Rust (same results)
|
|
826
|
+
found = _colormap.get_rgba_and_mask(self, X, alpha, bytes)
|
|
827
|
+
if found is not None:
|
|
828
|
+
return found
|
|
829
|
+
|
|
830
|
+
xa = np.array(X, copy=True)
|
|
831
|
+
if not xa.dtype.isnative:
|
|
832
|
+
# Native byteorder is faster.
|
|
833
|
+
xa = xa.byteswap().view(xa.dtype.newbyteorder())
|
|
834
|
+
if xa.dtype.kind == "f":
|
|
835
|
+
xa *= self.N
|
|
836
|
+
# xa == 1 (== N after multiplication) is not out of range.
|
|
837
|
+
xa[xa == self.N] = self.N - 1
|
|
838
|
+
# Pre-compute the masks before casting to int (which can truncate
|
|
839
|
+
# negative values to zero or wrap large floats to negative ints).
|
|
840
|
+
mask_under = xa < 0
|
|
841
|
+
mask_over = xa >= self.N
|
|
842
|
+
# If input was masked, get the bad mask from it; else mask out nans.
|
|
843
|
+
mask_bad = X.mask if np.ma.is_masked(X) else np.isnan(xa)
|
|
844
|
+
with np.errstate(invalid="ignore"):
|
|
845
|
+
# We need this cast for unsigned ints as well as floats
|
|
846
|
+
xa = xa.astype(int)
|
|
847
|
+
xa[mask_under] = self._i_under
|
|
848
|
+
xa[mask_over] = self._i_over
|
|
849
|
+
xa[mask_bad] = self._i_bad
|
|
850
|
+
|
|
851
|
+
lut = self._lut
|
|
852
|
+
if bytes:
|
|
853
|
+
lut = (lut * 255).astype(np.uint8)
|
|
854
|
+
|
|
855
|
+
rgba = lut.take(xa, axis=0, mode='clip')
|
|
856
|
+
|
|
857
|
+
if alpha is not None:
|
|
858
|
+
alpha = np.clip(alpha, 0, 1)
|
|
859
|
+
if bytes:
|
|
860
|
+
alpha *= 255 # Will be cast to uint8 upon assignment.
|
|
861
|
+
if alpha.shape not in [(), xa.shape]:
|
|
862
|
+
raise ValueError(
|
|
863
|
+
f"alpha is array-like but its shape {alpha.shape} does "
|
|
864
|
+
f"not match that of X {xa.shape}")
|
|
865
|
+
rgba[..., -1] = alpha
|
|
866
|
+
# If the "bad" color is all zeros, then ignore alpha input.
|
|
867
|
+
if (lut[-1] == 0).all():
|
|
868
|
+
rgba[mask_bad] = (0, 0, 0, 0)
|
|
869
|
+
|
|
870
|
+
return rgba, mask_bad
|
|
871
|
+
|
|
872
|
+
def __copy__(self):
|
|
873
|
+
cls = self.__class__
|
|
874
|
+
cmapobject = cls.__new__(cls)
|
|
875
|
+
cmapobject.__dict__.update(self.__dict__)
|
|
876
|
+
if self._isinit:
|
|
877
|
+
cmapobject._lut = np.copy(self._lut)
|
|
878
|
+
return cmapobject
|
|
879
|
+
|
|
880
|
+
def __eq__(self, other):
|
|
881
|
+
if (not isinstance(other, Colormap) or
|
|
882
|
+
self.colorbar_extend != other.colorbar_extend):
|
|
883
|
+
return False
|
|
884
|
+
# To compare lookup tables the Colormaps have to be initialized
|
|
885
|
+
self._ensure_inited()
|
|
886
|
+
other._ensure_inited()
|
|
887
|
+
return np.array_equal(self._lut, other._lut)
|
|
888
|
+
|
|
889
|
+
def get_bad(self):
|
|
890
|
+
"""Get the color for masked values."""
|
|
891
|
+
self._ensure_inited()
|
|
892
|
+
return np.array(self._lut[self._i_bad])
|
|
893
|
+
|
|
894
|
+
@_api.deprecated(
|
|
895
|
+
"3.11",
|
|
896
|
+
pending=True,
|
|
897
|
+
alternative="cmap.with_extremes(bad=...) or Colormap(bad=...)")
|
|
898
|
+
def set_bad(self, color='k', alpha=None):
|
|
899
|
+
"""Set the color for masked values."""
|
|
900
|
+
self._set_extremes(bad=(color, alpha))
|
|
901
|
+
|
|
902
|
+
def get_under(self):
|
|
903
|
+
"""Get the color for low out-of-range values."""
|
|
904
|
+
self._ensure_inited()
|
|
905
|
+
return np.array(self._lut[self._i_under])
|
|
906
|
+
|
|
907
|
+
@_api.deprecated(
|
|
908
|
+
"3.11",
|
|
909
|
+
pending=True,
|
|
910
|
+
alternative="cmap.with_extremes(under=...) or Colormap(under=...)")
|
|
911
|
+
def set_under(self, color='k', alpha=None):
|
|
912
|
+
"""Set the color for low out-of-range values."""
|
|
913
|
+
self._set_extremes(under=(color, alpha))
|
|
914
|
+
|
|
915
|
+
def get_over(self):
|
|
916
|
+
"""Get the color for high out-of-range values."""
|
|
917
|
+
self._ensure_inited()
|
|
918
|
+
return np.array(self._lut[self._i_over])
|
|
919
|
+
|
|
920
|
+
@_api.deprecated(
|
|
921
|
+
"3.11",
|
|
922
|
+
pending=True,
|
|
923
|
+
alternative="cmap.with_extremes(over=...) or Colormap(over=...)")
|
|
924
|
+
def set_over(self, color='k', alpha=None):
|
|
925
|
+
"""Set the color for high out-of-range values."""
|
|
926
|
+
self._set_extremes(over=(color, alpha))
|
|
927
|
+
|
|
928
|
+
@_api.deprecated(
|
|
929
|
+
"3.11",
|
|
930
|
+
pending=True,
|
|
931
|
+
alternative="cmap.with_extremes(bad=..., under=..., over=...) or "
|
|
932
|
+
"Colormap(bad=..., under=..., over=...)")
|
|
933
|
+
def set_extremes(self, *, bad=None, under=None, over=None):
|
|
934
|
+
"""
|
|
935
|
+
Set the colors for masked (*bad*) values and, when ``norm.clip =
|
|
936
|
+
False``, low (*under*) and high (*over*) out-of-range values.
|
|
937
|
+
"""
|
|
938
|
+
self._set_extremes(bad=bad, under=under, over=over)
|
|
939
|
+
|
|
940
|
+
def with_extremes(self, *, bad=None, under=None, over=None):
|
|
941
|
+
"""
|
|
942
|
+
Return a copy of the colormap, for which the colors for masked (*bad*)
|
|
943
|
+
values and, when ``norm.clip = False``, low (*under*) and high (*over*)
|
|
944
|
+
out-of-range values, have been set accordingly.
|
|
945
|
+
"""
|
|
946
|
+
new_cm = self.copy()
|
|
947
|
+
new_cm._set_extremes(bad=bad, under=under, over=over)
|
|
948
|
+
return new_cm
|
|
949
|
+
|
|
950
|
+
def _set_extremes(self, bad=None, under=None, over=None):
|
|
951
|
+
"""
|
|
952
|
+
Set the colors for masked (*bad*) and out-of-range (*under* and *over*) values.
|
|
953
|
+
|
|
954
|
+
Parameters that are None are left unchanged.
|
|
955
|
+
"""
|
|
956
|
+
if bad is not None:
|
|
957
|
+
self._rgba_bad = to_rgba(bad)
|
|
958
|
+
if under is not None:
|
|
959
|
+
self._rgba_under = to_rgba(under)
|
|
960
|
+
if over is not None:
|
|
961
|
+
self._rgba_over = to_rgba(over)
|
|
962
|
+
if self._isinit:
|
|
963
|
+
self._update_lut_extremes()
|
|
964
|
+
|
|
965
|
+
def _update_lut_extremes(self):
|
|
966
|
+
"""Ensure than an existing lookup table has the correct extreme values."""
|
|
967
|
+
if self._rgba_under:
|
|
968
|
+
self._lut[self._i_under] = self._rgba_under
|
|
969
|
+
else:
|
|
970
|
+
self._lut[self._i_under] = self._lut[0]
|
|
971
|
+
if self._rgba_over:
|
|
972
|
+
self._lut[self._i_over] = self._rgba_over
|
|
973
|
+
else:
|
|
974
|
+
self._lut[self._i_over] = self._lut[self.N - 1]
|
|
975
|
+
self._lut[self._i_bad] = self._rgba_bad
|
|
976
|
+
|
|
977
|
+
def with_alpha(self, alpha):
|
|
978
|
+
"""
|
|
979
|
+
Return a copy of the colormap with a new uniform transparency.
|
|
980
|
+
|
|
981
|
+
Parameters
|
|
982
|
+
----------
|
|
983
|
+
alpha : float
|
|
984
|
+
The alpha blending value, between 0 (transparent) and 1 (opaque).
|
|
985
|
+
"""
|
|
986
|
+
if not isinstance(alpha, Real):
|
|
987
|
+
raise TypeError(f"'alpha' must be numeric or None, not {type(alpha)}")
|
|
988
|
+
if not 0 <= alpha <= 1:
|
|
989
|
+
raise ValueError("'alpha' must be between 0 and 1, inclusive")
|
|
990
|
+
new_cm = self.copy()
|
|
991
|
+
new_cm._ensure_inited()
|
|
992
|
+
new_cm._lut[:, 3] = alpha
|
|
993
|
+
return new_cm
|
|
994
|
+
|
|
995
|
+
def _init(self):
|
|
996
|
+
"""Generate the lookup table, ``self._lut``."""
|
|
997
|
+
raise NotImplementedError("Abstract class only")
|
|
998
|
+
|
|
999
|
+
def _ensure_inited(self):
|
|
1000
|
+
if not self._isinit:
|
|
1001
|
+
self._init()
|
|
1002
|
+
|
|
1003
|
+
def is_gray(self):
|
|
1004
|
+
"""Return whether the colormap is grayscale."""
|
|
1005
|
+
self._ensure_inited()
|
|
1006
|
+
return (np.all(self._lut[:, 0] == self._lut[:, 1]) and
|
|
1007
|
+
np.all(self._lut[:, 0] == self._lut[:, 2]))
|
|
1008
|
+
|
|
1009
|
+
def resampled(self, lutsize):
|
|
1010
|
+
"""Return a new colormap with *lutsize* entries."""
|
|
1011
|
+
if hasattr(self, '_resample'):
|
|
1012
|
+
_api.warn_external(
|
|
1013
|
+
"The ability to resample a color map is now public API "
|
|
1014
|
+
f"However the class {type(self)} still only implements "
|
|
1015
|
+
"the previous private _resample method. Please update "
|
|
1016
|
+
"your class."
|
|
1017
|
+
)
|
|
1018
|
+
return self._resample(lutsize)
|
|
1019
|
+
|
|
1020
|
+
raise NotImplementedError()
|
|
1021
|
+
|
|
1022
|
+
def reversed(self, name=None):
|
|
1023
|
+
"""
|
|
1024
|
+
Return a reversed instance of the Colormap.
|
|
1025
|
+
|
|
1026
|
+
.. note:: This function is not implemented for the base class.
|
|
1027
|
+
|
|
1028
|
+
Parameters
|
|
1029
|
+
----------
|
|
1030
|
+
name : str, optional
|
|
1031
|
+
The name for the reversed colormap. If None, the
|
|
1032
|
+
name is set to ``self.name + "_r"``.
|
|
1033
|
+
|
|
1034
|
+
See Also
|
|
1035
|
+
--------
|
|
1036
|
+
LinearSegmentedColormap.reversed
|
|
1037
|
+
ListedColormap.reversed
|
|
1038
|
+
"""
|
|
1039
|
+
raise NotImplementedError()
|
|
1040
|
+
|
|
1041
|
+
def _repr_png_(self):
|
|
1042
|
+
"""Generate a PNG representation of the Colormap."""
|
|
1043
|
+
X = np.tile(np.linspace(0, 1, _REPR_PNG_SIZE[0]),
|
|
1044
|
+
(_REPR_PNG_SIZE[1], 1))
|
|
1045
|
+
pixels = self(X, bytes=True)
|
|
1046
|
+
png_bytes = io.BytesIO()
|
|
1047
|
+
title = self.name + ' colormap'
|
|
1048
|
+
author = f'Matplotlib v{mpl.__version__}, https://matplotlib.org'
|
|
1049
|
+
_save_repr_png(png_bytes, pixels, title, author)
|
|
1050
|
+
return png_bytes.getvalue()
|
|
1051
|
+
|
|
1052
|
+
def _repr_html_(self):
|
|
1053
|
+
"""Generate an HTML representation of the Colormap."""
|
|
1054
|
+
png_bytes = self._repr_png_()
|
|
1055
|
+
png_base64 = base64.b64encode(png_bytes).decode('ascii')
|
|
1056
|
+
def color_block(color):
|
|
1057
|
+
hex_color = to_hex(color, keep_alpha=True)
|
|
1058
|
+
return (f'<div title="{hex_color}" '
|
|
1059
|
+
'style="display: inline-block; '
|
|
1060
|
+
'width: 1em; height: 1em; '
|
|
1061
|
+
'margin: 0; '
|
|
1062
|
+
'vertical-align: middle; '
|
|
1063
|
+
'border: 1px solid #555; '
|
|
1064
|
+
f'background-color: {hex_color};"></div>')
|
|
1065
|
+
|
|
1066
|
+
return ('<div style="vertical-align: middle;">'
|
|
1067
|
+
f'<strong>{self.name}</strong> '
|
|
1068
|
+
'</div>'
|
|
1069
|
+
'<div class="cmap"><img '
|
|
1070
|
+
f'alt="{self.name} colormap" '
|
|
1071
|
+
f'title="{self.name}" '
|
|
1072
|
+
'style="border: 1px solid #555;" '
|
|
1073
|
+
f'src="data:image/png;base64,{png_base64}"></div>'
|
|
1074
|
+
'<div style="vertical-align: middle; '
|
|
1075
|
+
f'max-width: {_REPR_PNG_SIZE[0]+2}px; '
|
|
1076
|
+
'display: flex; justify-content: space-between;">'
|
|
1077
|
+
'<div style="float: left;">'
|
|
1078
|
+
f'{color_block(self.get_under())} under'
|
|
1079
|
+
'</div>'
|
|
1080
|
+
'<div style="margin: 0 auto; display: inline-block;">'
|
|
1081
|
+
f'bad {color_block(self.get_bad())}'
|
|
1082
|
+
'</div>'
|
|
1083
|
+
'<div style="float: right;">'
|
|
1084
|
+
f'over {color_block(self.get_over())}'
|
|
1085
|
+
'</div>'
|
|
1086
|
+
'</div>')
|
|
1087
|
+
|
|
1088
|
+
def copy(self):
|
|
1089
|
+
"""Return a copy of the colormap."""
|
|
1090
|
+
return self.__copy__()
|
|
1091
|
+
|
|
1092
|
+
|
|
1093
|
+
class LinearSegmentedColormap(Colormap):
|
|
1094
|
+
"""
|
|
1095
|
+
Colormap objects based on lookup tables using linear segments.
|
|
1096
|
+
|
|
1097
|
+
The lookup table is generated using linear interpolation for each
|
|
1098
|
+
primary color, with the 0-1 domain divided into any number of
|
|
1099
|
+
segments.
|
|
1100
|
+
"""
|
|
1101
|
+
|
|
1102
|
+
def __init__(self, name, segmentdata, N=256, gamma=1.0, *,
|
|
1103
|
+
bad=None, under=None, over=None):
|
|
1104
|
+
"""
|
|
1105
|
+
Create colormap from linear mapping segments.
|
|
1106
|
+
|
|
1107
|
+
Parameters
|
|
1108
|
+
----------
|
|
1109
|
+
name : str
|
|
1110
|
+
The name of the colormap.
|
|
1111
|
+
segmentdata : dict
|
|
1112
|
+
A dictionary with keys "red", "green", "blue" for the color channels.
|
|
1113
|
+
Each entry should be a list of *x*, *y0*, *y1* tuples, forming rows
|
|
1114
|
+
in a table. Entries for alpha are optional.
|
|
1115
|
+
|
|
1116
|
+
Example: suppose you want red to increase from 0 to 1 over
|
|
1117
|
+
the bottom half, green to do the same over the middle half,
|
|
1118
|
+
and blue over the top half. Then you would use::
|
|
1119
|
+
|
|
1120
|
+
{
|
|
1121
|
+
'red': [(0.0, 0.0, 0.0),
|
|
1122
|
+
(0.5, 1.0, 1.0),
|
|
1123
|
+
(1.0, 1.0, 1.0)],
|
|
1124
|
+
'green': [(0.0, 0.0, 0.0),
|
|
1125
|
+
(0.25, 0.0, 0.0),
|
|
1126
|
+
(0.75, 1.0, 1.0),
|
|
1127
|
+
(1.0, 1.0, 1.0)],
|
|
1128
|
+
'blue': [(0.0, 0.0, 0.0),
|
|
1129
|
+
(0.5, 0.0, 0.0),
|
|
1130
|
+
(1.0, 1.0, 1.0)]
|
|
1131
|
+
}
|
|
1132
|
+
|
|
1133
|
+
Each row in the table for a given color is a sequence of
|
|
1134
|
+
*x*, *y0*, *y1* tuples. In each sequence, *x* must increase
|
|
1135
|
+
monotonically from 0 to 1. For any input value *z* falling
|
|
1136
|
+
between *x[i]* and *x[i+1]*, the output value of a given color
|
|
1137
|
+
will be linearly interpolated between *y1[i]* and *y0[i+1]*::
|
|
1138
|
+
|
|
1139
|
+
row i: x y0 y1
|
|
1140
|
+
/
|
|
1141
|
+
/
|
|
1142
|
+
row i+1: x y0 y1
|
|
1143
|
+
|
|
1144
|
+
Hence, y0 in the first row and y1 in the last row are never used.
|
|
1145
|
+
|
|
1146
|
+
N : int
|
|
1147
|
+
The number of RGB quantization levels.
|
|
1148
|
+
gamma : float
|
|
1149
|
+
Gamma correction factor for input distribution x of the mapping.
|
|
1150
|
+
See also https://en.wikipedia.org/wiki/Gamma_correction.
|
|
1151
|
+
bad : :mpltype:`color`, default: transparent
|
|
1152
|
+
The color for invalid values (NaN or masked).
|
|
1153
|
+
|
|
1154
|
+
.. versionadded:: 3.11
|
|
1155
|
+
|
|
1156
|
+
under : :mpltype:`color`, default: color of the lowest value
|
|
1157
|
+
The color for low out-of-range values.
|
|
1158
|
+
|
|
1159
|
+
.. versionadded:: 3.11
|
|
1160
|
+
|
|
1161
|
+
over : :mpltype:`color`, default: color of the highest value
|
|
1162
|
+
The color for high out-of-range values.
|
|
1163
|
+
|
|
1164
|
+
.. versionadded:: 3.11
|
|
1165
|
+
|
|
1166
|
+
See Also
|
|
1167
|
+
--------
|
|
1168
|
+
LinearSegmentedColormap.from_list
|
|
1169
|
+
Static method; factory function for generating a smoothly-varying
|
|
1170
|
+
LinearSegmentedColormap.
|
|
1171
|
+
"""
|
|
1172
|
+
# True only if all colors in map are identical; needed for contouring.
|
|
1173
|
+
self.monochrome = False
|
|
1174
|
+
super().__init__(name, N, bad=bad, under=under, over=over)
|
|
1175
|
+
self._segmentdata = segmentdata
|
|
1176
|
+
self._gamma = gamma
|
|
1177
|
+
|
|
1178
|
+
def _init(self):
|
|
1179
|
+
# Assemble the LUT first in a local variable in case of parallel threads
|
|
1180
|
+
lut = np.ones((self.N + 3, 4), float)
|
|
1181
|
+
lut[:-3, 0] = _create_lookup_table(
|
|
1182
|
+
self.N, self._segmentdata['red'], self._gamma)
|
|
1183
|
+
lut[:-3, 1] = _create_lookup_table(
|
|
1184
|
+
self.N, self._segmentdata['green'], self._gamma)
|
|
1185
|
+
lut[:-3, 2] = _create_lookup_table(
|
|
1186
|
+
self.N, self._segmentdata['blue'], self._gamma)
|
|
1187
|
+
if 'alpha' in self._segmentdata:
|
|
1188
|
+
lut[:-3, 3] = _create_lookup_table(
|
|
1189
|
+
self.N, self._segmentdata['alpha'], 1)
|
|
1190
|
+
self._lut = lut
|
|
1191
|
+
self._isinit = True
|
|
1192
|
+
self._update_lut_extremes()
|
|
1193
|
+
|
|
1194
|
+
def set_gamma(self, gamma):
|
|
1195
|
+
"""Set a new gamma value and regenerate colormap."""
|
|
1196
|
+
self._gamma = gamma
|
|
1197
|
+
self._init()
|
|
1198
|
+
|
|
1199
|
+
@staticmethod
|
|
1200
|
+
def from_list(name, colors, N=256, gamma=1.0, *, bad=None, under=None, over=None):
|
|
1201
|
+
"""
|
|
1202
|
+
Create a `LinearSegmentedColormap` from a list of colors.
|
|
1203
|
+
|
|
1204
|
+
Parameters
|
|
1205
|
+
----------
|
|
1206
|
+
name : str
|
|
1207
|
+
The name of the colormap.
|
|
1208
|
+
colors : list of :mpltype:`color` or list of (value, color)
|
|
1209
|
+
If only colors are given, they are equidistantly mapped from the
|
|
1210
|
+
range :math:`[0, 1]`; i.e. 0 maps to ``colors[0]`` and 1 maps to
|
|
1211
|
+
``colors[-1]``.
|
|
1212
|
+
If (value, color) pairs are given, the mapping is from *value*
|
|
1213
|
+
to *color*. This can be used to divide the range unevenly. The
|
|
1214
|
+
values must increase monotonically from 0 to 1.
|
|
1215
|
+
N : int
|
|
1216
|
+
The number of RGB quantization levels.
|
|
1217
|
+
gamma : float
|
|
1218
|
+
|
|
1219
|
+
bad : :mpltype:`color`, default: transparent
|
|
1220
|
+
The color for invalid values (NaN or masked).
|
|
1221
|
+
under : :mpltype:`color`, default: color of the lowest value
|
|
1222
|
+
The color for low out-of-range values.
|
|
1223
|
+
over : :mpltype:`color`, default: color of the highest value
|
|
1224
|
+
The color for high out-of-range values.
|
|
1225
|
+
"""
|
|
1226
|
+
if not np.iterable(colors):
|
|
1227
|
+
raise ValueError('colors must be iterable')
|
|
1228
|
+
|
|
1229
|
+
try:
|
|
1230
|
+
# Assume the passed colors are a list of colors
|
|
1231
|
+
# and not a (value, color) tuple.
|
|
1232
|
+
r, g, b, a = to_rgba_array(colors).T
|
|
1233
|
+
vals = np.linspace(0, 1, len(colors))
|
|
1234
|
+
except Exception as e:
|
|
1235
|
+
# Assume the passed values are a list of
|
|
1236
|
+
# (value, color) tuples.
|
|
1237
|
+
try:
|
|
1238
|
+
_vals, _colors = itertools.zip_longest(*colors)
|
|
1239
|
+
except Exception as e2:
|
|
1240
|
+
raise e2 from e
|
|
1241
|
+
vals = np.asarray(_vals)
|
|
1242
|
+
if np.min(vals) < 0 or np.max(vals) > 1 or np.any(np.diff(vals) < 0):
|
|
1243
|
+
raise ValueError(
|
|
1244
|
+
"the values passed in the (value, color) pairs "
|
|
1245
|
+
"must increase monotonically from 0 to 1."
|
|
1246
|
+
)
|
|
1247
|
+
r, g, b, a = to_rgba_array(_colors).T
|
|
1248
|
+
|
|
1249
|
+
cdict = {
|
|
1250
|
+
"red": np.column_stack([vals, r, r]),
|
|
1251
|
+
"green": np.column_stack([vals, g, g]),
|
|
1252
|
+
"blue": np.column_stack([vals, b, b]),
|
|
1253
|
+
"alpha": np.column_stack([vals, a, a]),
|
|
1254
|
+
}
|
|
1255
|
+
|
|
1256
|
+
return LinearSegmentedColormap(name, cdict, N, gamma,
|
|
1257
|
+
bad=bad, under=under, over=over)
|
|
1258
|
+
|
|
1259
|
+
def resampled(self, lutsize):
|
|
1260
|
+
"""Return a new colormap with *lutsize* entries."""
|
|
1261
|
+
new_cmap = LinearSegmentedColormap(self.name, self._segmentdata,
|
|
1262
|
+
lutsize)
|
|
1263
|
+
new_cmap._rgba_over = self._rgba_over
|
|
1264
|
+
new_cmap._rgba_under = self._rgba_under
|
|
1265
|
+
new_cmap._rgba_bad = self._rgba_bad
|
|
1266
|
+
return new_cmap
|
|
1267
|
+
|
|
1268
|
+
# Helper ensuring picklability of the reversed cmap.
|
|
1269
|
+
@staticmethod
|
|
1270
|
+
def _reverser(func, x):
|
|
1271
|
+
return func(1 - x)
|
|
1272
|
+
|
|
1273
|
+
def reversed(self, name=None):
|
|
1274
|
+
"""
|
|
1275
|
+
Return a reversed instance of the Colormap.
|
|
1276
|
+
|
|
1277
|
+
Parameters
|
|
1278
|
+
----------
|
|
1279
|
+
name : str, optional
|
|
1280
|
+
The name for the reversed colormap. If None, the
|
|
1281
|
+
name is set to ``self.name + "_r"``.
|
|
1282
|
+
|
|
1283
|
+
Returns
|
|
1284
|
+
-------
|
|
1285
|
+
LinearSegmentedColormap
|
|
1286
|
+
The reversed colormap.
|
|
1287
|
+
"""
|
|
1288
|
+
if name is None:
|
|
1289
|
+
name = self.name + "_r"
|
|
1290
|
+
|
|
1291
|
+
# Using a partial object keeps the cmap picklable.
|
|
1292
|
+
data_r = {key: (functools.partial(self._reverser, data)
|
|
1293
|
+
if callable(data) else
|
|
1294
|
+
[(1.0 - x, y1, y0) for x, y0, y1 in reversed(data)])
|
|
1295
|
+
for key, data in self._segmentdata.items()}
|
|
1296
|
+
|
|
1297
|
+
new_cmap = LinearSegmentedColormap(name, data_r, self.N, self._gamma)
|
|
1298
|
+
# Reverse the over/under values too
|
|
1299
|
+
new_cmap._rgba_over = self._rgba_under
|
|
1300
|
+
new_cmap._rgba_under = self._rgba_over
|
|
1301
|
+
new_cmap._rgba_bad = self._rgba_bad
|
|
1302
|
+
return new_cmap
|
|
1303
|
+
|
|
1304
|
+
|
|
1305
|
+
class ListedColormap(Colormap):
|
|
1306
|
+
"""
|
|
1307
|
+
Colormap object generated from a list of colors.
|
|
1308
|
+
|
|
1309
|
+
This may be most useful when indexing directly into a colormap,
|
|
1310
|
+
but it can also be used to generate special colormaps for ordinary
|
|
1311
|
+
mapping.
|
|
1312
|
+
|
|
1313
|
+
Parameters
|
|
1314
|
+
----------
|
|
1315
|
+
colors : list of :mpltype:`color` or array
|
|
1316
|
+
Sequence of Matplotlib color specifications (color names or RGB(A)
|
|
1317
|
+
values).
|
|
1318
|
+
name : str, optional
|
|
1319
|
+
String to identify the colormap.
|
|
1320
|
+
N : int, optional
|
|
1321
|
+
Number of entries in the map. The default is *None*, in which case
|
|
1322
|
+
there is one colormap entry for each element in the list of colors.
|
|
1323
|
+
If ::
|
|
1324
|
+
|
|
1325
|
+
N < len(colors)
|
|
1326
|
+
|
|
1327
|
+
the list will be truncated at *N*. If ::
|
|
1328
|
+
|
|
1329
|
+
N > len(colors)
|
|
1330
|
+
|
|
1331
|
+
the list will be extended by repetition.
|
|
1332
|
+
|
|
1333
|
+
.. deprecated:: 3.11
|
|
1334
|
+
|
|
1335
|
+
This parameter will be removed. Please instead ensure that
|
|
1336
|
+
the list of passed colors is the required length.
|
|
1337
|
+
|
|
1338
|
+
bad : :mpltype:`color`, default: transparent
|
|
1339
|
+
The color for invalid values (NaN or masked).
|
|
1340
|
+
|
|
1341
|
+
.. versionadded:: 3.11
|
|
1342
|
+
|
|
1343
|
+
under : :mpltype:`color`, default: color of the lowest value
|
|
1344
|
+
The color for low out-of-range values.
|
|
1345
|
+
|
|
1346
|
+
.. versionadded:: 3.11
|
|
1347
|
+
|
|
1348
|
+
over : :mpltype:`color`, default: color of the highest value
|
|
1349
|
+
The color for high out-of-range values.
|
|
1350
|
+
|
|
1351
|
+
.. versionadded:: 3.11
|
|
1352
|
+
"""
|
|
1353
|
+
|
|
1354
|
+
@_api.delete_parameter(
|
|
1355
|
+
"3.11", "N",
|
|
1356
|
+
message="Passing 'N' to ListedColormap is deprecated since %(since)s "
|
|
1357
|
+
"and will be removed in %(removal)s. Please ensure the list "
|
|
1358
|
+
"of passed colors is the required length instead."
|
|
1359
|
+
)
|
|
1360
|
+
def __init__(self, colors, name='unnamed', N=None, *,
|
|
1361
|
+
bad=None, under=None, over=None):
|
|
1362
|
+
if N is None:
|
|
1363
|
+
self.colors = colors
|
|
1364
|
+
N = len(colors)
|
|
1365
|
+
else:
|
|
1366
|
+
if isinstance(colors, str):
|
|
1367
|
+
self.colors = [colors] * N
|
|
1368
|
+
elif np.iterable(colors):
|
|
1369
|
+
self.colors = list(
|
|
1370
|
+
itertools.islice(itertools.cycle(colors), N))
|
|
1371
|
+
else:
|
|
1372
|
+
try:
|
|
1373
|
+
gray = float(colors)
|
|
1374
|
+
except TypeError:
|
|
1375
|
+
pass
|
|
1376
|
+
else:
|
|
1377
|
+
self.colors = [gray] * N
|
|
1378
|
+
super().__init__(name, N, bad=bad, under=under, over=over)
|
|
1379
|
+
|
|
1380
|
+
def _init(self):
|
|
1381
|
+
# Assemble the LUT first in a local variable in case of parallel threads
|
|
1382
|
+
lut = np.zeros((self.N + 3, 4), float)
|
|
1383
|
+
lut[:-3] = to_rgba_array(self.colors)
|
|
1384
|
+
self._lut = lut
|
|
1385
|
+
self._isinit = True
|
|
1386
|
+
self._update_lut_extremes()
|
|
1387
|
+
|
|
1388
|
+
@property
|
|
1389
|
+
def monochrome(self):
|
|
1390
|
+
"""Return whether all colors in the colormap are identical."""
|
|
1391
|
+
# Replacement for the attribute *monochrome*. This ensures a consistent
|
|
1392
|
+
# response independent of the way the ListedColormap was created, which
|
|
1393
|
+
# was not the case for the manually set attribute.
|
|
1394
|
+
#
|
|
1395
|
+
# TODO: It's a separate discussion whether we need this property on
|
|
1396
|
+
# colormaps at all (at least as public API). It's a very special edge
|
|
1397
|
+
# case and we only use it for contours internally.
|
|
1398
|
+
self._ensure_inited()
|
|
1399
|
+
return self.N <= 1 or np.all(self._lut[0] == self._lut[1:self.N])
|
|
1400
|
+
|
|
1401
|
+
def resampled(self, lutsize):
|
|
1402
|
+
"""Return a new colormap with *lutsize* entries."""
|
|
1403
|
+
colors = self(np.linspace(0, 1, lutsize))
|
|
1404
|
+
new_cmap = ListedColormap(colors, name=self.name)
|
|
1405
|
+
# Keep the over/under values too
|
|
1406
|
+
new_cmap._rgba_over = self._rgba_over
|
|
1407
|
+
new_cmap._rgba_under = self._rgba_under
|
|
1408
|
+
new_cmap._rgba_bad = self._rgba_bad
|
|
1409
|
+
return new_cmap
|
|
1410
|
+
|
|
1411
|
+
def reversed(self, name=None):
|
|
1412
|
+
"""
|
|
1413
|
+
Return a reversed instance of the Colormap.
|
|
1414
|
+
|
|
1415
|
+
Parameters
|
|
1416
|
+
----------
|
|
1417
|
+
name : str, optional
|
|
1418
|
+
The name for the reversed colormap. If None, the
|
|
1419
|
+
name is set to ``self.name + "_r"``.
|
|
1420
|
+
|
|
1421
|
+
Returns
|
|
1422
|
+
-------
|
|
1423
|
+
ListedColormap
|
|
1424
|
+
A reversed instance of the colormap.
|
|
1425
|
+
"""
|
|
1426
|
+
if name is None:
|
|
1427
|
+
name = self.name + "_r"
|
|
1428
|
+
|
|
1429
|
+
colors_r = list(reversed(self.colors))
|
|
1430
|
+
new_cmap = ListedColormap(colors_r, name=name)
|
|
1431
|
+
# Reverse the over/under values too
|
|
1432
|
+
new_cmap._rgba_over = self._rgba_under
|
|
1433
|
+
new_cmap._rgba_under = self._rgba_over
|
|
1434
|
+
new_cmap._rgba_bad = self._rgba_bad
|
|
1435
|
+
return new_cmap
|
|
1436
|
+
|
|
1437
|
+
|
|
1438
|
+
class MultivarColormap:
|
|
1439
|
+
"""
|
|
1440
|
+
Class for holding multiple `~matplotlib.colors.Colormap` for use in a
|
|
1441
|
+
`~matplotlib.cm.ScalarMappable` object
|
|
1442
|
+
"""
|
|
1443
|
+
def __init__(self, colormaps, combination_mode, name='multivariate colormap'):
|
|
1444
|
+
"""
|
|
1445
|
+
Parameters
|
|
1446
|
+
----------
|
|
1447
|
+
colormaps: list or tuple of `~matplotlib.colors.Colormap` objects
|
|
1448
|
+
The individual colormaps that are combined
|
|
1449
|
+
combination_mode: str, 'sRGB_add' or 'sRGB_sub'
|
|
1450
|
+
Describe how colormaps are combined in sRGB space
|
|
1451
|
+
|
|
1452
|
+
- If 'sRGB_add' -> Mixing produces brighter colors
|
|
1453
|
+
`sRGB = sum(colors)`
|
|
1454
|
+
- If 'sRGB_sub' -> Mixing produces darker colors
|
|
1455
|
+
`sRGB = 1 - sum(1 - colors)`
|
|
1456
|
+
name : str, optional
|
|
1457
|
+
The name of the colormap family.
|
|
1458
|
+
"""
|
|
1459
|
+
self.name = name
|
|
1460
|
+
|
|
1461
|
+
if not np.iterable(colormaps) \
|
|
1462
|
+
or len(colormaps) == 1 \
|
|
1463
|
+
or isinstance(colormaps, str):
|
|
1464
|
+
raise ValueError("A MultivarColormap must have more than one colormap.")
|
|
1465
|
+
colormaps = list(colormaps) # ensure cmaps is a list, i.e. not a tuple
|
|
1466
|
+
for i, cmap in enumerate(colormaps):
|
|
1467
|
+
if isinstance(cmap, str):
|
|
1468
|
+
colormaps[i] = mpl.colormaps[cmap]
|
|
1469
|
+
elif not isinstance(cmap, Colormap):
|
|
1470
|
+
raise ValueError("colormaps must be a list of objects that subclass"
|
|
1471
|
+
" Colormap or a name found in the colormap registry.")
|
|
1472
|
+
|
|
1473
|
+
self._colormaps = colormaps
|
|
1474
|
+
_api.check_in_list(['sRGB_add', 'sRGB_sub'], combination_mode=combination_mode)
|
|
1475
|
+
self._combination_mode = combination_mode
|
|
1476
|
+
self.n_variates = len(colormaps)
|
|
1477
|
+
self._rgba_bad = (0.0, 0.0, 0.0, 0.0) # If bad, don't paint anything.
|
|
1478
|
+
|
|
1479
|
+
def __call__(self, X, alpha=None, bytes=False, clip=True):
|
|
1480
|
+
r"""
|
|
1481
|
+
Parameters
|
|
1482
|
+
----------
|
|
1483
|
+
X : tuple (X0, X1, ...) of length equal to the number of colormaps
|
|
1484
|
+
X0, X1 ...:
|
|
1485
|
+
float or int, `~numpy.ndarray` or scalar
|
|
1486
|
+
The data value(s) to convert to RGBA.
|
|
1487
|
+
For floats, *Xi...* should be in the interval ``[0.0, 1.0]`` to
|
|
1488
|
+
return the RGBA values ``X*100`` percent along the Colormap line.
|
|
1489
|
+
For integers, *Xi...* should be in the interval ``[0, self[i].N)`` to
|
|
1490
|
+
return RGBA values *indexed* from colormap [i] with index ``Xi``, where
|
|
1491
|
+
self[i] is colormap i.
|
|
1492
|
+
alpha : float or array-like or None
|
|
1493
|
+
Alpha must be a scalar between 0 and 1, a sequence of such
|
|
1494
|
+
floats with shape matching *Xi*, or None.
|
|
1495
|
+
bytes : bool, default: False
|
|
1496
|
+
If False (default), the returned RGBA values will be floats in the
|
|
1497
|
+
interval ``[0, 1]`` otherwise they will be `numpy.uint8`\s in the
|
|
1498
|
+
interval ``[0, 255]``.
|
|
1499
|
+
clip : bool, default: True
|
|
1500
|
+
If True, clip output to 0 to 1
|
|
1501
|
+
|
|
1502
|
+
Returns
|
|
1503
|
+
-------
|
|
1504
|
+
Tuple of RGBA values if X[0] is scalar, otherwise an array of
|
|
1505
|
+
RGBA values with a shape of ``X.shape + (4, )``.
|
|
1506
|
+
"""
|
|
1507
|
+
|
|
1508
|
+
if len(X) != len(self):
|
|
1509
|
+
raise ValueError(
|
|
1510
|
+
f'For the selected colormap the data must have a first dimension '
|
|
1511
|
+
f'{len(self)}, not {len(X)}')
|
|
1512
|
+
rgba, mask_bad = self[0]._get_rgba_and_mask(X[0], bytes=False)
|
|
1513
|
+
for c, xx in zip(self[1:], X[1:]):
|
|
1514
|
+
sub_rgba, sub_mask_bad = c._get_rgba_and_mask(xx, bytes=False)
|
|
1515
|
+
rgba[..., :3] += sub_rgba[..., :3] # add colors
|
|
1516
|
+
rgba[..., 3] *= sub_rgba[..., 3] # multiply alpha
|
|
1517
|
+
mask_bad |= sub_mask_bad
|
|
1518
|
+
|
|
1519
|
+
if self.combination_mode == 'sRGB_sub':
|
|
1520
|
+
rgba[..., :3] -= len(self) - 1
|
|
1521
|
+
|
|
1522
|
+
rgba[mask_bad] = self.get_bad()
|
|
1523
|
+
|
|
1524
|
+
if clip:
|
|
1525
|
+
rgba = np.clip(rgba, 0, 1)
|
|
1526
|
+
|
|
1527
|
+
if alpha is not None:
|
|
1528
|
+
if clip:
|
|
1529
|
+
alpha = np.clip(alpha, 0, 1)
|
|
1530
|
+
if np.shape(alpha) not in [(), np.shape(X[0])]:
|
|
1531
|
+
raise ValueError(
|
|
1532
|
+
f"alpha is array-like but its shape {np.shape(alpha)} does "
|
|
1533
|
+
f"not match that of X[0] {np.shape(X[0])}")
|
|
1534
|
+
rgba[..., -1] *= alpha
|
|
1535
|
+
|
|
1536
|
+
if bytes:
|
|
1537
|
+
if not clip:
|
|
1538
|
+
raise ValueError(
|
|
1539
|
+
"clip cannot be false while bytes is true"
|
|
1540
|
+
" as uint8 does not support values below 0"
|
|
1541
|
+
" or above 255.")
|
|
1542
|
+
rgba = (rgba * 255).astype('uint8')
|
|
1543
|
+
|
|
1544
|
+
if not np.iterable(X[0]):
|
|
1545
|
+
rgba = tuple(rgba)
|
|
1546
|
+
|
|
1547
|
+
return rgba
|
|
1548
|
+
|
|
1549
|
+
def copy(self):
|
|
1550
|
+
"""Return a copy of the multivarcolormap."""
|
|
1551
|
+
return self.__copy__()
|
|
1552
|
+
|
|
1553
|
+
def __copy__(self):
|
|
1554
|
+
cls = self.__class__
|
|
1555
|
+
cmapobject = cls.__new__(cls)
|
|
1556
|
+
cmapobject.__dict__.update(self.__dict__)
|
|
1557
|
+
cmapobject._colormaps = [cm.copy() for cm in self._colormaps]
|
|
1558
|
+
cmapobject._rgba_bad = np.copy(self._rgba_bad)
|
|
1559
|
+
return cmapobject
|
|
1560
|
+
|
|
1561
|
+
def __eq__(self, other):
|
|
1562
|
+
if not isinstance(other, MultivarColormap):
|
|
1563
|
+
return False
|
|
1564
|
+
if len(self) != len(other):
|
|
1565
|
+
return False
|
|
1566
|
+
for c0, c1 in zip(self, other):
|
|
1567
|
+
if c0 != c1:
|
|
1568
|
+
return False
|
|
1569
|
+
if not all(self._rgba_bad == other._rgba_bad):
|
|
1570
|
+
return False
|
|
1571
|
+
if self.combination_mode != other.combination_mode:
|
|
1572
|
+
return False
|
|
1573
|
+
return True
|
|
1574
|
+
|
|
1575
|
+
def __getitem__(self, item):
|
|
1576
|
+
return self._colormaps[item]
|
|
1577
|
+
|
|
1578
|
+
def __iter__(self):
|
|
1579
|
+
for c in self._colormaps:
|
|
1580
|
+
yield c
|
|
1581
|
+
|
|
1582
|
+
def __len__(self):
|
|
1583
|
+
return len(self._colormaps)
|
|
1584
|
+
|
|
1585
|
+
def __str__(self):
|
|
1586
|
+
return self.name
|
|
1587
|
+
|
|
1588
|
+
def get_bad(self):
|
|
1589
|
+
"""Get the color for masked values."""
|
|
1590
|
+
return np.array(self._rgba_bad)
|
|
1591
|
+
|
|
1592
|
+
def resampled(self, lutshape):
|
|
1593
|
+
"""
|
|
1594
|
+
Return a new colormap with *lutshape* entries.
|
|
1595
|
+
|
|
1596
|
+
Parameters
|
|
1597
|
+
----------
|
|
1598
|
+
lutshape : tuple of (`int`, `None`)
|
|
1599
|
+
The tuple must have a length matching the number of variates.
|
|
1600
|
+
For each element in the tuple, if `int`, the corresponding colorbar
|
|
1601
|
+
is resampled, if `None`, the corresponding colorbar is not resampled.
|
|
1602
|
+
|
|
1603
|
+
Returns
|
|
1604
|
+
-------
|
|
1605
|
+
MultivarColormap
|
|
1606
|
+
"""
|
|
1607
|
+
|
|
1608
|
+
if not np.iterable(lutshape) or len(lutshape) != len(self):
|
|
1609
|
+
raise ValueError(f"lutshape must be of length {len(self)}")
|
|
1610
|
+
new_cmap = self.copy()
|
|
1611
|
+
for i, s in enumerate(lutshape):
|
|
1612
|
+
if s is not None:
|
|
1613
|
+
new_cmap._colormaps[i] = self[i].resampled(s)
|
|
1614
|
+
return new_cmap
|
|
1615
|
+
|
|
1616
|
+
def with_extremes(self, *, bad=None, under=None, over=None):
|
|
1617
|
+
"""
|
|
1618
|
+
Return a copy of the `MultivarColormap` with modified out-of-range attributes.
|
|
1619
|
+
|
|
1620
|
+
The *bad* keyword modifies the copied `MultivarColormap` while *under* and
|
|
1621
|
+
*over* modifies the attributes of the copied component colormaps.
|
|
1622
|
+
Note that *under* and *over* colors are subject to the mixing rules determined
|
|
1623
|
+
by the *combination_mode*.
|
|
1624
|
+
|
|
1625
|
+
Parameters
|
|
1626
|
+
----------
|
|
1627
|
+
bad: :mpltype:`color`, default: None
|
|
1628
|
+
If Matplotlib color, the bad value is set accordingly in the copy
|
|
1629
|
+
|
|
1630
|
+
under tuple of :mpltype:`color`, default: None
|
|
1631
|
+
If tuple, the `under` value of each component is set with the values
|
|
1632
|
+
from the tuple.
|
|
1633
|
+
|
|
1634
|
+
over tuple of :mpltype:`color`, default: None
|
|
1635
|
+
If tuple, the `over` value of each component is set with the values
|
|
1636
|
+
from the tuple.
|
|
1637
|
+
|
|
1638
|
+
Returns
|
|
1639
|
+
-------
|
|
1640
|
+
MultivarColormap
|
|
1641
|
+
copy of self with attributes set
|
|
1642
|
+
|
|
1643
|
+
"""
|
|
1644
|
+
new_cm = self.copy()
|
|
1645
|
+
if bad is not None:
|
|
1646
|
+
new_cm._rgba_bad = to_rgba(bad)
|
|
1647
|
+
if under is not None:
|
|
1648
|
+
if not np.iterable(under) or len(under) != len(new_cm):
|
|
1649
|
+
raise ValueError("*under* must contain a color for each scalar colormap"
|
|
1650
|
+
f" i.e. be of length {len(new_cm)}.")
|
|
1651
|
+
else:
|
|
1652
|
+
for c, b in zip(new_cm, under):
|
|
1653
|
+
# in-place change is ok, since we've just created c as a copy
|
|
1654
|
+
c._set_extremes(under=b)
|
|
1655
|
+
if over is not None:
|
|
1656
|
+
if not np.iterable(over) or len(over) != len(new_cm):
|
|
1657
|
+
raise ValueError("*over* must contain a color for each scalar colormap"
|
|
1658
|
+
f" i.e. be of length {len(new_cm)}.")
|
|
1659
|
+
else:
|
|
1660
|
+
for c, b in zip(new_cm, over):
|
|
1661
|
+
# in-place change is ok, since we've just created c as a copy
|
|
1662
|
+
c._set_extremes(over=b)
|
|
1663
|
+
return new_cm
|
|
1664
|
+
|
|
1665
|
+
@property
|
|
1666
|
+
def combination_mode(self):
|
|
1667
|
+
return self._combination_mode
|
|
1668
|
+
|
|
1669
|
+
def _repr_png_(self):
|
|
1670
|
+
"""Generate a PNG representation of the Colormap."""
|
|
1671
|
+
X = np.tile(np.linspace(0, 1, _REPR_PNG_SIZE[0]),
|
|
1672
|
+
(_REPR_PNG_SIZE[1], 1))
|
|
1673
|
+
pixels = np.zeros((_REPR_PNG_SIZE[1]*len(self), _REPR_PNG_SIZE[0], 4),
|
|
1674
|
+
dtype=np.uint8)
|
|
1675
|
+
for i, c in enumerate(self):
|
|
1676
|
+
pixels[i*_REPR_PNG_SIZE[1]:(i+1)*_REPR_PNG_SIZE[1], :] = c(X, bytes=True)
|
|
1677
|
+
png_bytes = io.BytesIO()
|
|
1678
|
+
title = self.name + ' multivariate colormap'
|
|
1679
|
+
author = f'Matplotlib v{mpl.__version__}, https://matplotlib.org'
|
|
1680
|
+
_save_repr_png(png_bytes, pixels, title, author)
|
|
1681
|
+
return png_bytes.getvalue()
|
|
1682
|
+
|
|
1683
|
+
def _repr_html_(self):
|
|
1684
|
+
"""Generate an HTML representation of the MultivarColormap."""
|
|
1685
|
+
return ''.join([c._repr_html_() for c in self._colormaps])
|
|
1686
|
+
|
|
1687
|
+
|
|
1688
|
+
class BivarColormap:
|
|
1689
|
+
"""
|
|
1690
|
+
Base class for all bivariate to RGBA mappings.
|
|
1691
|
+
|
|
1692
|
+
Designed as a drop-in replacement for Colormap when using a 2D
|
|
1693
|
+
lookup table. To be used with `~matplotlib.cm.ScalarMappable`.
|
|
1694
|
+
"""
|
|
1695
|
+
|
|
1696
|
+
def __init__(self, N=256, M=256, shape='square', origin=(0, 0),
|
|
1697
|
+
name='bivariate colormap'):
|
|
1698
|
+
"""
|
|
1699
|
+
Parameters
|
|
1700
|
+
----------
|
|
1701
|
+
N : int, default: 256
|
|
1702
|
+
The number of RGB quantization levels along the first axis.
|
|
1703
|
+
M : int, default: 256
|
|
1704
|
+
The number of RGB quantization levels along the second axis.
|
|
1705
|
+
shape : {'square', 'circle', 'ignore', 'circleignore'}
|
|
1706
|
+
|
|
1707
|
+
- 'square' each variate is clipped to [0,1] independently
|
|
1708
|
+
- 'circle' the variates are clipped radially to the center
|
|
1709
|
+
of the colormap, and a circular mask is applied when the colormap
|
|
1710
|
+
is displayed
|
|
1711
|
+
- 'ignore' the variates are not clipped, but instead assigned the
|
|
1712
|
+
'outside' color
|
|
1713
|
+
- 'circleignore' a circular mask is applied, but the data is not
|
|
1714
|
+
clipped and instead assigned the 'outside' color
|
|
1715
|
+
|
|
1716
|
+
origin : (float, float), default: (0,0)
|
|
1717
|
+
The relative origin of the colormap. Typically (0, 0), for colormaps
|
|
1718
|
+
that are linear on both axis, and (.5, .5) for circular colormaps.
|
|
1719
|
+
Used when getting 1D colormaps from 2D colormaps.
|
|
1720
|
+
name : str, optional
|
|
1721
|
+
The name of the colormap.
|
|
1722
|
+
"""
|
|
1723
|
+
|
|
1724
|
+
self.name = name
|
|
1725
|
+
self.N = int(N) # ensure that N is always int
|
|
1726
|
+
self.M = int(M)
|
|
1727
|
+
_api.check_in_list(['square', 'circle', 'ignore', 'circleignore'], shape=shape)
|
|
1728
|
+
self._shape = shape
|
|
1729
|
+
self._rgba_bad = (0.0, 0.0, 0.0, 0.0) # If bad, don't paint anything.
|
|
1730
|
+
self._rgba_outside = (1.0, 0.0, 1.0, 1.0)
|
|
1731
|
+
self._isinit = False
|
|
1732
|
+
self.n_variates = 2
|
|
1733
|
+
self._origin = (float(origin[0]), float(origin[1]))
|
|
1734
|
+
'''#: When this colormap exists on a scalar mappable and colorbar_extend
|
|
1735
|
+
#: is not False, colorbar creation will pick up ``colorbar_extend`` as
|
|
1736
|
+
#: the default value for the ``extend`` keyword in the
|
|
1737
|
+
#: `matplotlib.colorbar.Colorbar` constructor.
|
|
1738
|
+
self.colorbar_extend = False'''
|
|
1739
|
+
|
|
1740
|
+
def __call__(self, X, alpha=None, bytes=False):
|
|
1741
|
+
r"""
|
|
1742
|
+
Parameters
|
|
1743
|
+
----------
|
|
1744
|
+
X : tuple (X0, X1), X0 and X1: float or int or array-like
|
|
1745
|
+
The data value(s) to convert to RGBA.
|
|
1746
|
+
|
|
1747
|
+
- For floats, *X* should be in the interval ``[0.0, 1.0]`` to
|
|
1748
|
+
return the RGBA values ``X*100`` percent along the Colormap.
|
|
1749
|
+
- For integers, *X* should be in the interval ``[0, Colormap.N)`` to
|
|
1750
|
+
return RGBA values *indexed* from the Colormap with index ``X``.
|
|
1751
|
+
|
|
1752
|
+
alpha : float or array-like or None, default: None
|
|
1753
|
+
Alpha must be a scalar between 0 and 1, a sequence of such
|
|
1754
|
+
floats with shape matching X0, or None.
|
|
1755
|
+
bytes : bool, default: False
|
|
1756
|
+
If False (default), the returned RGBA values will be floats in the
|
|
1757
|
+
interval ``[0, 1]`` otherwise they will be `numpy.uint8`\s in the
|
|
1758
|
+
interval ``[0, 255]``.
|
|
1759
|
+
|
|
1760
|
+
Returns
|
|
1761
|
+
-------
|
|
1762
|
+
Tuple of RGBA values if X is scalar, otherwise an array of
|
|
1763
|
+
RGBA values with a shape of ``X.shape + (4, )``.
|
|
1764
|
+
"""
|
|
1765
|
+
|
|
1766
|
+
if len(X) != 2:
|
|
1767
|
+
raise ValueError(
|
|
1768
|
+
f'For a `BivarColormap` the data must have a first dimension '
|
|
1769
|
+
f'2, not {len(X)}')
|
|
1770
|
+
|
|
1771
|
+
if not self._isinit:
|
|
1772
|
+
self._init()
|
|
1773
|
+
|
|
1774
|
+
X0 = np.ma.array(X[0], copy=True)
|
|
1775
|
+
X1 = np.ma.array(X[1], copy=True)
|
|
1776
|
+
# clip to shape of colormap, circle square, etc.
|
|
1777
|
+
self._clip((X0, X1))
|
|
1778
|
+
|
|
1779
|
+
# Native byteorder is faster.
|
|
1780
|
+
if not X0.dtype.isnative:
|
|
1781
|
+
X0 = X0.byteswap().view(X0.dtype.newbyteorder())
|
|
1782
|
+
if not X1.dtype.isnative:
|
|
1783
|
+
X1 = X1.byteswap().view(X1.dtype.newbyteorder())
|
|
1784
|
+
|
|
1785
|
+
if X0.dtype.kind == "f":
|
|
1786
|
+
X0 *= self.N
|
|
1787
|
+
# xa == 1 (== N after multiplication) is not out of range.
|
|
1788
|
+
X0[X0 == self.N] = self.N - 1
|
|
1789
|
+
|
|
1790
|
+
if X1.dtype.kind == "f":
|
|
1791
|
+
X1 *= self.M
|
|
1792
|
+
# xa == 1 (== N after multiplication) is not out of range.
|
|
1793
|
+
X1[X1 == self.M] = self.M - 1
|
|
1794
|
+
|
|
1795
|
+
# Pre-compute the masks before casting to int (which can truncate)
|
|
1796
|
+
mask_outside = (X0 < 0) | (X1 < 0) | (X0 >= self.N) | (X1 >= self.M)
|
|
1797
|
+
# If input was masked, get the bad mask from it; else mask out nans.
|
|
1798
|
+
mask_bad_0 = X0.mask if np.ma.is_masked(X0) else np.isnan(X0)
|
|
1799
|
+
mask_bad_1 = X1.mask if np.ma.is_masked(X1) else np.isnan(X1)
|
|
1800
|
+
mask_bad = mask_bad_0 | mask_bad_1
|
|
1801
|
+
|
|
1802
|
+
with np.errstate(invalid="ignore"):
|
|
1803
|
+
# We need this cast for unsigned ints as well as floats
|
|
1804
|
+
X0 = X0.astype(int)
|
|
1805
|
+
X1 = X1.astype(int)
|
|
1806
|
+
|
|
1807
|
+
# Set masked values to zero
|
|
1808
|
+
# The corresponding rgb values will be replaced later
|
|
1809
|
+
for X_part in [X0, X1]:
|
|
1810
|
+
X_part[mask_outside] = 0
|
|
1811
|
+
X_part[mask_bad] = 0
|
|
1812
|
+
|
|
1813
|
+
rgba = self._lut[X0, X1]
|
|
1814
|
+
if np.isscalar(X[0]):
|
|
1815
|
+
rgba = np.copy(rgba)
|
|
1816
|
+
rgba[mask_outside] = self._rgba_outside
|
|
1817
|
+
rgba[mask_bad] = self._rgba_bad
|
|
1818
|
+
if bytes:
|
|
1819
|
+
rgba = (rgba * 255).astype(np.uint8)
|
|
1820
|
+
if alpha is not None:
|
|
1821
|
+
alpha = np.clip(alpha, 0, 1)
|
|
1822
|
+
if bytes:
|
|
1823
|
+
alpha *= 255 # Will be cast to uint8 upon assignment.
|
|
1824
|
+
if np.shape(alpha) not in [(), np.shape(X0)]:
|
|
1825
|
+
raise ValueError(
|
|
1826
|
+
f"alpha is array-like but its shape {np.shape(alpha)} does "
|
|
1827
|
+
f"not match that of X[0] {np.shape(X0)}")
|
|
1828
|
+
rgba[..., -1] = alpha
|
|
1829
|
+
# If the "bad" color is all zeros, then ignore alpha input.
|
|
1830
|
+
if (np.array(self._rgba_bad) == 0).all():
|
|
1831
|
+
rgba[mask_bad] = (0, 0, 0, 0)
|
|
1832
|
+
|
|
1833
|
+
if not np.iterable(X[0]):
|
|
1834
|
+
rgba = tuple(rgba)
|
|
1835
|
+
return rgba
|
|
1836
|
+
|
|
1837
|
+
@property
|
|
1838
|
+
def lut(self):
|
|
1839
|
+
"""
|
|
1840
|
+
For external access to the lut, i.e. for displaying the cmap.
|
|
1841
|
+
For circular colormaps this returns a lut with a circular mask.
|
|
1842
|
+
|
|
1843
|
+
Internal functions (such as to_rgb()) should use _lut
|
|
1844
|
+
which stores the lut without a circular mask
|
|
1845
|
+
A lut without the circular mask is needed in to_rgb() because the
|
|
1846
|
+
conversion from floats to ints results in some some pixel-requests
|
|
1847
|
+
just outside of the circular mask
|
|
1848
|
+
|
|
1849
|
+
"""
|
|
1850
|
+
if not self._isinit:
|
|
1851
|
+
self._init()
|
|
1852
|
+
lut = np.copy(self._lut)
|
|
1853
|
+
if self.shape == 'circle' or self.shape == 'circleignore':
|
|
1854
|
+
n = np.linspace(-1, 1, self.N)
|
|
1855
|
+
m = np.linspace(-1, 1, self.M)
|
|
1856
|
+
radii_sqr = (n**2)[:, np.newaxis] + (m**2)[np.newaxis, :]
|
|
1857
|
+
mask_outside = radii_sqr > 1
|
|
1858
|
+
lut[mask_outside, 3] = 0
|
|
1859
|
+
return lut
|
|
1860
|
+
|
|
1861
|
+
def __copy__(self):
|
|
1862
|
+
cls = self.__class__
|
|
1863
|
+
cmapobject = cls.__new__(cls)
|
|
1864
|
+
cmapobject.__dict__.update(self.__dict__)
|
|
1865
|
+
|
|
1866
|
+
cmapobject._rgba_outside = np.copy(self._rgba_outside)
|
|
1867
|
+
cmapobject._rgba_bad = np.copy(self._rgba_bad)
|
|
1868
|
+
cmapobject._shape = self.shape
|
|
1869
|
+
if self._isinit:
|
|
1870
|
+
cmapobject._lut = np.copy(self._lut)
|
|
1871
|
+
return cmapobject
|
|
1872
|
+
|
|
1873
|
+
def __eq__(self, other):
|
|
1874
|
+
if not isinstance(other, BivarColormap):
|
|
1875
|
+
return False
|
|
1876
|
+
# To compare lookup tables the Colormaps have to be initialized
|
|
1877
|
+
if not self._isinit:
|
|
1878
|
+
self._init()
|
|
1879
|
+
if not other._isinit:
|
|
1880
|
+
other._init()
|
|
1881
|
+
if not np.array_equal(self._lut, other._lut):
|
|
1882
|
+
return False
|
|
1883
|
+
if not np.array_equal(self._rgba_bad, other._rgba_bad):
|
|
1884
|
+
return False
|
|
1885
|
+
if not np.array_equal(self._rgba_outside, other._rgba_outside):
|
|
1886
|
+
return False
|
|
1887
|
+
if self.shape != other.shape:
|
|
1888
|
+
return False
|
|
1889
|
+
return True
|
|
1890
|
+
|
|
1891
|
+
def get_bad(self):
|
|
1892
|
+
"""Get the color for masked values."""
|
|
1893
|
+
return self._rgba_bad
|
|
1894
|
+
|
|
1895
|
+
def get_outside(self):
|
|
1896
|
+
"""Get the color for out-of-range values."""
|
|
1897
|
+
return self._rgba_outside
|
|
1898
|
+
|
|
1899
|
+
def resampled(self, lutshape, transposed=False):
|
|
1900
|
+
"""
|
|
1901
|
+
Return a new colormap with *lutshape* entries.
|
|
1902
|
+
|
|
1903
|
+
Note that this function does not move the origin.
|
|
1904
|
+
|
|
1905
|
+
Parameters
|
|
1906
|
+
----------
|
|
1907
|
+
lutshape : tuple of ints or None
|
|
1908
|
+
The tuple must be of length 2, and each entry is either an int or None.
|
|
1909
|
+
|
|
1910
|
+
- If an int, the corresponding axis is resampled.
|
|
1911
|
+
- If negative the corresponding axis is resampled in reverse
|
|
1912
|
+
- If -1, the axis is inverted
|
|
1913
|
+
- If 1 or None, the corresponding axis is not resampled.
|
|
1914
|
+
|
|
1915
|
+
transposed : bool, default: False
|
|
1916
|
+
if True, the axes are swapped after resampling
|
|
1917
|
+
|
|
1918
|
+
Returns
|
|
1919
|
+
-------
|
|
1920
|
+
BivarColormap
|
|
1921
|
+
"""
|
|
1922
|
+
|
|
1923
|
+
if not np.iterable(lutshape) or len(lutshape) != 2:
|
|
1924
|
+
raise ValueError("lutshape must be of length 2")
|
|
1925
|
+
lutshape = [lutshape[0], lutshape[1]]
|
|
1926
|
+
if lutshape[0] is None or lutshape[0] == 1:
|
|
1927
|
+
lutshape[0] = self.N
|
|
1928
|
+
if lutshape[1] is None or lutshape[1] == 1:
|
|
1929
|
+
lutshape[1] = self.M
|
|
1930
|
+
|
|
1931
|
+
inverted = [False, False]
|
|
1932
|
+
if lutshape[0] < 0:
|
|
1933
|
+
inverted[0] = True
|
|
1934
|
+
lutshape[0] = -lutshape[0]
|
|
1935
|
+
if lutshape[0] == 1:
|
|
1936
|
+
lutshape[0] = self.N
|
|
1937
|
+
if lutshape[1] < 0:
|
|
1938
|
+
inverted[1] = True
|
|
1939
|
+
lutshape[1] = -lutshape[1]
|
|
1940
|
+
if lutshape[1] == 1:
|
|
1941
|
+
lutshape[1] = self.M
|
|
1942
|
+
x_0, x_1 = np.mgrid[0:1:(lutshape[0] * 1j), 0:1:(lutshape[1] * 1j)]
|
|
1943
|
+
if inverted[0]:
|
|
1944
|
+
x_0 = x_0[::-1, :]
|
|
1945
|
+
if inverted[1]:
|
|
1946
|
+
x_1 = x_1[:, ::-1]
|
|
1947
|
+
|
|
1948
|
+
# we need to use shape = 'square' while resampling the colormap.
|
|
1949
|
+
# if the colormap has shape = 'circle' we would otherwise get *outside* in the
|
|
1950
|
+
# resampled colormap
|
|
1951
|
+
shape_memory = self._shape
|
|
1952
|
+
self._shape = 'square'
|
|
1953
|
+
if transposed:
|
|
1954
|
+
new_lut = self((x_1, x_0))
|
|
1955
|
+
new_cmap = BivarColormapFromImage(new_lut, name=self.name,
|
|
1956
|
+
shape=shape_memory,
|
|
1957
|
+
origin=self.origin[::-1])
|
|
1958
|
+
else:
|
|
1959
|
+
new_lut = self((x_0, x_1))
|
|
1960
|
+
new_cmap = BivarColormapFromImage(new_lut, name=self.name,
|
|
1961
|
+
shape=shape_memory,
|
|
1962
|
+
origin=self.origin)
|
|
1963
|
+
self._shape = shape_memory
|
|
1964
|
+
|
|
1965
|
+
new_cmap._rgba_bad = self._rgba_bad
|
|
1966
|
+
new_cmap._rgba_outside = self._rgba_outside
|
|
1967
|
+
return new_cmap
|
|
1968
|
+
|
|
1969
|
+
def reversed(self, axis_0=True, axis_1=True):
|
|
1970
|
+
"""
|
|
1971
|
+
Reverses both or one of the axis.
|
|
1972
|
+
"""
|
|
1973
|
+
r_0 = -1 if axis_0 else 1
|
|
1974
|
+
r_1 = -1 if axis_1 else 1
|
|
1975
|
+
return self.resampled((r_0, r_1))
|
|
1976
|
+
|
|
1977
|
+
def transposed(self):
|
|
1978
|
+
"""
|
|
1979
|
+
Transposes the colormap by swapping the order of the axis
|
|
1980
|
+
"""
|
|
1981
|
+
return self.resampled((None, None), transposed=True)
|
|
1982
|
+
|
|
1983
|
+
def with_extremes(self, *, bad=None, outside=None, shape=None, origin=None):
|
|
1984
|
+
"""
|
|
1985
|
+
Return a copy of the `BivarColormap` with modified attributes.
|
|
1986
|
+
|
|
1987
|
+
Note that the *outside* color is only relevant if `shape` = 'ignore'
|
|
1988
|
+
or 'circleignore'.
|
|
1989
|
+
|
|
1990
|
+
Parameters
|
|
1991
|
+
----------
|
|
1992
|
+
bad : :mpltype:`color`, optional
|
|
1993
|
+
If given, the *bad* value is set accordingly in the copy.
|
|
1994
|
+
|
|
1995
|
+
outside : :mpltype:`color`, optional
|
|
1996
|
+
If given and shape is 'ignore' or 'circleignore', values
|
|
1997
|
+
*outside* the colormap are colored accordingly in the copy.
|
|
1998
|
+
|
|
1999
|
+
shape : {'square', 'circle', 'ignore', 'circleignore'}
|
|
2000
|
+
|
|
2001
|
+
- If 'square' each variate is clipped to [0,1] independently
|
|
2002
|
+
- If 'circle' the variates are clipped radially to the center
|
|
2003
|
+
of the colormap, and a circular mask is applied when the colormap
|
|
2004
|
+
is displayed
|
|
2005
|
+
- If 'ignore' the variates are not clipped, but instead assigned the
|
|
2006
|
+
*outside* color
|
|
2007
|
+
- If 'circleignore' a circular mask is applied, but the data is not
|
|
2008
|
+
clipped and instead assigned the *outside* color
|
|
2009
|
+
|
|
2010
|
+
origin : (float, float)
|
|
2011
|
+
The relative origin of the colormap. Typically (0, 0), for colormaps
|
|
2012
|
+
that are linear on both axis, and (.5, .5) for circular colormaps.
|
|
2013
|
+
Used when getting 1D colormaps from 2D colormaps.
|
|
2014
|
+
|
|
2015
|
+
Returns
|
|
2016
|
+
-------
|
|
2017
|
+
BivarColormap
|
|
2018
|
+
copy of self with attributes set
|
|
2019
|
+
"""
|
|
2020
|
+
new_cm = self.copy()
|
|
2021
|
+
if bad is not None:
|
|
2022
|
+
new_cm._rgba_bad = to_rgba(bad)
|
|
2023
|
+
if outside is not None:
|
|
2024
|
+
new_cm._rgba_outside = to_rgba(outside)
|
|
2025
|
+
if shape is not None:
|
|
2026
|
+
_api.check_in_list(['square', 'circle', 'ignore', 'circleignore'],
|
|
2027
|
+
shape=shape)
|
|
2028
|
+
new_cm._shape = shape
|
|
2029
|
+
if origin is not None:
|
|
2030
|
+
new_cm._origin = (float(origin[0]), float(origin[1]))
|
|
2031
|
+
|
|
2032
|
+
return new_cm
|
|
2033
|
+
|
|
2034
|
+
def _init(self):
|
|
2035
|
+
"""Generate the lookup table, ``self._lut``."""
|
|
2036
|
+
raise NotImplementedError("Abstract class only")
|
|
2037
|
+
|
|
2038
|
+
@property
|
|
2039
|
+
def shape(self):
|
|
2040
|
+
return self._shape
|
|
2041
|
+
|
|
2042
|
+
@property
|
|
2043
|
+
def origin(self):
|
|
2044
|
+
return self._origin
|
|
2045
|
+
|
|
2046
|
+
def _clip(self, X):
|
|
2047
|
+
"""
|
|
2048
|
+
For internal use when applying a BivarColormap to data.
|
|
2049
|
+
i.e. cm.ScalarMappable().to_rgba()
|
|
2050
|
+
Clips X[0] and X[1] according to 'self.shape'.
|
|
2051
|
+
X is modified in-place.
|
|
2052
|
+
|
|
2053
|
+
Parameters
|
|
2054
|
+
----------
|
|
2055
|
+
X: np.array
|
|
2056
|
+
array of floats or ints to be clipped
|
|
2057
|
+
shape : {'square', 'circle', 'ignore', 'circleignore'}
|
|
2058
|
+
|
|
2059
|
+
- If 'square' each variate is clipped to [0,1] independently
|
|
2060
|
+
- If 'circle' the variates are clipped radially to the center
|
|
2061
|
+
of the colormap.
|
|
2062
|
+
It is assumed that a circular mask is applied when the colormap
|
|
2063
|
+
is displayed
|
|
2064
|
+
- If 'ignore' the variates are not clipped, but instead assigned the
|
|
2065
|
+
'outside' color
|
|
2066
|
+
- If 'circleignore' a circular mask is applied, but the data is not clipped
|
|
2067
|
+
and instead assigned the 'outside' color
|
|
2068
|
+
|
|
2069
|
+
"""
|
|
2070
|
+
if self.shape == 'square':
|
|
2071
|
+
for X_part, mx in zip(X, (self.N, self.M)):
|
|
2072
|
+
X_part[X_part < 0] = 0
|
|
2073
|
+
if X_part.dtype.kind == "f":
|
|
2074
|
+
X_part[X_part > 1] = 1
|
|
2075
|
+
else:
|
|
2076
|
+
X_part[X_part >= mx] = mx - 1
|
|
2077
|
+
|
|
2078
|
+
elif self.shape == 'ignore':
|
|
2079
|
+
for X_part, mx in zip(X, (self.N, self.M)):
|
|
2080
|
+
X_part[X_part < 0] = -1
|
|
2081
|
+
if X_part.dtype.kind == "f":
|
|
2082
|
+
X_part[X_part > 1] = -1
|
|
2083
|
+
else:
|
|
2084
|
+
X_part[X_part >= mx] = -1
|
|
2085
|
+
|
|
2086
|
+
elif self.shape == 'circle' or self.shape == 'circleignore':
|
|
2087
|
+
for X_part in X:
|
|
2088
|
+
if X_part.dtype.kind != "f":
|
|
2089
|
+
raise NotImplementedError(
|
|
2090
|
+
"Circular bivariate colormaps are only"
|
|
2091
|
+
" implemented for use with with floats")
|
|
2092
|
+
radii_sqr = (X[0] - 0.5)**2 + (X[1] - 0.5)**2
|
|
2093
|
+
mask_outside = radii_sqr > 0.25
|
|
2094
|
+
if self.shape == 'circle':
|
|
2095
|
+
overextend = 2 * np.sqrt(radii_sqr[mask_outside])
|
|
2096
|
+
X[0][mask_outside] = (X[0][mask_outside] - 0.5) / overextend + 0.5
|
|
2097
|
+
X[1][mask_outside] = (X[1][mask_outside] - 0.5) / overextend + 0.5
|
|
2098
|
+
else:
|
|
2099
|
+
X[0][mask_outside] = -1
|
|
2100
|
+
X[1][mask_outside] = -1
|
|
2101
|
+
|
|
2102
|
+
def __getitem__(self, item):
|
|
2103
|
+
"""Creates and returns a colorbar along the selected axis"""
|
|
2104
|
+
if not self._isinit:
|
|
2105
|
+
self._init()
|
|
2106
|
+
extremes = (
|
|
2107
|
+
dict(bad=self._rgba_bad, over=self._rgba_outside, under=self._rgba_outside)
|
|
2108
|
+
if self.shape in ['ignore', 'circleignore']
|
|
2109
|
+
else dict(bad=self._rgba_bad)
|
|
2110
|
+
)
|
|
2111
|
+
if item == 0:
|
|
2112
|
+
origin_1_as_int = int(self._origin[1]*self.M)
|
|
2113
|
+
if origin_1_as_int > self.M-1:
|
|
2114
|
+
origin_1_as_int = self.M-1
|
|
2115
|
+
one_d_lut = self._lut[:, origin_1_as_int]
|
|
2116
|
+
new_cmap = ListedColormap(one_d_lut, name=f'{self.name}_0', **extremes)
|
|
2117
|
+
|
|
2118
|
+
elif item == 1:
|
|
2119
|
+
origin_0_as_int = int(self._origin[0]*self.N)
|
|
2120
|
+
if origin_0_as_int > self.N-1:
|
|
2121
|
+
origin_0_as_int = self.N-1
|
|
2122
|
+
one_d_lut = self._lut[origin_0_as_int, :]
|
|
2123
|
+
new_cmap = ListedColormap(one_d_lut, name=f'{self.name}_1', **extremes)
|
|
2124
|
+
else:
|
|
2125
|
+
raise KeyError(f"only 0 or 1 are"
|
|
2126
|
+
f" valid keys for BivarColormap, not {item!r}")
|
|
2127
|
+
return new_cmap
|
|
2128
|
+
|
|
2129
|
+
def _repr_png_(self):
|
|
2130
|
+
"""Generate a PNG representation of the BivarColormap."""
|
|
2131
|
+
if not self._isinit:
|
|
2132
|
+
self._init()
|
|
2133
|
+
pixels = self.lut
|
|
2134
|
+
if pixels.shape[0] < _BIVAR_REPR_PNG_SIZE:
|
|
2135
|
+
pixels = np.repeat(pixels,
|
|
2136
|
+
repeats=_BIVAR_REPR_PNG_SIZE//pixels.shape[0],
|
|
2137
|
+
axis=0)[:256, :]
|
|
2138
|
+
if pixels.shape[1] < _BIVAR_REPR_PNG_SIZE:
|
|
2139
|
+
pixels = np.repeat(pixels,
|
|
2140
|
+
repeats=_BIVAR_REPR_PNG_SIZE//pixels.shape[1],
|
|
2141
|
+
axis=1)[:, :256]
|
|
2142
|
+
pixels = (pixels[::-1, :, :] * 255).astype(np.uint8)
|
|
2143
|
+
png_bytes = io.BytesIO()
|
|
2144
|
+
title = self.name + ' BivarColormap'
|
|
2145
|
+
author = f'Matplotlib v{mpl.__version__}, https://matplotlib.org'
|
|
2146
|
+
_save_repr_png(png_bytes, pixels, title, author)
|
|
2147
|
+
return png_bytes.getvalue()
|
|
2148
|
+
|
|
2149
|
+
def _repr_html_(self):
|
|
2150
|
+
"""Generate an HTML representation of the Colormap."""
|
|
2151
|
+
png_bytes = self._repr_png_()
|
|
2152
|
+
png_base64 = base64.b64encode(png_bytes).decode('ascii')
|
|
2153
|
+
def color_block(color):
|
|
2154
|
+
hex_color = to_hex(color, keep_alpha=True)
|
|
2155
|
+
return (f'<div title="{hex_color}" '
|
|
2156
|
+
'style="display: inline-block; '
|
|
2157
|
+
'width: 1em; height: 1em; '
|
|
2158
|
+
'margin: 0; '
|
|
2159
|
+
'vertical-align: middle; '
|
|
2160
|
+
'border: 1px solid #555; '
|
|
2161
|
+
f'background-color: {hex_color};"></div>')
|
|
2162
|
+
|
|
2163
|
+
return ('<div style="vertical-align: middle;">'
|
|
2164
|
+
f'<strong>{self.name}</strong> '
|
|
2165
|
+
'</div>'
|
|
2166
|
+
'<div class="cmap"><img '
|
|
2167
|
+
f'alt="{self.name} BivarColormap" '
|
|
2168
|
+
f'title="{self.name}" '
|
|
2169
|
+
'style="border: 1px solid #555;" '
|
|
2170
|
+
f'src="data:image/png;base64,{png_base64}"></div>'
|
|
2171
|
+
'<div style="vertical-align: middle; '
|
|
2172
|
+
f'max-width: {_BIVAR_REPR_PNG_SIZE+2}px; '
|
|
2173
|
+
'display: flex; justify-content: space-between;">'
|
|
2174
|
+
'<div style="float: left;">'
|
|
2175
|
+
f'{color_block(self.get_outside())} outside'
|
|
2176
|
+
'</div>'
|
|
2177
|
+
'<div style="float: right;">'
|
|
2178
|
+
f'bad {color_block(self.get_bad())}'
|
|
2179
|
+
'</div></div>')
|
|
2180
|
+
|
|
2181
|
+
def copy(self):
|
|
2182
|
+
"""Return a copy of the colormap."""
|
|
2183
|
+
return self.__copy__()
|
|
2184
|
+
|
|
2185
|
+
|
|
2186
|
+
class SegmentedBivarColormap(BivarColormap):
|
|
2187
|
+
"""
|
|
2188
|
+
BivarColormap object generated by supersampling a regular grid.
|
|
2189
|
+
|
|
2190
|
+
Parameters
|
|
2191
|
+
----------
|
|
2192
|
+
patch : np.array
|
|
2193
|
+
Patch is required to have a shape (k, l, 3), and will get supersampled
|
|
2194
|
+
to a lut of shape (N, N, 4).
|
|
2195
|
+
N : int
|
|
2196
|
+
The number of RGB quantization levels along each axis.
|
|
2197
|
+
shape : {'square', 'circle', 'ignore', 'circleignore'}
|
|
2198
|
+
|
|
2199
|
+
- If 'square' each variate is clipped to [0,1] independently
|
|
2200
|
+
- If 'circle' the variates are clipped radially to the center
|
|
2201
|
+
of the colormap, and a circular mask is applied when the colormap
|
|
2202
|
+
is displayed
|
|
2203
|
+
- If 'ignore' the variates are not clipped, but instead assigned the
|
|
2204
|
+
'outside' color
|
|
2205
|
+
- If 'circleignore' a circular mask is applied, but the data is not clipped
|
|
2206
|
+
|
|
2207
|
+
origin : (float, float)
|
|
2208
|
+
The relative origin of the colormap. Typically (0, 0), for colormaps
|
|
2209
|
+
that are linear on both axis, and (.5, .5) for circular colormaps.
|
|
2210
|
+
Used when getting 1D colormaps from 2D colormaps.
|
|
2211
|
+
|
|
2212
|
+
name : str, optional
|
|
2213
|
+
The name of the colormap.
|
|
2214
|
+
"""
|
|
2215
|
+
|
|
2216
|
+
def __init__(self, patch, N=256, shape='square', origin=(0, 0),
|
|
2217
|
+
name='segmented bivariate colormap'):
|
|
2218
|
+
_api.check_shape((None, None, 3), patch=patch)
|
|
2219
|
+
self.patch = patch
|
|
2220
|
+
super().__init__(N, N, shape, origin, name=name)
|
|
2221
|
+
|
|
2222
|
+
def _init(self):
|
|
2223
|
+
# Perform bilinear interpolation
|
|
2224
|
+
|
|
2225
|
+
s = self.patch.shape
|
|
2226
|
+
|
|
2227
|
+
# Indices (whole and fraction) of the new grid points
|
|
2228
|
+
row = np.linspace(0, s[0] - 1, self.N)[:, np.newaxis]
|
|
2229
|
+
col = np.linspace(0, s[1] - 1, self.N)[np.newaxis, :]
|
|
2230
|
+
left = row.astype(int) # floor not needed because all values are nonnegative
|
|
2231
|
+
top = col.astype(int) # floor not needed because all values are nonnegative
|
|
2232
|
+
row_frac = (row - left)[:, :, np.newaxis]
|
|
2233
|
+
col_frac = (col - top)[:, :, np.newaxis]
|
|
2234
|
+
|
|
2235
|
+
# Indices of the next edges, clipping where needed
|
|
2236
|
+
right = np.clip(left + 1, 0, s[0] - 1)
|
|
2237
|
+
bottom = np.clip(top + 1, 0, s[1] - 1)
|
|
2238
|
+
|
|
2239
|
+
# Values at the corners
|
|
2240
|
+
tl = self.patch[left, top, :]
|
|
2241
|
+
tr = self.patch[right, top, :]
|
|
2242
|
+
bl = self.patch[left, bottom, :]
|
|
2243
|
+
br = self.patch[right, bottom, :]
|
|
2244
|
+
|
|
2245
|
+
# Interpolate between the corners
|
|
2246
|
+
lut = (tl * (1 - row_frac) * (1 - col_frac) +
|
|
2247
|
+
tr * row_frac * (1 - col_frac) +
|
|
2248
|
+
bl * (1 - row_frac) * col_frac +
|
|
2249
|
+
br * row_frac * col_frac)
|
|
2250
|
+
|
|
2251
|
+
# Add the alpha channel
|
|
2252
|
+
self._lut = np.concatenate([lut, np.ones((self.N, self.N, 1))], axis=2)
|
|
2253
|
+
|
|
2254
|
+
self._isinit = True
|
|
2255
|
+
|
|
2256
|
+
|
|
2257
|
+
class BivarColormapFromImage(BivarColormap):
|
|
2258
|
+
"""
|
|
2259
|
+
BivarColormap object generated by supersampling a regular grid.
|
|
2260
|
+
|
|
2261
|
+
Parameters
|
|
2262
|
+
----------
|
|
2263
|
+
lut : nparray of shape (N, M, 3) or (N, M, 4)
|
|
2264
|
+
The look-up-table
|
|
2265
|
+
shape: {'square', 'circle', 'ignore', 'circleignore'}
|
|
2266
|
+
|
|
2267
|
+
- If 'square' each variate is clipped to [0,1] independently
|
|
2268
|
+
- If 'circle' the variates are clipped radially to the center
|
|
2269
|
+
of the colormap, and a circular mask is applied when the colormap
|
|
2270
|
+
is displayed
|
|
2271
|
+
- If 'ignore' the variates are not clipped, but instead assigned the
|
|
2272
|
+
'outside' color
|
|
2273
|
+
- If 'circleignore' a circular mask is applied, but the data is not clipped
|
|
2274
|
+
|
|
2275
|
+
origin: (float, float)
|
|
2276
|
+
The relative origin of the colormap. Typically (0, 0), for colormaps
|
|
2277
|
+
that are linear on both axis, and (.5, .5) for circular colormaps.
|
|
2278
|
+
Used when getting 1D colormaps from 2D colormaps.
|
|
2279
|
+
name : str, optional
|
|
2280
|
+
The name of the colormap.
|
|
2281
|
+
|
|
2282
|
+
"""
|
|
2283
|
+
|
|
2284
|
+
def __init__(self, lut, shape='square', origin=(0, 0), name='from image'):
|
|
2285
|
+
# We can allow for a PIL.Image as input in the following way, but importing
|
|
2286
|
+
# matplotlib.image.pil_to_array() results in a circular import
|
|
2287
|
+
# For now, this function only accepts numpy arrays.
|
|
2288
|
+
# i.e.:
|
|
2289
|
+
# if isinstance(Image, lut):
|
|
2290
|
+
# lut = image.pil_to_array(lut)
|
|
2291
|
+
lut = np.array(lut, copy=True)
|
|
2292
|
+
if lut.ndim != 3 or lut.shape[2] not in (3, 4):
|
|
2293
|
+
raise ValueError("The lut must be an array of shape (n, m, 3) or (n, m, 4)",
|
|
2294
|
+
" or a PIL.image encoded as RGB or RGBA")
|
|
2295
|
+
|
|
2296
|
+
if lut.dtype == np.uint8:
|
|
2297
|
+
lut = lut.astype(np.float32)/255
|
|
2298
|
+
if lut.shape[2] == 3:
|
|
2299
|
+
new_lut = np.empty((lut.shape[0], lut.shape[1], 4), dtype=lut.dtype)
|
|
2300
|
+
new_lut[:, :, :3] = lut
|
|
2301
|
+
new_lut[:, :, 3] = 1.
|
|
2302
|
+
lut = new_lut
|
|
2303
|
+
self._lut = lut
|
|
2304
|
+
super().__init__(lut.shape[0], lut.shape[1], shape, origin, name=name)
|
|
2305
|
+
|
|
2306
|
+
def _init(self):
|
|
2307
|
+
self._isinit = True
|
|
2308
|
+
|
|
2309
|
+
|
|
2310
|
+
class Norm(ABC):
|
|
2311
|
+
"""
|
|
2312
|
+
Abstract base class for normalizations.
|
|
2313
|
+
|
|
2314
|
+
Subclasses include `Normalize` which maps from a scalar to
|
|
2315
|
+
a scalar. However, this class makes no such requirement, and subclasses may
|
|
2316
|
+
support the normalization of multiple variates simultaneously, with
|
|
2317
|
+
separate normalization for each variate.
|
|
2318
|
+
"""
|
|
2319
|
+
|
|
2320
|
+
def __init__(self):
|
|
2321
|
+
self.callbacks = cbook.CallbackRegistry(signals=["changed"])
|
|
2322
|
+
|
|
2323
|
+
@property
|
|
2324
|
+
@abstractmethod
|
|
2325
|
+
def vmin(self):
|
|
2326
|
+
"""Lower limit of the input data interval; maps to 0."""
|
|
2327
|
+
pass
|
|
2328
|
+
|
|
2329
|
+
@property
|
|
2330
|
+
@abstractmethod
|
|
2331
|
+
def vmax(self):
|
|
2332
|
+
"""Upper limit of the input data interval; maps to 1."""
|
|
2333
|
+
pass
|
|
2334
|
+
|
|
2335
|
+
@property
|
|
2336
|
+
@abstractmethod
|
|
2337
|
+
def clip(self):
|
|
2338
|
+
"""
|
|
2339
|
+
Determines the behavior for mapping values outside the range ``[vmin, vmax]``.
|
|
2340
|
+
|
|
2341
|
+
See the *clip* parameter in `.Normalize`.
|
|
2342
|
+
"""
|
|
2343
|
+
pass
|
|
2344
|
+
|
|
2345
|
+
@abstractmethod
|
|
2346
|
+
def __call__(self, value, clip=None):
|
|
2347
|
+
"""
|
|
2348
|
+
Normalize the data and return the normalized data.
|
|
2349
|
+
|
|
2350
|
+
Parameters
|
|
2351
|
+
----------
|
|
2352
|
+
value
|
|
2353
|
+
Data to normalize.
|
|
2354
|
+
clip : bool, optional
|
|
2355
|
+
See the description of the parameter *clip* in `.Normalize`.
|
|
2356
|
+
|
|
2357
|
+
If ``None``, defaults to ``self.clip`` (which defaults to
|
|
2358
|
+
``False``).
|
|
2359
|
+
|
|
2360
|
+
Notes
|
|
2361
|
+
-----
|
|
2362
|
+
If not already initialized, ``self.vmin`` and ``self.vmax`` are
|
|
2363
|
+
initialized using ``self.autoscale_None(value)``.
|
|
2364
|
+
"""
|
|
2365
|
+
pass
|
|
2366
|
+
|
|
2367
|
+
@abstractmethod
|
|
2368
|
+
def autoscale(self, A):
|
|
2369
|
+
"""Set *vmin*, *vmax* to min, max of *A*."""
|
|
2370
|
+
pass
|
|
2371
|
+
|
|
2372
|
+
@abstractmethod
|
|
2373
|
+
def autoscale_None(self, A):
|
|
2374
|
+
"""If *vmin* or *vmax* are not set, use the min/max of *A* to set them."""
|
|
2375
|
+
pass
|
|
2376
|
+
|
|
2377
|
+
@abstractmethod
|
|
2378
|
+
def scaled(self):
|
|
2379
|
+
"""Return whether *vmin* and *vmax* are both set."""
|
|
2380
|
+
pass
|
|
2381
|
+
|
|
2382
|
+
def _changed(self):
|
|
2383
|
+
"""
|
|
2384
|
+
Call this whenever the norm is changed to notify all the
|
|
2385
|
+
callback listeners to the 'changed' signal.
|
|
2386
|
+
"""
|
|
2387
|
+
self.callbacks.process('changed')
|
|
2388
|
+
|
|
2389
|
+
@property
|
|
2390
|
+
@abstractmethod
|
|
2391
|
+
def n_components(self):
|
|
2392
|
+
"""
|
|
2393
|
+
The number of normalized components.
|
|
2394
|
+
|
|
2395
|
+
This is the number of elements of the parameter to ``__call__`` and of
|
|
2396
|
+
*vmin*, *vmax*.
|
|
2397
|
+
"""
|
|
2398
|
+
pass
|
|
2399
|
+
|
|
2400
|
+
|
|
2401
|
+
class Normalize(Norm):
|
|
2402
|
+
"""
|
|
2403
|
+
A class which, when called, maps values within the interval
|
|
2404
|
+
``[vmin, vmax]`` linearly to the interval ``[0.0, 1.0]``. The mapping of
|
|
2405
|
+
values outside ``[vmin, vmax]`` depends on *clip*.
|
|
2406
|
+
|
|
2407
|
+
Examples
|
|
2408
|
+
--------
|
|
2409
|
+
::
|
|
2410
|
+
|
|
2411
|
+
x = [-2, -1, 0, 1, 2]
|
|
2412
|
+
|
|
2413
|
+
norm = mpl.colors.Normalize(vmin=-1, vmax=1, clip=False)
|
|
2414
|
+
norm(x) # [-0.5, 0., 0.5, 1., 1.5]
|
|
2415
|
+
norm = mpl.colors.Normalize(vmin=-1, vmax=1, clip=True)
|
|
2416
|
+
norm(x) # [0., 0., 0.5, 1., 1.]
|
|
2417
|
+
|
|
2418
|
+
See Also
|
|
2419
|
+
--------
|
|
2420
|
+
:ref:`colormapnorms`
|
|
2421
|
+
"""
|
|
2422
|
+
|
|
2423
|
+
def __init__(self, vmin=None, vmax=None, clip=False):
|
|
2424
|
+
"""
|
|
2425
|
+
Parameters
|
|
2426
|
+
----------
|
|
2427
|
+
vmin, vmax : float or None
|
|
2428
|
+
Values within the range ``[vmin, vmax]`` from the input data will be
|
|
2429
|
+
linearly mapped to ``[0, 1]``. If either *vmin* or *vmax* is not
|
|
2430
|
+
provided, they default to the minimum and maximum values of the input,
|
|
2431
|
+
respectively.
|
|
2432
|
+
|
|
2433
|
+
clip : bool, default: False
|
|
2434
|
+
Determines the behavior for mapping values outside the range
|
|
2435
|
+
``[vmin, vmax]``.
|
|
2436
|
+
|
|
2437
|
+
If clipping is off, values outside the range ``[vmin, vmax]`` are
|
|
2438
|
+
also transformed, resulting in values outside ``[0, 1]``. This
|
|
2439
|
+
behavior is usually desirable, as colormaps can mark these *under*
|
|
2440
|
+
and *over* values with specific colors.
|
|
2441
|
+
|
|
2442
|
+
If clipping is on, values below *vmin* are mapped to 0 and values
|
|
2443
|
+
above *vmax* are mapped to 1. Such values become indistinguishable
|
|
2444
|
+
from regular boundary values, which may cause misinterpretation of
|
|
2445
|
+
the data.
|
|
2446
|
+
|
|
2447
|
+
Notes
|
|
2448
|
+
-----
|
|
2449
|
+
If ``vmin == vmax``, input data will be mapped to 0.
|
|
2450
|
+
"""
|
|
2451
|
+
super().__init__()
|
|
2452
|
+
self._vmin = _sanitize_extrema(vmin)
|
|
2453
|
+
self._vmax = _sanitize_extrema(vmax)
|
|
2454
|
+
self._clip = clip
|
|
2455
|
+
self._scale = None
|
|
2456
|
+
|
|
2457
|
+
@property
|
|
2458
|
+
def vmin(self):
|
|
2459
|
+
# docstring inherited
|
|
2460
|
+
return self._vmin
|
|
2461
|
+
|
|
2462
|
+
@vmin.setter
|
|
2463
|
+
def vmin(self, value):
|
|
2464
|
+
value = _sanitize_extrema(value)
|
|
2465
|
+
if value != self._vmin:
|
|
2466
|
+
self._vmin = value
|
|
2467
|
+
self._changed()
|
|
2468
|
+
|
|
2469
|
+
@property
|
|
2470
|
+
def vmax(self):
|
|
2471
|
+
# docstring inherited
|
|
2472
|
+
return self._vmax
|
|
2473
|
+
|
|
2474
|
+
@vmax.setter
|
|
2475
|
+
def vmax(self, value):
|
|
2476
|
+
value = _sanitize_extrema(value)
|
|
2477
|
+
if value != self._vmax:
|
|
2478
|
+
self._vmax = value
|
|
2479
|
+
self._changed()
|
|
2480
|
+
|
|
2481
|
+
@property
|
|
2482
|
+
def clip(self):
|
|
2483
|
+
# docstring inherited
|
|
2484
|
+
return self._clip
|
|
2485
|
+
|
|
2486
|
+
@clip.setter
|
|
2487
|
+
def clip(self, value):
|
|
2488
|
+
if value != self._clip:
|
|
2489
|
+
self._clip = value
|
|
2490
|
+
self._changed()
|
|
2491
|
+
|
|
2492
|
+
@staticmethod
|
|
2493
|
+
def process_value(value):
|
|
2494
|
+
"""
|
|
2495
|
+
Homogenize the input *value* for easy and efficient normalization.
|
|
2496
|
+
|
|
2497
|
+
*value* can be a scalar or sequence.
|
|
2498
|
+
|
|
2499
|
+
Parameters
|
|
2500
|
+
----------
|
|
2501
|
+
value
|
|
2502
|
+
Data to normalize.
|
|
2503
|
+
|
|
2504
|
+
Returns
|
|
2505
|
+
-------
|
|
2506
|
+
result : masked array
|
|
2507
|
+
Masked array with the same shape as *value*.
|
|
2508
|
+
is_scalar : bool
|
|
2509
|
+
Whether *value* is a scalar.
|
|
2510
|
+
|
|
2511
|
+
Notes
|
|
2512
|
+
-----
|
|
2513
|
+
Float dtypes are preserved; integer types with two bytes or smaller are
|
|
2514
|
+
converted to np.float32, and larger types are converted to np.float64.
|
|
2515
|
+
Preserving float32 when possible, and using in-place operations,
|
|
2516
|
+
greatly improves speed for large arrays.
|
|
2517
|
+
"""
|
|
2518
|
+
is_scalar = not np.iterable(value)
|
|
2519
|
+
if is_scalar:
|
|
2520
|
+
value = [value]
|
|
2521
|
+
dtype = np.min_scalar_type(value)
|
|
2522
|
+
if np.issubdtype(dtype, np.integer) or dtype.type is np.bool_:
|
|
2523
|
+
# bool_/int8/int16 -> float32; int32/int64 -> float64
|
|
2524
|
+
dtype = np.promote_types(dtype, np.float32)
|
|
2525
|
+
# ensure data passed in as an ndarray subclass are interpreted as
|
|
2526
|
+
# an ndarray. See issue #6622.
|
|
2527
|
+
mask = np.ma.getmask(value)
|
|
2528
|
+
data = np.asarray(value)
|
|
2529
|
+
result = np.ma.array(data, mask=mask, dtype=dtype, copy=True)
|
|
2530
|
+
return result, is_scalar
|
|
2531
|
+
|
|
2532
|
+
def __call__(self, value, clip=None):
|
|
2533
|
+
# docstring inherited
|
|
2534
|
+
if clip is None:
|
|
2535
|
+
clip = self.clip
|
|
2536
|
+
|
|
2537
|
+
result, is_scalar = self.process_value(value)
|
|
2538
|
+
|
|
2539
|
+
if self.vmin is None or self.vmax is None:
|
|
2540
|
+
self.autoscale_None(result)
|
|
2541
|
+
# Convert at least to float, without losing precision.
|
|
2542
|
+
(vmin,), _ = self.process_value(self.vmin)
|
|
2543
|
+
(vmax,), _ = self.process_value(self.vmax)
|
|
2544
|
+
if vmin == vmax:
|
|
2545
|
+
result.fill(0) # Or should it be all masked? Or 0.5?
|
|
2546
|
+
elif vmin > vmax:
|
|
2547
|
+
raise ValueError("minvalue must be less than or equal to maxvalue")
|
|
2548
|
+
else:
|
|
2549
|
+
if clip:
|
|
2550
|
+
mask = np.ma.getmask(result)
|
|
2551
|
+
result = np.ma.array(np.clip(result.filled(vmax), vmin, vmax),
|
|
2552
|
+
mask=mask)
|
|
2553
|
+
# ma division is very slow; we can take a shortcut
|
|
2554
|
+
resdat = result.data
|
|
2555
|
+
resdat -= vmin
|
|
2556
|
+
resdat /= (vmax - vmin)
|
|
2557
|
+
result = np.ma.array(resdat, mask=result.mask, copy=False)
|
|
2558
|
+
if is_scalar:
|
|
2559
|
+
result = result[0]
|
|
2560
|
+
return result
|
|
2561
|
+
|
|
2562
|
+
def inverse(self, value):
|
|
2563
|
+
"""
|
|
2564
|
+
Maps the normalized value (i.e., index in the colormap) back to image
|
|
2565
|
+
data value.
|
|
2566
|
+
|
|
2567
|
+
Parameters
|
|
2568
|
+
----------
|
|
2569
|
+
value
|
|
2570
|
+
Normalized value.
|
|
2571
|
+
"""
|
|
2572
|
+
if not self.scaled():
|
|
2573
|
+
raise ValueError("Not invertible until both vmin and vmax are set")
|
|
2574
|
+
(vmin,), _ = self.process_value(self.vmin)
|
|
2575
|
+
(vmax,), _ = self.process_value(self.vmax)
|
|
2576
|
+
|
|
2577
|
+
if np.iterable(value):
|
|
2578
|
+
val = np.ma.asarray(value)
|
|
2579
|
+
return vmin + val * (vmax - vmin)
|
|
2580
|
+
else:
|
|
2581
|
+
return vmin + value * (vmax - vmin)
|
|
2582
|
+
|
|
2583
|
+
def autoscale(self, A):
|
|
2584
|
+
# docstring inherited
|
|
2585
|
+
with self.callbacks.blocked():
|
|
2586
|
+
# Pause callbacks while we are updating so we only get
|
|
2587
|
+
# a single update signal at the end
|
|
2588
|
+
self.vmin = self.vmax = None
|
|
2589
|
+
self.autoscale_None(A)
|
|
2590
|
+
self._changed()
|
|
2591
|
+
|
|
2592
|
+
def autoscale_None(self, A):
|
|
2593
|
+
# docstring inherited
|
|
2594
|
+
A = np.asanyarray(A)
|
|
2595
|
+
|
|
2596
|
+
if isinstance(A, np.ma.MaskedArray):
|
|
2597
|
+
# we need to make the distinction between an array, False, np.bool_(False)
|
|
2598
|
+
if A.mask is False or not A.mask.shape:
|
|
2599
|
+
A = A.data
|
|
2600
|
+
|
|
2601
|
+
if self.vmin is None and A.size:
|
|
2602
|
+
self.vmin = A.min()
|
|
2603
|
+
if self.vmax is None and A.size:
|
|
2604
|
+
self.vmax = A.max()
|
|
2605
|
+
|
|
2606
|
+
def scaled(self):
|
|
2607
|
+
# docstring inherited
|
|
2608
|
+
return self.vmin is not None and self.vmax is not None
|
|
2609
|
+
|
|
2610
|
+
@property
|
|
2611
|
+
def n_components(self):
|
|
2612
|
+
"""
|
|
2613
|
+
The number of distinct components supported (1).
|
|
2614
|
+
|
|
2615
|
+
This is the number of elements of the parameter to ``__call__`` and of
|
|
2616
|
+
*vmin*, *vmax*.
|
|
2617
|
+
|
|
2618
|
+
This class support only a single component, as opposed to `MultiNorm`
|
|
2619
|
+
which supports multiple components.
|
|
2620
|
+
"""
|
|
2621
|
+
return 1
|
|
2622
|
+
|
|
2623
|
+
|
|
2624
|
+
class TwoSlopeNorm(Normalize):
|
|
2625
|
+
def __init__(self, vcenter, vmin=None, vmax=None):
|
|
2626
|
+
"""
|
|
2627
|
+
Normalize data with a set center.
|
|
2628
|
+
|
|
2629
|
+
Useful when mapping data with an unequal rates of change around a
|
|
2630
|
+
conceptual center, e.g., data that range from -2 to 4, with 0 as
|
|
2631
|
+
the midpoint.
|
|
2632
|
+
|
|
2633
|
+
Parameters
|
|
2634
|
+
----------
|
|
2635
|
+
vcenter : float
|
|
2636
|
+
The data value that defines ``0.5`` in the normalization.
|
|
2637
|
+
vmin : float, optional
|
|
2638
|
+
The data value that defines ``0.0`` in the normalization.
|
|
2639
|
+
Defaults to the min value of the dataset.
|
|
2640
|
+
vmax : float, optional
|
|
2641
|
+
The data value that defines ``1.0`` in the normalization.
|
|
2642
|
+
Defaults to the max value of the dataset.
|
|
2643
|
+
|
|
2644
|
+
Examples
|
|
2645
|
+
--------
|
|
2646
|
+
This maps data value -4000 to 0., 0 to 0.5, and +10000 to 1.0; data
|
|
2647
|
+
between is linearly interpolated::
|
|
2648
|
+
|
|
2649
|
+
>>> import matplotlib.colors as mcolors
|
|
2650
|
+
>>> offset = mcolors.TwoSlopeNorm(vmin=-4000.,
|
|
2651
|
+
... vcenter=0., vmax=10000)
|
|
2652
|
+
>>> data = [-4000., -2000., 0., 2500., 5000., 7500., 10000.]
|
|
2653
|
+
>>> offset(data)
|
|
2654
|
+
array([0., 0.25, 0.5, 0.625, 0.75, 0.875, 1.0])
|
|
2655
|
+
"""
|
|
2656
|
+
|
|
2657
|
+
super().__init__(vmin=vmin, vmax=vmax)
|
|
2658
|
+
self._vcenter = vcenter
|
|
2659
|
+
if vcenter is not None and vmax is not None and vcenter >= vmax:
|
|
2660
|
+
raise ValueError('vmin, vcenter, and vmax must be in '
|
|
2661
|
+
'ascending order')
|
|
2662
|
+
if vcenter is not None and vmin is not None and vcenter <= vmin:
|
|
2663
|
+
raise ValueError('vmin, vcenter, and vmax must be in '
|
|
2664
|
+
'ascending order')
|
|
2665
|
+
|
|
2666
|
+
@property
|
|
2667
|
+
def vcenter(self):
|
|
2668
|
+
return self._vcenter
|
|
2669
|
+
|
|
2670
|
+
@vcenter.setter
|
|
2671
|
+
def vcenter(self, value):
|
|
2672
|
+
if value != self._vcenter:
|
|
2673
|
+
self._vcenter = value
|
|
2674
|
+
self._changed()
|
|
2675
|
+
|
|
2676
|
+
def autoscale_None(self, A):
|
|
2677
|
+
"""
|
|
2678
|
+
Get vmin and vmax.
|
|
2679
|
+
|
|
2680
|
+
If vcenter isn't in the range [vmin, vmax], either vmin or vmax
|
|
2681
|
+
is expanded so that vcenter lies in the middle of the modified range
|
|
2682
|
+
[vmin, vmax].
|
|
2683
|
+
"""
|
|
2684
|
+
super().autoscale_None(A)
|
|
2685
|
+
if self.vmin >= self.vcenter:
|
|
2686
|
+
self.vmin = self.vcenter - (self.vmax - self.vcenter)
|
|
2687
|
+
if self.vmax <= self.vcenter:
|
|
2688
|
+
self.vmax = self.vcenter + (self.vcenter - self.vmin)
|
|
2689
|
+
|
|
2690
|
+
def __call__(self, value, clip=None):
|
|
2691
|
+
"""
|
|
2692
|
+
Map value to the interval [0, 1]. The *clip* argument is unused.
|
|
2693
|
+
"""
|
|
2694
|
+
result, is_scalar = self.process_value(value)
|
|
2695
|
+
self.autoscale_None(result) # sets self.vmin, self.vmax if None
|
|
2696
|
+
|
|
2697
|
+
if not self.vmin <= self.vcenter <= self.vmax:
|
|
2698
|
+
raise ValueError("vmin, vcenter, vmax must increase monotonically")
|
|
2699
|
+
# note that we must extrapolate for tick locators:
|
|
2700
|
+
result = np.ma.masked_array(
|
|
2701
|
+
np.interp(result, [self.vmin, self.vcenter, self.vmax],
|
|
2702
|
+
[0, 0.5, 1], left=-np.inf, right=np.inf),
|
|
2703
|
+
mask=np.ma.getmask(result))
|
|
2704
|
+
if is_scalar:
|
|
2705
|
+
result = np.atleast_1d(result)[0]
|
|
2706
|
+
return result
|
|
2707
|
+
|
|
2708
|
+
def inverse(self, value):
|
|
2709
|
+
if not self.scaled():
|
|
2710
|
+
raise ValueError("Not invertible until both vmin and vmax are set")
|
|
2711
|
+
(vmin,), _ = self.process_value(self.vmin)
|
|
2712
|
+
(vmax,), _ = self.process_value(self.vmax)
|
|
2713
|
+
(vcenter,), _ = self.process_value(self.vcenter)
|
|
2714
|
+
result = np.interp(value, [0, 0.5, 1], [vmin, vcenter, vmax],
|
|
2715
|
+
left=-np.inf, right=np.inf)
|
|
2716
|
+
return result
|
|
2717
|
+
|
|
2718
|
+
|
|
2719
|
+
class CenteredNorm(Normalize):
|
|
2720
|
+
def __init__(self, vcenter=0, halfrange=None, clip=False):
|
|
2721
|
+
"""
|
|
2722
|
+
Normalize symmetrical data around a center (0 by default).
|
|
2723
|
+
|
|
2724
|
+
Unlike `TwoSlopeNorm`, `CenteredNorm` applies an equal rate of change
|
|
2725
|
+
around the center.
|
|
2726
|
+
|
|
2727
|
+
Useful when mapping symmetrical data around a conceptual center
|
|
2728
|
+
e.g., data that range from -2 to 4, with 0 as the midpoint, and
|
|
2729
|
+
with equal rates of change around that midpoint.
|
|
2730
|
+
|
|
2731
|
+
Parameters
|
|
2732
|
+
----------
|
|
2733
|
+
vcenter : float, default: 0
|
|
2734
|
+
The data value that defines ``0.5`` in the normalization.
|
|
2735
|
+
halfrange : float, optional
|
|
2736
|
+
The range of data values that defines a range of ``0.5`` in the
|
|
2737
|
+
normalization, so that *vcenter* - *halfrange* is ``0.0`` and
|
|
2738
|
+
*vcenter* + *halfrange* is ``1.0`` in the normalization.
|
|
2739
|
+
Defaults to the largest absolute difference to *vcenter* for
|
|
2740
|
+
the values in the dataset.
|
|
2741
|
+
clip : bool, default: False
|
|
2742
|
+
Determines the behavior for mapping values outside the range
|
|
2743
|
+
``[vmin, vmax]``.
|
|
2744
|
+
|
|
2745
|
+
If clipping is off, values outside the range ``[vmin, vmax]`` are
|
|
2746
|
+
also transformed, resulting in values outside ``[0, 1]``. This
|
|
2747
|
+
behavior is usually desirable, as colormaps can mark these *under*
|
|
2748
|
+
and *over* values with specific colors.
|
|
2749
|
+
|
|
2750
|
+
If clipping is on, values below *vmin* are mapped to 0 and values
|
|
2751
|
+
above *vmax* are mapped to 1. Such values become indistinguishable
|
|
2752
|
+
from regular boundary values, which may cause misinterpretation of
|
|
2753
|
+
the data.
|
|
2754
|
+
|
|
2755
|
+
Examples
|
|
2756
|
+
--------
|
|
2757
|
+
This maps data values -2 to 0.25, 0 to 0.5, and 4 to 1.0
|
|
2758
|
+
(assuming equal rates of change above and below 0.0):
|
|
2759
|
+
|
|
2760
|
+
>>> import matplotlib.colors as mcolors
|
|
2761
|
+
>>> norm = mcolors.CenteredNorm(halfrange=4.0)
|
|
2762
|
+
>>> data = [-2., 0., 4.]
|
|
2763
|
+
>>> norm(data)
|
|
2764
|
+
array([0.25, 0.5 , 1. ])
|
|
2765
|
+
"""
|
|
2766
|
+
super().__init__(vmin=None, vmax=None, clip=clip)
|
|
2767
|
+
self._vcenter = vcenter
|
|
2768
|
+
# calling the halfrange setter to set vmin and vmax
|
|
2769
|
+
self.halfrange = halfrange
|
|
2770
|
+
|
|
2771
|
+
def autoscale(self, A):
|
|
2772
|
+
"""
|
|
2773
|
+
Set *halfrange* to ``max(abs(A-vcenter))``, then set *vmin* and *vmax*.
|
|
2774
|
+
"""
|
|
2775
|
+
A = np.asanyarray(A)
|
|
2776
|
+
self.halfrange = max(self._vcenter-A.min(),
|
|
2777
|
+
A.max()-self._vcenter)
|
|
2778
|
+
|
|
2779
|
+
def autoscale_None(self, A):
|
|
2780
|
+
"""Set *vmin* and *vmax*."""
|
|
2781
|
+
A = np.asanyarray(A)
|
|
2782
|
+
if self.halfrange is None and A.size:
|
|
2783
|
+
self.autoscale(A)
|
|
2784
|
+
|
|
2785
|
+
@property
|
|
2786
|
+
def vmin(self):
|
|
2787
|
+
return self._vmin
|
|
2788
|
+
|
|
2789
|
+
@vmin.setter
|
|
2790
|
+
def vmin(self, value):
|
|
2791
|
+
value = _sanitize_extrema(value)
|
|
2792
|
+
if value != self._vmin:
|
|
2793
|
+
self._vmin = value
|
|
2794
|
+
self._vmax = 2*self.vcenter - value
|
|
2795
|
+
self._changed()
|
|
2796
|
+
|
|
2797
|
+
@property
|
|
2798
|
+
def vmax(self):
|
|
2799
|
+
return self._vmax
|
|
2800
|
+
|
|
2801
|
+
@vmax.setter
|
|
2802
|
+
def vmax(self, value):
|
|
2803
|
+
value = _sanitize_extrema(value)
|
|
2804
|
+
if value != self._vmax:
|
|
2805
|
+
self._vmax = value
|
|
2806
|
+
self._vmin = 2*self.vcenter - value
|
|
2807
|
+
self._changed()
|
|
2808
|
+
|
|
2809
|
+
@property
|
|
2810
|
+
def vcenter(self):
|
|
2811
|
+
return self._vcenter
|
|
2812
|
+
|
|
2813
|
+
@vcenter.setter
|
|
2814
|
+
def vcenter(self, vcenter):
|
|
2815
|
+
if vcenter != self._vcenter:
|
|
2816
|
+
self._vcenter = vcenter
|
|
2817
|
+
# Trigger an update of the vmin/vmax values through the setter
|
|
2818
|
+
self.halfrange = self.halfrange
|
|
2819
|
+
self._changed()
|
|
2820
|
+
|
|
2821
|
+
@property
|
|
2822
|
+
def halfrange(self):
|
|
2823
|
+
if self.vmin is None or self.vmax is None:
|
|
2824
|
+
return None
|
|
2825
|
+
return (self.vmax - self.vmin) / 2
|
|
2826
|
+
|
|
2827
|
+
@halfrange.setter
|
|
2828
|
+
def halfrange(self, halfrange):
|
|
2829
|
+
if halfrange is None:
|
|
2830
|
+
self.vmin = None
|
|
2831
|
+
self.vmax = None
|
|
2832
|
+
else:
|
|
2833
|
+
self.vmin = self.vcenter - abs(halfrange)
|
|
2834
|
+
self.vmax = self.vcenter + abs(halfrange)
|
|
2835
|
+
|
|
2836
|
+
|
|
2837
|
+
def make_norm_from_scale(scale_cls, base_norm_cls=None, *, init=None):
|
|
2838
|
+
"""
|
|
2839
|
+
Decorator for building a `.Normalize` subclass from a `~.scale.ScaleBase`
|
|
2840
|
+
subclass.
|
|
2841
|
+
|
|
2842
|
+
After ::
|
|
2843
|
+
|
|
2844
|
+
@make_norm_from_scale(scale_cls)
|
|
2845
|
+
class norm_cls(Normalize):
|
|
2846
|
+
...
|
|
2847
|
+
|
|
2848
|
+
*norm_cls* is filled with methods so that normalization computations are
|
|
2849
|
+
forwarded to *scale_cls* (i.e., *scale_cls* is the scale that would be used
|
|
2850
|
+
for the colorbar of a mappable normalized with *norm_cls*).
|
|
2851
|
+
|
|
2852
|
+
If *init* is not passed, then the constructor signature of *norm_cls*
|
|
2853
|
+
will be ``norm_cls(vmin=None, vmax=None, clip=False)``; these three
|
|
2854
|
+
parameters will be forwarded to the base class (``Normalize.__init__``),
|
|
2855
|
+
and a *scale_cls* object will be initialized with no arguments (other than
|
|
2856
|
+
a dummy axis).
|
|
2857
|
+
|
|
2858
|
+
If the *scale_cls* constructor takes additional parameters, then *init*
|
|
2859
|
+
should be passed to `make_norm_from_scale`. It is a callable which is
|
|
2860
|
+
*only* used for its signature. First, this signature will become the
|
|
2861
|
+
signature of *norm_cls*. Second, the *norm_cls* constructor will bind the
|
|
2862
|
+
parameters passed to it using this signature, extract the bound *vmin*,
|
|
2863
|
+
*vmax*, and *clip* values, pass those to ``Normalize.__init__``, and
|
|
2864
|
+
forward the remaining bound values (including any defaults defined by the
|
|
2865
|
+
signature) to the *scale_cls* constructor.
|
|
2866
|
+
"""
|
|
2867
|
+
|
|
2868
|
+
if base_norm_cls is None:
|
|
2869
|
+
return functools.partial(make_norm_from_scale, scale_cls, init=init)
|
|
2870
|
+
|
|
2871
|
+
if isinstance(scale_cls, functools.partial):
|
|
2872
|
+
scale_args = scale_cls.args
|
|
2873
|
+
scale_kwargs_items = tuple(scale_cls.keywords.items())
|
|
2874
|
+
scale_cls = scale_cls.func
|
|
2875
|
+
else:
|
|
2876
|
+
scale_args = scale_kwargs_items = ()
|
|
2877
|
+
|
|
2878
|
+
if init is None:
|
|
2879
|
+
def init(vmin=None, vmax=None, clip=False): pass
|
|
2880
|
+
|
|
2881
|
+
return _make_norm_from_scale(
|
|
2882
|
+
scale_cls, scale_args, scale_kwargs_items,
|
|
2883
|
+
base_norm_cls, inspect.signature(init))
|
|
2884
|
+
|
|
2885
|
+
|
|
2886
|
+
@functools.cache
|
|
2887
|
+
def _make_norm_from_scale(
|
|
2888
|
+
scale_cls, scale_args, scale_kwargs_items,
|
|
2889
|
+
base_norm_cls, bound_init_signature,
|
|
2890
|
+
):
|
|
2891
|
+
"""
|
|
2892
|
+
Helper for `make_norm_from_scale`.
|
|
2893
|
+
|
|
2894
|
+
This function is split out to enable caching (in particular so that
|
|
2895
|
+
different unpickles reuse the same class). In order to do so,
|
|
2896
|
+
|
|
2897
|
+
- ``functools.partial`` *scale_cls* is expanded into ``func, args, kwargs``
|
|
2898
|
+
to allow memoizing returned norms (partial instances always compare
|
|
2899
|
+
unequal, but we can check identity based on ``func, args, kwargs``;
|
|
2900
|
+
- *init* is replaced by *init_signature*, as signatures are picklable,
|
|
2901
|
+
unlike to arbitrary lambdas.
|
|
2902
|
+
"""
|
|
2903
|
+
|
|
2904
|
+
class ScaleNorm(base_norm_cls):
|
|
2905
|
+
def __reduce__(self):
|
|
2906
|
+
cls = type(self)
|
|
2907
|
+
# If the class is toplevel-accessible, it is possible to directly
|
|
2908
|
+
# pickle it "by name". This is required to support norm classes
|
|
2909
|
+
# defined at a module's toplevel, as the inner base_norm_cls is
|
|
2910
|
+
# otherwise unpicklable (as it gets shadowed by the generated norm
|
|
2911
|
+
# class). If either import or attribute access fails, fall back to
|
|
2912
|
+
# the general path.
|
|
2913
|
+
try:
|
|
2914
|
+
if cls is getattr(importlib.import_module(cls.__module__),
|
|
2915
|
+
cls.__qualname__):
|
|
2916
|
+
return (_create_empty_object_of_class, (cls,), vars(self))
|
|
2917
|
+
except (ImportError, AttributeError):
|
|
2918
|
+
pass
|
|
2919
|
+
return (_picklable_norm_constructor,
|
|
2920
|
+
(scale_cls, scale_args, scale_kwargs_items,
|
|
2921
|
+
base_norm_cls, bound_init_signature),
|
|
2922
|
+
vars(self))
|
|
2923
|
+
|
|
2924
|
+
def __init__(self, *args, **kwargs):
|
|
2925
|
+
ba = bound_init_signature.bind(*args, **kwargs)
|
|
2926
|
+
ba.apply_defaults()
|
|
2927
|
+
super().__init__(
|
|
2928
|
+
**{k: ba.arguments.pop(k) for k in ["vmin", "vmax", "clip"]})
|
|
2929
|
+
self._scale = functools.partial(
|
|
2930
|
+
scale_cls, *scale_args, **dict(scale_kwargs_items))(
|
|
2931
|
+
axis=None, **ba.arguments)
|
|
2932
|
+
self._trf = self._scale.get_transform()
|
|
2933
|
+
|
|
2934
|
+
__init__.__signature__ = bound_init_signature.replace(parameters=[
|
|
2935
|
+
inspect.Parameter("self", inspect.Parameter.POSITIONAL_OR_KEYWORD),
|
|
2936
|
+
*bound_init_signature.parameters.values()])
|
|
2937
|
+
|
|
2938
|
+
def __call__(self, value, clip=None):
|
|
2939
|
+
value, is_scalar = self.process_value(value)
|
|
2940
|
+
if self.vmin is None or self.vmax is None:
|
|
2941
|
+
self.autoscale_None(value)
|
|
2942
|
+
if self.vmin > self.vmax:
|
|
2943
|
+
raise ValueError("vmin must be less or equal to vmax")
|
|
2944
|
+
if self.vmin == self.vmax:
|
|
2945
|
+
return np.full_like(value, 0)
|
|
2946
|
+
if clip is None:
|
|
2947
|
+
clip = self.clip
|
|
2948
|
+
if clip:
|
|
2949
|
+
value = np.clip(value, self.vmin, self.vmax)
|
|
2950
|
+
t_value = self._trf.transform(value).reshape(np.shape(value))
|
|
2951
|
+
t_vmin, t_vmax = self._trf.transform([self.vmin, self.vmax])
|
|
2952
|
+
if not np.isfinite([t_vmin, t_vmax]).all():
|
|
2953
|
+
raise ValueError("Invalid vmin or vmax")
|
|
2954
|
+
t_value -= t_vmin
|
|
2955
|
+
t_value /= (t_vmax - t_vmin)
|
|
2956
|
+
t_value = np.ma.masked_invalid(t_value, copy=False)
|
|
2957
|
+
return t_value[0] if is_scalar else t_value
|
|
2958
|
+
|
|
2959
|
+
def inverse(self, value):
|
|
2960
|
+
if not self.scaled():
|
|
2961
|
+
raise ValueError("Not invertible until scaled")
|
|
2962
|
+
if self.vmin > self.vmax:
|
|
2963
|
+
raise ValueError("vmin must be less or equal to vmax")
|
|
2964
|
+
t_vmin, t_vmax = self._trf.transform([self.vmin, self.vmax])
|
|
2965
|
+
if not np.isfinite([t_vmin, t_vmax]).all():
|
|
2966
|
+
raise ValueError("Invalid vmin or vmax")
|
|
2967
|
+
value, is_scalar = self.process_value(value)
|
|
2968
|
+
rescaled = value * (t_vmax - t_vmin)
|
|
2969
|
+
rescaled += t_vmin
|
|
2970
|
+
value = (self._trf
|
|
2971
|
+
.inverted()
|
|
2972
|
+
.transform(rescaled)
|
|
2973
|
+
.reshape(np.shape(value)))
|
|
2974
|
+
return value[0] if is_scalar else value
|
|
2975
|
+
|
|
2976
|
+
def autoscale_None(self, A):
|
|
2977
|
+
# i.e. A[np.isfinite(...)], but also for non-array A's
|
|
2978
|
+
in_trf_domain = np.extract(np.isfinite(self._trf.transform(A)), A)
|
|
2979
|
+
if in_trf_domain.size == 0:
|
|
2980
|
+
in_trf_domain = np.ma.masked
|
|
2981
|
+
return super().autoscale_None(in_trf_domain)
|
|
2982
|
+
|
|
2983
|
+
if base_norm_cls is Normalize:
|
|
2984
|
+
ScaleNorm.__name__ = f"{scale_cls.__name__}Norm"
|
|
2985
|
+
ScaleNorm.__qualname__ = f"{scale_cls.__qualname__}Norm"
|
|
2986
|
+
else:
|
|
2987
|
+
ScaleNorm.__name__ = base_norm_cls.__name__
|
|
2988
|
+
ScaleNorm.__qualname__ = base_norm_cls.__qualname__
|
|
2989
|
+
ScaleNorm.__module__ = base_norm_cls.__module__
|
|
2990
|
+
ScaleNorm.__doc__ = base_norm_cls.__doc__
|
|
2991
|
+
|
|
2992
|
+
return ScaleNorm
|
|
2993
|
+
|
|
2994
|
+
|
|
2995
|
+
def _create_empty_object_of_class(cls):
|
|
2996
|
+
return cls.__new__(cls)
|
|
2997
|
+
|
|
2998
|
+
|
|
2999
|
+
def _picklable_norm_constructor(*args):
|
|
3000
|
+
return _create_empty_object_of_class(_make_norm_from_scale(*args))
|
|
3001
|
+
|
|
3002
|
+
|
|
3003
|
+
@make_norm_from_scale(
|
|
3004
|
+
scale.FuncScale,
|
|
3005
|
+
init=lambda functions, vmin=None, vmax=None, clip=False: None)
|
|
3006
|
+
class FuncNorm(Normalize):
|
|
3007
|
+
"""
|
|
3008
|
+
Arbitrary normalization using functions for the forward and inverse.
|
|
3009
|
+
|
|
3010
|
+
Parameters
|
|
3011
|
+
----------
|
|
3012
|
+
functions : (callable, callable)
|
|
3013
|
+
two-tuple of the forward and inverse functions for the normalization.
|
|
3014
|
+
The forward function must be monotonic.
|
|
3015
|
+
|
|
3016
|
+
Both functions must have the signature ::
|
|
3017
|
+
|
|
3018
|
+
def forward(values: array-like) -> array-like
|
|
3019
|
+
|
|
3020
|
+
vmin, vmax : float or None
|
|
3021
|
+
If *vmin* and/or *vmax* is not given, they are initialized from the
|
|
3022
|
+
minimum and maximum value, respectively, of the first input
|
|
3023
|
+
processed; i.e., ``__call__(A)`` calls ``autoscale_None(A)``.
|
|
3024
|
+
|
|
3025
|
+
clip : bool, default: False
|
|
3026
|
+
Determines the behavior for mapping values outside the range
|
|
3027
|
+
``[vmin, vmax]``.
|
|
3028
|
+
|
|
3029
|
+
If clipping is off, values outside the range ``[vmin, vmax]`` are also
|
|
3030
|
+
transformed by the function, resulting in values outside ``[0, 1]``.
|
|
3031
|
+
This behavior is usually desirable, as colormaps can mark these *under*
|
|
3032
|
+
and *over* values with specific colors.
|
|
3033
|
+
|
|
3034
|
+
If clipping is on, values below *vmin* are mapped to 0 and values above
|
|
3035
|
+
*vmax* are mapped to 1. Such values become indistinguishable from
|
|
3036
|
+
regular boundary values, which may cause misinterpretation of the data.
|
|
3037
|
+
"""
|
|
3038
|
+
|
|
3039
|
+
|
|
3040
|
+
LogNorm = make_norm_from_scale(
|
|
3041
|
+
functools.partial(scale.LogScale, nonpositive="mask"))(Normalize)
|
|
3042
|
+
LogNorm.__name__ = LogNorm.__qualname__ = "LogNorm"
|
|
3043
|
+
LogNorm.__doc__ = "Normalize a given value to the 0-1 range on a log scale."
|
|
3044
|
+
|
|
3045
|
+
|
|
3046
|
+
@make_norm_from_scale(
|
|
3047
|
+
scale.SymmetricalLogScale,
|
|
3048
|
+
init=lambda linthresh, linscale=1., vmin=None, vmax=None, clip=False, *,
|
|
3049
|
+
base=10: None)
|
|
3050
|
+
class SymLogNorm(Normalize):
|
|
3051
|
+
"""
|
|
3052
|
+
The symmetrical logarithmic scale is logarithmic in both the
|
|
3053
|
+
positive and negative directions from the origin.
|
|
3054
|
+
|
|
3055
|
+
Since the values close to zero tend toward infinity, there is a
|
|
3056
|
+
need to have a range around zero that is linear. The parameter
|
|
3057
|
+
*linthresh* allows the user to specify the size of this range
|
|
3058
|
+
(-*linthresh*, *linthresh*).
|
|
3059
|
+
|
|
3060
|
+
Parameters
|
|
3061
|
+
----------
|
|
3062
|
+
linthresh : float
|
|
3063
|
+
The range within which the plot is linear (to avoid having the plot
|
|
3064
|
+
go to infinity around zero).
|
|
3065
|
+
linscale : float, default: 1
|
|
3066
|
+
This allows the linear range (-*linthresh* to *linthresh*) to be
|
|
3067
|
+
stretched relative to the logarithmic range. Its value is the
|
|
3068
|
+
number of decades to use for each half of the linear range. For
|
|
3069
|
+
example, when *linscale* == 1.0 (the default), the space used for
|
|
3070
|
+
the positive and negative halves of the linear range will be equal
|
|
3071
|
+
to one decade in the logarithmic range.
|
|
3072
|
+
base : float, default: 10
|
|
3073
|
+
"""
|
|
3074
|
+
|
|
3075
|
+
@property
|
|
3076
|
+
def linthresh(self):
|
|
3077
|
+
return self._scale.linthresh
|
|
3078
|
+
|
|
3079
|
+
@linthresh.setter
|
|
3080
|
+
def linthresh(self, value):
|
|
3081
|
+
self._scale.linthresh = value
|
|
3082
|
+
|
|
3083
|
+
|
|
3084
|
+
@make_norm_from_scale(
|
|
3085
|
+
scale.AsinhScale,
|
|
3086
|
+
init=lambda linear_width=1, vmin=None, vmax=None, clip=False: None)
|
|
3087
|
+
class AsinhNorm(Normalize):
|
|
3088
|
+
"""
|
|
3089
|
+
The inverse hyperbolic sine scale is approximately linear near
|
|
3090
|
+
the origin, but becomes logarithmic for larger positive
|
|
3091
|
+
or negative values. Unlike the `SymLogNorm`, the transition between
|
|
3092
|
+
these linear and logarithmic regions is smooth, which may reduce
|
|
3093
|
+
the risk of visual artifacts.
|
|
3094
|
+
|
|
3095
|
+
.. note::
|
|
3096
|
+
|
|
3097
|
+
This API is provisional and may be revised in the future
|
|
3098
|
+
based on early user feedback.
|
|
3099
|
+
|
|
3100
|
+
Parameters
|
|
3101
|
+
----------
|
|
3102
|
+
linear_width : float, default: 1
|
|
3103
|
+
The effective width of the linear region, beyond which
|
|
3104
|
+
the transformation becomes asymptotically logarithmic
|
|
3105
|
+
"""
|
|
3106
|
+
|
|
3107
|
+
@property
|
|
3108
|
+
def linear_width(self):
|
|
3109
|
+
return self._scale.linear_width
|
|
3110
|
+
|
|
3111
|
+
@linear_width.setter
|
|
3112
|
+
def linear_width(self, value):
|
|
3113
|
+
self._scale.linear_width = value
|
|
3114
|
+
|
|
3115
|
+
|
|
3116
|
+
class PowerNorm(Normalize):
|
|
3117
|
+
r"""
|
|
3118
|
+
Linearly map a given value to the 0-1 range and then apply
|
|
3119
|
+
a power-law normalization over that range.
|
|
3120
|
+
|
|
3121
|
+
Parameters
|
|
3122
|
+
----------
|
|
3123
|
+
gamma : float
|
|
3124
|
+
Power law exponent.
|
|
3125
|
+
vmin, vmax : float or None
|
|
3126
|
+
If *vmin* and/or *vmax* is not given, they are initialized from the
|
|
3127
|
+
minimum and maximum value, respectively, of the first input
|
|
3128
|
+
processed; i.e., ``__call__(A)`` calls ``autoscale_None(A)``.
|
|
3129
|
+
clip : bool, default: False
|
|
3130
|
+
Determines the behavior for mapping values outside the range
|
|
3131
|
+
``[vmin, vmax]``.
|
|
3132
|
+
|
|
3133
|
+
If clipping is off, values above *vmax* are transformed by the power
|
|
3134
|
+
function, resulting in values above 1, and values below *vmin* are linearly
|
|
3135
|
+
transformed resulting in values below 0. This behavior is usually desirable, as
|
|
3136
|
+
colormaps can mark these *under* and *over* values with specific colors.
|
|
3137
|
+
|
|
3138
|
+
If clipping is on, values below *vmin* are mapped to 0 and values above
|
|
3139
|
+
*vmax* are mapped to 1. Such values become indistinguishable from
|
|
3140
|
+
regular boundary values, which may cause misinterpretation of the data.
|
|
3141
|
+
|
|
3142
|
+
Notes
|
|
3143
|
+
-----
|
|
3144
|
+
The normalization formula is
|
|
3145
|
+
|
|
3146
|
+
.. math::
|
|
3147
|
+
|
|
3148
|
+
\left ( \frac{x - v_{min}}{v_{max} - v_{min}} \right )^{\gamma}
|
|
3149
|
+
|
|
3150
|
+
For input values below *vmin*, gamma is set to one.
|
|
3151
|
+
"""
|
|
3152
|
+
def __init__(self, gamma, vmin=None, vmax=None, clip=False):
|
|
3153
|
+
super().__init__(vmin, vmax, clip)
|
|
3154
|
+
self.gamma = gamma
|
|
3155
|
+
|
|
3156
|
+
def __call__(self, value, clip=None):
|
|
3157
|
+
if clip is None:
|
|
3158
|
+
clip = self.clip
|
|
3159
|
+
|
|
3160
|
+
result, is_scalar = self.process_value(value)
|
|
3161
|
+
|
|
3162
|
+
self.autoscale_None(result)
|
|
3163
|
+
gamma = self.gamma
|
|
3164
|
+
vmin, vmax = self.vmin, self.vmax
|
|
3165
|
+
if vmin > vmax:
|
|
3166
|
+
raise ValueError("minvalue must be less than or equal to maxvalue")
|
|
3167
|
+
elif vmin == vmax:
|
|
3168
|
+
result.fill(0)
|
|
3169
|
+
else:
|
|
3170
|
+
if clip:
|
|
3171
|
+
mask = np.ma.getmask(result)
|
|
3172
|
+
result = np.ma.array(np.clip(result.filled(vmax), vmin, vmax),
|
|
3173
|
+
mask=mask)
|
|
3174
|
+
resdat = result.data
|
|
3175
|
+
resdat -= vmin
|
|
3176
|
+
resdat /= (vmax - vmin)
|
|
3177
|
+
resdat[resdat > 0] = np.power(resdat[resdat > 0], gamma)
|
|
3178
|
+
|
|
3179
|
+
result = np.ma.array(resdat, mask=result.mask, copy=False)
|
|
3180
|
+
if is_scalar:
|
|
3181
|
+
result = result[0]
|
|
3182
|
+
return result
|
|
3183
|
+
|
|
3184
|
+
def inverse(self, value):
|
|
3185
|
+
if not self.scaled():
|
|
3186
|
+
raise ValueError("Not invertible until scaled")
|
|
3187
|
+
|
|
3188
|
+
result, is_scalar = self.process_value(value)
|
|
3189
|
+
|
|
3190
|
+
gamma = self.gamma
|
|
3191
|
+
vmin, vmax = self.vmin, self.vmax
|
|
3192
|
+
|
|
3193
|
+
resdat = result.data
|
|
3194
|
+
resdat[resdat > 0] = np.power(resdat[resdat > 0], 1 / gamma)
|
|
3195
|
+
resdat *= (vmax - vmin)
|
|
3196
|
+
resdat += vmin
|
|
3197
|
+
|
|
3198
|
+
result = np.ma.array(resdat, mask=result.mask, copy=False)
|
|
3199
|
+
if is_scalar:
|
|
3200
|
+
result = result[0]
|
|
3201
|
+
return result
|
|
3202
|
+
|
|
3203
|
+
|
|
3204
|
+
class BoundaryNorm(Normalize):
|
|
3205
|
+
"""
|
|
3206
|
+
Generate a colormap index based on discrete intervals.
|
|
3207
|
+
|
|
3208
|
+
Unlike `Normalize` or `LogNorm`, `BoundaryNorm` maps values to integers
|
|
3209
|
+
instead of to the interval 0-1.
|
|
3210
|
+
"""
|
|
3211
|
+
|
|
3212
|
+
# Mapping to the 0-1 interval could have been done via piece-wise linear
|
|
3213
|
+
# interpolation, but using integers seems simpler, and reduces the number
|
|
3214
|
+
# of conversions back and forth between int and float.
|
|
3215
|
+
|
|
3216
|
+
def __init__(self, boundaries, ncolors, clip=False, *, extend='neither'):
|
|
3217
|
+
"""
|
|
3218
|
+
Parameters
|
|
3219
|
+
----------
|
|
3220
|
+
boundaries : array-like
|
|
3221
|
+
Monotonically increasing sequence of at least 2 bin edges: data
|
|
3222
|
+
falling in the n-th bin will be mapped to the n-th color.
|
|
3223
|
+
Bins are left-closed and right-open; i.e., the n-th bin is
|
|
3224
|
+
``boundaries[n] <= value < boundaries[n + 1]``.
|
|
3225
|
+
|
|
3226
|
+
ncolors : int
|
|
3227
|
+
Number of colors in the colormap to be used.
|
|
3228
|
+
|
|
3229
|
+
clip : bool, optional
|
|
3230
|
+
If clip is ``True``, out of range values are mapped to 0 if they
|
|
3231
|
+
are below ``boundaries[0]`` or mapped to ``ncolors - 1`` if they
|
|
3232
|
+
are greater than or equal to ``boundaries[-1]``.
|
|
3233
|
+
|
|
3234
|
+
If clip is ``False``, out of range values are mapped to -1 if
|
|
3235
|
+
they are below ``boundaries[0]`` or mapped to *ncolors* if they are
|
|
3236
|
+
greater than or equal to ``boundaries[-1]``. These are then
|
|
3237
|
+
converted to valid indices by `Colormap.__call__`.
|
|
3238
|
+
|
|
3239
|
+
extend : {'neither', 'both', 'min', 'max'}, default: 'neither'
|
|
3240
|
+
Extend the number of bins to include one or both of the
|
|
3241
|
+
regions beyond the boundaries. For example, if ``extend``
|
|
3242
|
+
is 'min', then the color to which the region between the first
|
|
3243
|
+
pair of boundaries is mapped will be distinct from the first
|
|
3244
|
+
color in the colormap, and by default a
|
|
3245
|
+
`~matplotlib.colorbar.Colorbar` will be drawn with
|
|
3246
|
+
the triangle extension on the left or lower end.
|
|
3247
|
+
|
|
3248
|
+
Notes
|
|
3249
|
+
-----
|
|
3250
|
+
If there are fewer bins (including extensions) than colors, then the
|
|
3251
|
+
color index is chosen by linearly interpolating the ``[0, nbins - 1]``
|
|
3252
|
+
range onto the ``[0, ncolors - 1]`` range, effectively skipping some
|
|
3253
|
+
colors in the middle of the colormap.
|
|
3254
|
+
"""
|
|
3255
|
+
if clip and extend != 'neither':
|
|
3256
|
+
raise ValueError("'clip=True' is not compatible with 'extend'")
|
|
3257
|
+
super().__init__(vmin=boundaries[0], vmax=boundaries[-1], clip=clip)
|
|
3258
|
+
self.boundaries = np.asarray(boundaries)
|
|
3259
|
+
self.N = len(self.boundaries)
|
|
3260
|
+
if self.N < 2:
|
|
3261
|
+
raise ValueError("You must provide at least 2 boundaries "
|
|
3262
|
+
f"(1 region) but you passed in {boundaries!r}")
|
|
3263
|
+
self.Ncmap = ncolors
|
|
3264
|
+
self.extend = extend
|
|
3265
|
+
|
|
3266
|
+
self._scale = None # don't use the default scale.
|
|
3267
|
+
|
|
3268
|
+
self._n_regions = self.N - 1 # number of colors needed
|
|
3269
|
+
self._offset = 0
|
|
3270
|
+
if extend in ('min', 'both'):
|
|
3271
|
+
self._n_regions += 1
|
|
3272
|
+
self._offset = 1
|
|
3273
|
+
if extend in ('max', 'both'):
|
|
3274
|
+
self._n_regions += 1
|
|
3275
|
+
if self._n_regions > self.Ncmap:
|
|
3276
|
+
raise ValueError(f"There are {self._n_regions} color bins "
|
|
3277
|
+
"including extensions, but ncolors = "
|
|
3278
|
+
f"{ncolors}; ncolors must equal or exceed the "
|
|
3279
|
+
"number of bins")
|
|
3280
|
+
|
|
3281
|
+
def __call__(self, value, clip=None):
|
|
3282
|
+
"""
|
|
3283
|
+
This method behaves similarly to `.Normalize.__call__`, except that it
|
|
3284
|
+
returns integers or arrays of int16.
|
|
3285
|
+
"""
|
|
3286
|
+
if clip is None:
|
|
3287
|
+
clip = self.clip
|
|
3288
|
+
|
|
3289
|
+
xx, is_scalar = self.process_value(value)
|
|
3290
|
+
mask = np.ma.getmaskarray(xx)
|
|
3291
|
+
# Fill masked values a value above the upper boundary
|
|
3292
|
+
xx = np.atleast_1d(xx.filled(self.vmax + 1))
|
|
3293
|
+
if clip:
|
|
3294
|
+
np.clip(xx, self.vmin, self.vmax, out=xx)
|
|
3295
|
+
max_col = self.Ncmap - 1
|
|
3296
|
+
else:
|
|
3297
|
+
max_col = self.Ncmap
|
|
3298
|
+
# this gives us the bins in the lookup table in the range
|
|
3299
|
+
# [0, _n_regions - 1] (the offset is set in the init)
|
|
3300
|
+
iret = np.digitize(xx, self.boundaries) - 1 + self._offset
|
|
3301
|
+
# if we have more colors than regions, stretch the region
|
|
3302
|
+
# index computed above to full range of the color bins. This
|
|
3303
|
+
# will make use of the full range (but skip some of the colors
|
|
3304
|
+
# in the middle) such that the first region is mapped to the
|
|
3305
|
+
# first color and the last region is mapped to the last color.
|
|
3306
|
+
if self.Ncmap > self._n_regions:
|
|
3307
|
+
if self._n_regions == 1:
|
|
3308
|
+
# special case the 1 region case, pick the middle color
|
|
3309
|
+
iret[iret == 0] = (self.Ncmap - 1) // 2
|
|
3310
|
+
else:
|
|
3311
|
+
# otherwise linearly remap the values from the region index
|
|
3312
|
+
# to the color index spaces
|
|
3313
|
+
iret = (self.Ncmap - 1) / (self._n_regions - 1) * iret
|
|
3314
|
+
# cast to 16bit integers in all cases
|
|
3315
|
+
iret = iret.astype(np.int16)
|
|
3316
|
+
iret[xx < self.vmin] = -1
|
|
3317
|
+
iret[xx >= self.vmax] = max_col
|
|
3318
|
+
ret = np.ma.array(iret, mask=mask)
|
|
3319
|
+
if is_scalar:
|
|
3320
|
+
ret = int(ret[0]) # assume python scalar
|
|
3321
|
+
return ret
|
|
3322
|
+
|
|
3323
|
+
def inverse(self, value):
|
|
3324
|
+
"""
|
|
3325
|
+
Raises
|
|
3326
|
+
------
|
|
3327
|
+
ValueError
|
|
3328
|
+
BoundaryNorm is not invertible, so calling this method will always
|
|
3329
|
+
raise an error
|
|
3330
|
+
"""
|
|
3331
|
+
raise ValueError("BoundaryNorm is not invertible")
|
|
3332
|
+
|
|
3333
|
+
|
|
3334
|
+
class NoNorm(Normalize):
|
|
3335
|
+
"""
|
|
3336
|
+
Dummy replacement for `Normalize`, for the case where we want to use
|
|
3337
|
+
indices directly in a `~matplotlib.cm.ScalarMappable`.
|
|
3338
|
+
"""
|
|
3339
|
+
def __call__(self, value, clip=None):
|
|
3340
|
+
if np.iterable(value):
|
|
3341
|
+
return np.ma.array(value)
|
|
3342
|
+
return value
|
|
3343
|
+
|
|
3344
|
+
def inverse(self, value):
|
|
3345
|
+
if np.iterable(value):
|
|
3346
|
+
return np.ma.array(value)
|
|
3347
|
+
return value
|
|
3348
|
+
|
|
3349
|
+
|
|
3350
|
+
class MultiNorm(Norm):
|
|
3351
|
+
"""
|
|
3352
|
+
A class which contains multiple scalar norms.
|
|
3353
|
+
"""
|
|
3354
|
+
|
|
3355
|
+
def __init__(self, norms, vmin=None, vmax=None, clip=None):
|
|
3356
|
+
"""
|
|
3357
|
+
Parameters
|
|
3358
|
+
----------
|
|
3359
|
+
norms : list of (str or `Normalize`)
|
|
3360
|
+
The constituent norms. The list must have a minimum length of 1.
|
|
3361
|
+
vmin, vmax : None or list of (float or None)
|
|
3362
|
+
Limits of the constituent norms.
|
|
3363
|
+
If a list, one value is assigned to each of the constituent
|
|
3364
|
+
norms.
|
|
3365
|
+
If None, the limits of the constituent norms
|
|
3366
|
+
are not changed.
|
|
3367
|
+
clip : None or list of bools, default: None
|
|
3368
|
+
Determines the behavior for mapping values outside the range
|
|
3369
|
+
``[vmin, vmax]`` for the constituent norms.
|
|
3370
|
+
If a list, each value is assigned to each of the constituent
|
|
3371
|
+
norms.
|
|
3372
|
+
If None, the behaviour of the constituent norms is not changed.
|
|
3373
|
+
"""
|
|
3374
|
+
if cbook.is_scalar_or_string(norms):
|
|
3375
|
+
raise ValueError(
|
|
3376
|
+
"MultiNorm must be assigned an iterable of norms, where each "
|
|
3377
|
+
f"norm is of type `str`, or `Normalize`, not {type(norms)}")
|
|
3378
|
+
|
|
3379
|
+
if len(norms) < 1:
|
|
3380
|
+
raise ValueError("MultiNorm must be assigned at least one norm")
|
|
3381
|
+
|
|
3382
|
+
def resolve(norm):
|
|
3383
|
+
if isinstance(norm, str):
|
|
3384
|
+
scale_cls = _api.getitem_checked(scale._scale_mapping, norm=norm)
|
|
3385
|
+
return mpl.colorizer._auto_norm_from_scale(scale_cls)()
|
|
3386
|
+
elif isinstance(norm, Normalize):
|
|
3387
|
+
return norm
|
|
3388
|
+
else:
|
|
3389
|
+
raise ValueError(
|
|
3390
|
+
"Each norm assigned to MultiNorm must be "
|
|
3391
|
+
f"of type `str`, or `Normalize`, not {type(norm)}")
|
|
3392
|
+
|
|
3393
|
+
self._norms = tuple(resolve(norm) for norm in norms)
|
|
3394
|
+
|
|
3395
|
+
self.callbacks = cbook.CallbackRegistry(signals=["changed"])
|
|
3396
|
+
|
|
3397
|
+
self.vmin = vmin
|
|
3398
|
+
self.vmax = vmax
|
|
3399
|
+
self.clip = clip
|
|
3400
|
+
|
|
3401
|
+
for n in self._norms:
|
|
3402
|
+
n.callbacks.connect('changed', self._changed)
|
|
3403
|
+
|
|
3404
|
+
@property
|
|
3405
|
+
def n_components(self):
|
|
3406
|
+
"""Number of norms held by this `MultiNorm`."""
|
|
3407
|
+
return len(self._norms)
|
|
3408
|
+
|
|
3409
|
+
@property
|
|
3410
|
+
def norms(self):
|
|
3411
|
+
"""The individual norms held by this `MultiNorm`."""
|
|
3412
|
+
return self._norms
|
|
3413
|
+
|
|
3414
|
+
@property
|
|
3415
|
+
def vmin(self):
|
|
3416
|
+
"""The lower limit of each constituent norm."""
|
|
3417
|
+
return tuple(n.vmin for n in self._norms)
|
|
3418
|
+
|
|
3419
|
+
@vmin.setter
|
|
3420
|
+
def vmin(self, values):
|
|
3421
|
+
if values is None:
|
|
3422
|
+
return
|
|
3423
|
+
if not np.iterable(values) or len(values) != self.n_components:
|
|
3424
|
+
raise ValueError("*vmin* must have one component for each norm. "
|
|
3425
|
+
f"Expected an iterable of length {self.n_components}, "
|
|
3426
|
+
f"but got {values!r}")
|
|
3427
|
+
with self.callbacks.blocked():
|
|
3428
|
+
for norm, v in zip(self.norms, values):
|
|
3429
|
+
norm.vmin = v
|
|
3430
|
+
self._changed()
|
|
3431
|
+
|
|
3432
|
+
@property
|
|
3433
|
+
def vmax(self):
|
|
3434
|
+
"""The upper limit of each constituent norm."""
|
|
3435
|
+
return tuple(n.vmax for n in self._norms)
|
|
3436
|
+
|
|
3437
|
+
@vmax.setter
|
|
3438
|
+
def vmax(self, values):
|
|
3439
|
+
if values is None:
|
|
3440
|
+
return
|
|
3441
|
+
if not np.iterable(values) or len(values) != self.n_components:
|
|
3442
|
+
raise ValueError("*vmax* must have one component for each norm. "
|
|
3443
|
+
f"Expected an iterable of length {self.n_components}, "
|
|
3444
|
+
f"but got {values!r}")
|
|
3445
|
+
with self.callbacks.blocked():
|
|
3446
|
+
for norm, v in zip(self.norms, values):
|
|
3447
|
+
norm.vmax = v
|
|
3448
|
+
self._changed()
|
|
3449
|
+
|
|
3450
|
+
@property
|
|
3451
|
+
def clip(self):
|
|
3452
|
+
"""The clip behaviour of each constituent norm."""
|
|
3453
|
+
return tuple(n.clip for n in self._norms)
|
|
3454
|
+
|
|
3455
|
+
@clip.setter
|
|
3456
|
+
def clip(self, values):
|
|
3457
|
+
if values is None:
|
|
3458
|
+
return
|
|
3459
|
+
if not np.iterable(values) or len(values) != self.n_components:
|
|
3460
|
+
raise ValueError("*clip* must have one component for each norm. "
|
|
3461
|
+
f"Expected an iterable of length {self.n_components}, "
|
|
3462
|
+
f"but got {values!r}")
|
|
3463
|
+
with self.callbacks.blocked():
|
|
3464
|
+
for norm, v in zip(self.norms, values):
|
|
3465
|
+
norm.clip = v
|
|
3466
|
+
self._changed()
|
|
3467
|
+
|
|
3468
|
+
def _changed(self):
|
|
3469
|
+
"""
|
|
3470
|
+
Call this whenever the norm is changed to notify all the
|
|
3471
|
+
callback listeners to the 'changed' signal.
|
|
3472
|
+
"""
|
|
3473
|
+
self.callbacks.process('changed')
|
|
3474
|
+
|
|
3475
|
+
def __call__(self, values, clip=None):
|
|
3476
|
+
"""
|
|
3477
|
+
Normalize the data and return the normalized data.
|
|
3478
|
+
|
|
3479
|
+
Each component of the input is normalized via the constituent norm.
|
|
3480
|
+
|
|
3481
|
+
Parameters
|
|
3482
|
+
----------
|
|
3483
|
+
values : array-like
|
|
3484
|
+
The input data, as an iterable or a structured numpy array.
|
|
3485
|
+
|
|
3486
|
+
- If iterable, must be of length `n_components`. Each element can be a
|
|
3487
|
+
scalar or array-like and is normalized through the corresponding norm.
|
|
3488
|
+
- If structured array, must have `n_components` fields. Each field
|
|
3489
|
+
is normalized through the corresponding norm.
|
|
3490
|
+
|
|
3491
|
+
clip : list of bools or None, optional
|
|
3492
|
+
Determines the behavior for mapping values outside the range
|
|
3493
|
+
``[vmin, vmax]``. See the description of the parameter *clip* in
|
|
3494
|
+
`.Normalize`.
|
|
3495
|
+
If ``None``, defaults to ``self.clip`` (which defaults to
|
|
3496
|
+
``False``).
|
|
3497
|
+
|
|
3498
|
+
Returns
|
|
3499
|
+
-------
|
|
3500
|
+
tuple
|
|
3501
|
+
Normalized input values
|
|
3502
|
+
|
|
3503
|
+
Notes
|
|
3504
|
+
-----
|
|
3505
|
+
If not already initialized, ``self.vmin`` and ``self.vmax`` are
|
|
3506
|
+
initialized using ``self.autoscale_None(values)``.
|
|
3507
|
+
"""
|
|
3508
|
+
if clip is None:
|
|
3509
|
+
clip = self.clip
|
|
3510
|
+
if not np.iterable(clip) or len(clip) != self.n_components:
|
|
3511
|
+
raise ValueError("*clip* must have one component for each norm. "
|
|
3512
|
+
f"Expected an iterable of length {self.n_components}, "
|
|
3513
|
+
f"but got {clip!r}")
|
|
3514
|
+
|
|
3515
|
+
values = self._iterable_components_in_data(values, self.n_components)
|
|
3516
|
+
result = tuple(n(v, clip=c) for n, v, c in zip(self.norms, values, clip))
|
|
3517
|
+
return result
|
|
3518
|
+
|
|
3519
|
+
def inverse(self, values):
|
|
3520
|
+
"""
|
|
3521
|
+
Map the normalized values (i.e., index in the colormap) back to data values.
|
|
3522
|
+
|
|
3523
|
+
Parameters
|
|
3524
|
+
----------
|
|
3525
|
+
values : array-like
|
|
3526
|
+
The input data, as an iterable or a structured numpy array.
|
|
3527
|
+
|
|
3528
|
+
- If iterable, must be of length `n_components`. Each element can be a
|
|
3529
|
+
scalar or array-like and is mapped through the corresponding norm.
|
|
3530
|
+
- If structured array, must have `n_components` fields. Each field
|
|
3531
|
+
is mapped through the corresponding norm.
|
|
3532
|
+
|
|
3533
|
+
"""
|
|
3534
|
+
values = self._iterable_components_in_data(values, self.n_components)
|
|
3535
|
+
result = tuple(n.inverse(v) for n, v in zip(self.norms, values))
|
|
3536
|
+
return result
|
|
3537
|
+
|
|
3538
|
+
def autoscale(self, A):
|
|
3539
|
+
"""
|
|
3540
|
+
For each constituent norm, set *vmin*, *vmax* to min, max of the corresponding
|
|
3541
|
+
component in *A*.
|
|
3542
|
+
|
|
3543
|
+
Parameters
|
|
3544
|
+
----------
|
|
3545
|
+
A : array-like
|
|
3546
|
+
The input data, as an iterable or a structured numpy array.
|
|
3547
|
+
|
|
3548
|
+
- If iterable, must be of length `n_components`. Each element
|
|
3549
|
+
is used for the limits of one constituent norm.
|
|
3550
|
+
- If structured array, must have `n_components` fields. Each field
|
|
3551
|
+
is used for the limits of one constituent norm.
|
|
3552
|
+
"""
|
|
3553
|
+
with self.callbacks.blocked():
|
|
3554
|
+
A = self._iterable_components_in_data(A, self.n_components)
|
|
3555
|
+
for n, a in zip(self.norms, A):
|
|
3556
|
+
n.autoscale(a)
|
|
3557
|
+
self._changed()
|
|
3558
|
+
|
|
3559
|
+
def autoscale_None(self, A):
|
|
3560
|
+
"""
|
|
3561
|
+
If *vmin* or *vmax* are not set on any constituent norm,
|
|
3562
|
+
use the min/max of the corresponding component in *A* to set them.
|
|
3563
|
+
|
|
3564
|
+
Parameters
|
|
3565
|
+
----------
|
|
3566
|
+
A : array-like
|
|
3567
|
+
The input data, as an iterable or a structured numpy array.
|
|
3568
|
+
|
|
3569
|
+
- If iterable, must be of length `n_components`. Each element
|
|
3570
|
+
is used for the limits of one constituent norm.
|
|
3571
|
+
- If structured array, must have `n_components` fields. Each field
|
|
3572
|
+
is used for the limits of one constituent norm.
|
|
3573
|
+
"""
|
|
3574
|
+
with self.callbacks.blocked():
|
|
3575
|
+
A = self._iterable_components_in_data(A, self.n_components)
|
|
3576
|
+
for n, a in zip(self.norms, A):
|
|
3577
|
+
n.autoscale_None(a)
|
|
3578
|
+
self._changed()
|
|
3579
|
+
|
|
3580
|
+
def scaled(self):
|
|
3581
|
+
"""Return whether both *vmin* and *vmax* are set on all constituent norms."""
|
|
3582
|
+
return all(n.scaled() for n in self.norms)
|
|
3583
|
+
|
|
3584
|
+
@staticmethod
|
|
3585
|
+
def _iterable_components_in_data(data, n_components):
|
|
3586
|
+
"""
|
|
3587
|
+
Provides an iterable over the components contained in the data.
|
|
3588
|
+
|
|
3589
|
+
An input array with `n_components` fields is returned as a tuple of length n
|
|
3590
|
+
referencing slices of the original array.
|
|
3591
|
+
|
|
3592
|
+
Parameters
|
|
3593
|
+
----------
|
|
3594
|
+
data : array-like
|
|
3595
|
+
The input data, as an iterable or a structured numpy array.
|
|
3596
|
+
|
|
3597
|
+
- If iterable, must be of length `n_components`
|
|
3598
|
+
- If structured array, must have `n_components` fields.
|
|
3599
|
+
|
|
3600
|
+
Returns
|
|
3601
|
+
-------
|
|
3602
|
+
tuple of np.ndarray
|
|
3603
|
+
|
|
3604
|
+
"""
|
|
3605
|
+
if isinstance(data, np.ndarray) and data.dtype.fields is not None:
|
|
3606
|
+
# structured array
|
|
3607
|
+
if len(data.dtype.fields) != n_components:
|
|
3608
|
+
raise ValueError(
|
|
3609
|
+
"Structured array inputs to MultiNorm must have the same "
|
|
3610
|
+
"number of fields as components in the MultiNorm. Expected "
|
|
3611
|
+
f"{n_components}, but got {len(data.dtype.fields)} fields"
|
|
3612
|
+
)
|
|
3613
|
+
else:
|
|
3614
|
+
return tuple(data[field] for field in data.dtype.names)
|
|
3615
|
+
try:
|
|
3616
|
+
n_elements = len(data)
|
|
3617
|
+
except TypeError:
|
|
3618
|
+
raise ValueError("MultiNorm expects a sequence with one element per "
|
|
3619
|
+
f"component as input, but got {data!r} instead")
|
|
3620
|
+
if n_elements != n_components:
|
|
3621
|
+
if isinstance(data, np.ndarray) and data.shape[-1] == n_components:
|
|
3622
|
+
if len(data.shape) == 2:
|
|
3623
|
+
raise ValueError(
|
|
3624
|
+
f"MultiNorm expects a sequence with one element per component. "
|
|
3625
|
+
"You can use `data_transposed = data.T` "
|
|
3626
|
+
"to convert the input data of shape "
|
|
3627
|
+
f"{data.shape} to a compatible shape {data.shape[::-1]}")
|
|
3628
|
+
else:
|
|
3629
|
+
raise ValueError(
|
|
3630
|
+
f"MultiNorm expects a sequence with one element per component. "
|
|
3631
|
+
"You can use `data_as_list = [data[..., i] for i in "
|
|
3632
|
+
"range(data.shape[-1])]` to convert the input data of shape "
|
|
3633
|
+
f" {data.shape} to a compatible list")
|
|
3634
|
+
|
|
3635
|
+
raise ValueError(
|
|
3636
|
+
"MultiNorm expects a sequence with one element per component. "
|
|
3637
|
+
f"This MultiNorm has {n_components} components, but got a sequence "
|
|
3638
|
+
f"with {n_elements} elements"
|
|
3639
|
+
)
|
|
3640
|
+
|
|
3641
|
+
return tuple(data[i] for i in range(n_elements))
|
|
3642
|
+
|
|
3643
|
+
|
|
3644
|
+
def rgb_to_hsv(arr):
|
|
3645
|
+
"""
|
|
3646
|
+
Convert an array of float RGB values (in the range [0, 1]) to HSV values.
|
|
3647
|
+
|
|
3648
|
+
Parameters
|
|
3649
|
+
----------
|
|
3650
|
+
arr : (..., 3) array-like
|
|
3651
|
+
All values must be in the range [0, 1]
|
|
3652
|
+
|
|
3653
|
+
Returns
|
|
3654
|
+
-------
|
|
3655
|
+
(..., 3) `~numpy.ndarray`
|
|
3656
|
+
Colors converted to HSV values in range [0, 1]
|
|
3657
|
+
"""
|
|
3658
|
+
arr = np.asarray(arr)
|
|
3659
|
+
|
|
3660
|
+
# check length of the last dimension, should be _some_ sort of rgb
|
|
3661
|
+
if arr.shape[-1] != 3:
|
|
3662
|
+
raise ValueError("Last dimension of input array must be 3; "
|
|
3663
|
+
f"shape {arr.shape} was found.")
|
|
3664
|
+
|
|
3665
|
+
in_shape = arr.shape
|
|
3666
|
+
# ensure numerics are done at least on float32; ints are cast as well
|
|
3667
|
+
arr = np.asarray(arr, dtype=np.promote_types(arr.dtype, np.float32))
|
|
3668
|
+
if arr.ndim == 1:
|
|
3669
|
+
arr = np.expand_dims(arr, axis=0) # ensure arr is 2D
|
|
3670
|
+
|
|
3671
|
+
out = np.zeros_like(arr)
|
|
3672
|
+
arr_max = arr.max(-1)
|
|
3673
|
+
# Check if input is in the expected range
|
|
3674
|
+
if np.any(arr_max > 1):
|
|
3675
|
+
raise ValueError(
|
|
3676
|
+
"Input array must be in the range [0, 1]. "
|
|
3677
|
+
f"Found a maximum value of {arr_max.max()}"
|
|
3678
|
+
)
|
|
3679
|
+
|
|
3680
|
+
if arr.min() < 0:
|
|
3681
|
+
raise ValueError(
|
|
3682
|
+
"Input array must be in the range [0, 1]. "
|
|
3683
|
+
f"Found a minimum value of {arr.min()}"
|
|
3684
|
+
)
|
|
3685
|
+
|
|
3686
|
+
ipos = arr_max > 0
|
|
3687
|
+
delta = np.ptp(arr, -1)
|
|
3688
|
+
s = np.zeros_like(delta)
|
|
3689
|
+
s[ipos] = delta[ipos] / arr_max[ipos]
|
|
3690
|
+
ipos = delta > 0
|
|
3691
|
+
# red is max
|
|
3692
|
+
idx = (arr[..., 0] == arr_max) & ipos
|
|
3693
|
+
out[idx, 0] = (arr[idx, 1] - arr[idx, 2]) / delta[idx]
|
|
3694
|
+
# green is max
|
|
3695
|
+
idx = (arr[..., 1] == arr_max) & ipos
|
|
3696
|
+
out[idx, 0] = 2. + (arr[idx, 2] - arr[idx, 0]) / delta[idx]
|
|
3697
|
+
# blue is max
|
|
3698
|
+
idx = (arr[..., 2] == arr_max) & ipos
|
|
3699
|
+
out[idx, 0] = 4. + (arr[idx, 0] - arr[idx, 1]) / delta[idx]
|
|
3700
|
+
|
|
3701
|
+
out[..., 0] = (out[..., 0] / 6.0) % 1.0
|
|
3702
|
+
out[..., 1] = s
|
|
3703
|
+
out[..., 2] = arr_max
|
|
3704
|
+
|
|
3705
|
+
return out.reshape(in_shape)
|
|
3706
|
+
|
|
3707
|
+
|
|
3708
|
+
def hsv_to_rgb(hsv):
|
|
3709
|
+
"""
|
|
3710
|
+
Convert HSV values to RGB.
|
|
3711
|
+
|
|
3712
|
+
Parameters
|
|
3713
|
+
----------
|
|
3714
|
+
hsv : (..., 3) array-like
|
|
3715
|
+
All values assumed to be in range [0, 1]
|
|
3716
|
+
|
|
3717
|
+
Returns
|
|
3718
|
+
-------
|
|
3719
|
+
(..., 3) `~numpy.ndarray`
|
|
3720
|
+
Colors converted to RGB values in range [0, 1]
|
|
3721
|
+
"""
|
|
3722
|
+
hsv = np.asarray(hsv)
|
|
3723
|
+
|
|
3724
|
+
# check length of the last dimension, should be _some_ sort of rgb
|
|
3725
|
+
if hsv.shape[-1] != 3:
|
|
3726
|
+
raise ValueError("Last dimension of input array must be 3; "
|
|
3727
|
+
f"shape {hsv.shape} was found.")
|
|
3728
|
+
|
|
3729
|
+
in_shape = hsv.shape
|
|
3730
|
+
# ensure numerics are done at least on float32; ints are cast as well
|
|
3731
|
+
hsv = np.asarray(hsv, dtype=np.promote_types(hsv.dtype, np.float32))
|
|
3732
|
+
if hsv.ndim == 1:
|
|
3733
|
+
hsv = np.expand_dims(hsv, axis=0) # ensure hsv is 2D
|
|
3734
|
+
|
|
3735
|
+
h = hsv[..., 0]
|
|
3736
|
+
s = hsv[..., 1]
|
|
3737
|
+
v = hsv[..., 2]
|
|
3738
|
+
|
|
3739
|
+
r = np.empty_like(h)
|
|
3740
|
+
g = np.empty_like(h)
|
|
3741
|
+
b = np.empty_like(h)
|
|
3742
|
+
|
|
3743
|
+
i = (h * 6.0).astype(int)
|
|
3744
|
+
f = (h * 6.0) - i
|
|
3745
|
+
p = v * (1.0 - s)
|
|
3746
|
+
q = v * (1.0 - s * f)
|
|
3747
|
+
t = v * (1.0 - s * (1.0 - f))
|
|
3748
|
+
|
|
3749
|
+
idx = i % 6 == 0
|
|
3750
|
+
r[idx] = v[idx]
|
|
3751
|
+
g[idx] = t[idx]
|
|
3752
|
+
b[idx] = p[idx]
|
|
3753
|
+
|
|
3754
|
+
idx = i == 1
|
|
3755
|
+
r[idx] = q[idx]
|
|
3756
|
+
g[idx] = v[idx]
|
|
3757
|
+
b[idx] = p[idx]
|
|
3758
|
+
|
|
3759
|
+
idx = i == 2
|
|
3760
|
+
r[idx] = p[idx]
|
|
3761
|
+
g[idx] = v[idx]
|
|
3762
|
+
b[idx] = t[idx]
|
|
3763
|
+
|
|
3764
|
+
idx = i == 3
|
|
3765
|
+
r[idx] = p[idx]
|
|
3766
|
+
g[idx] = q[idx]
|
|
3767
|
+
b[idx] = v[idx]
|
|
3768
|
+
|
|
3769
|
+
idx = i == 4
|
|
3770
|
+
r[idx] = t[idx]
|
|
3771
|
+
g[idx] = p[idx]
|
|
3772
|
+
b[idx] = v[idx]
|
|
3773
|
+
|
|
3774
|
+
idx = i == 5
|
|
3775
|
+
r[idx] = v[idx]
|
|
3776
|
+
g[idx] = p[idx]
|
|
3777
|
+
b[idx] = q[idx]
|
|
3778
|
+
|
|
3779
|
+
idx = s == 0
|
|
3780
|
+
r[idx] = v[idx]
|
|
3781
|
+
g[idx] = v[idx]
|
|
3782
|
+
b[idx] = v[idx]
|
|
3783
|
+
|
|
3784
|
+
rgb = np.stack([r, g, b], axis=-1)
|
|
3785
|
+
|
|
3786
|
+
return rgb.reshape(in_shape)
|
|
3787
|
+
|
|
3788
|
+
|
|
3789
|
+
def _vector_magnitude(arr):
|
|
3790
|
+
# things that don't work here:
|
|
3791
|
+
# * np.linalg.norm: drops mask from ma.array
|
|
3792
|
+
# * np.sum: drops mask from ma.array unless entire vector is masked
|
|
3793
|
+
sum_sq = 0
|
|
3794
|
+
for i in range(arr.shape[-1]):
|
|
3795
|
+
sum_sq += arr[..., i, np.newaxis] ** 2
|
|
3796
|
+
return np.sqrt(sum_sq)
|
|
3797
|
+
|
|
3798
|
+
|
|
3799
|
+
class LightSource:
|
|
3800
|
+
"""
|
|
3801
|
+
Create a light source coming from the specified azimuth and elevation.
|
|
3802
|
+
Angles are in degrees, with the azimuth measured
|
|
3803
|
+
clockwise from north and elevation up from the zero plane of the surface.
|
|
3804
|
+
|
|
3805
|
+
`shade` is used to produce "shaded" RGB values for a data array.
|
|
3806
|
+
`shade_rgb` can be used to combine an RGB image with an elevation map.
|
|
3807
|
+
`hillshade` produces an illumination map of a surface.
|
|
3808
|
+
"""
|
|
3809
|
+
|
|
3810
|
+
def __init__(self, azdeg=315, altdeg=45, hsv_min_val=0, hsv_max_val=1,
|
|
3811
|
+
hsv_min_sat=1, hsv_max_sat=0):
|
|
3812
|
+
"""
|
|
3813
|
+
Specify the azimuth (measured clockwise from south) and altitude
|
|
3814
|
+
(measured up from the plane of the surface) of the light source
|
|
3815
|
+
in degrees.
|
|
3816
|
+
|
|
3817
|
+
Parameters
|
|
3818
|
+
----------
|
|
3819
|
+
azdeg : float, default: 315 degrees (from the northwest)
|
|
3820
|
+
The azimuth (0-360, degrees clockwise from North) of the light
|
|
3821
|
+
source.
|
|
3822
|
+
altdeg : float, default: 45 degrees
|
|
3823
|
+
The altitude (0-90, degrees up from horizontal) of the light
|
|
3824
|
+
source.
|
|
3825
|
+
hsv_min_val : number, default: 0
|
|
3826
|
+
The minimum value ("v" in "hsv") that the *intensity* map can shift the
|
|
3827
|
+
output image to.
|
|
3828
|
+
hsv_max_val : number, default: 1
|
|
3829
|
+
The maximum value ("v" in "hsv") that the *intensity* map can shift the
|
|
3830
|
+
output image to.
|
|
3831
|
+
hsv_min_sat : number, default: 1
|
|
3832
|
+
The minimum saturation value that the *intensity* map can shift the output
|
|
3833
|
+
image to.
|
|
3834
|
+
hsv_max_sat : number, default: 0
|
|
3835
|
+
The maximum saturation value that the *intensity* map can shift the output
|
|
3836
|
+
image to.
|
|
3837
|
+
|
|
3838
|
+
Notes
|
|
3839
|
+
-----
|
|
3840
|
+
For backwards compatibility, the parameters *hsv_min_val*,
|
|
3841
|
+
*hsv_max_val*, *hsv_min_sat*, and *hsv_max_sat* may be supplied at
|
|
3842
|
+
initialization as well. However, these parameters will only be used if
|
|
3843
|
+
"blend_mode='hsv'" is passed into `shade` or `shade_rgb`.
|
|
3844
|
+
See the documentation for `blend_hsv` for more details.
|
|
3845
|
+
"""
|
|
3846
|
+
self.azdeg = azdeg
|
|
3847
|
+
self.altdeg = altdeg
|
|
3848
|
+
self.hsv_min_val = hsv_min_val
|
|
3849
|
+
self.hsv_max_val = hsv_max_val
|
|
3850
|
+
self.hsv_min_sat = hsv_min_sat
|
|
3851
|
+
self.hsv_max_sat = hsv_max_sat
|
|
3852
|
+
|
|
3853
|
+
@property
|
|
3854
|
+
def direction(self):
|
|
3855
|
+
"""The unit vector direction towards the light source."""
|
|
3856
|
+
# Azimuth is in degrees clockwise from North. Convert to radians
|
|
3857
|
+
# counterclockwise from East (mathematical notation).
|
|
3858
|
+
az = np.radians(90 - self.azdeg)
|
|
3859
|
+
alt = np.radians(self.altdeg)
|
|
3860
|
+
return np.array([
|
|
3861
|
+
np.cos(az) * np.cos(alt),
|
|
3862
|
+
np.sin(az) * np.cos(alt),
|
|
3863
|
+
np.sin(alt)
|
|
3864
|
+
])
|
|
3865
|
+
|
|
3866
|
+
def hillshade(self, elevation, vert_exag=1, dx=1, dy=1, fraction=1.):
|
|
3867
|
+
"""
|
|
3868
|
+
Calculate the illumination intensity for a surface using the defined
|
|
3869
|
+
azimuth and elevation for the light source.
|
|
3870
|
+
|
|
3871
|
+
This computes the normal vectors for the surface, and then passes them
|
|
3872
|
+
on to `shade_normals`
|
|
3873
|
+
|
|
3874
|
+
Parameters
|
|
3875
|
+
----------
|
|
3876
|
+
elevation : 2D array-like
|
|
3877
|
+
The height values used to generate an illumination map
|
|
3878
|
+
vert_exag : number, optional
|
|
3879
|
+
The amount to exaggerate the elevation values by when calculating
|
|
3880
|
+
illumination. This can be used either to correct for differences in
|
|
3881
|
+
units between the x-y coordinate system and the elevation
|
|
3882
|
+
coordinate system (e.g. decimal degrees vs. meters) or to
|
|
3883
|
+
exaggerate or de-emphasize topographic effects.
|
|
3884
|
+
dx : number, optional
|
|
3885
|
+
The x-spacing (columns) of the input *elevation* grid.
|
|
3886
|
+
dy : number, optional
|
|
3887
|
+
The y-spacing (rows) of the input *elevation* grid.
|
|
3888
|
+
fraction : number, optional
|
|
3889
|
+
Increases or decreases the contrast of the hillshade. Values
|
|
3890
|
+
greater than one will cause intermediate values to move closer to
|
|
3891
|
+
full illumination or shadow (and clipping any values that move
|
|
3892
|
+
beyond 0 or 1). Note that this is not visually or mathematically
|
|
3893
|
+
the same as vertical exaggeration.
|
|
3894
|
+
|
|
3895
|
+
Returns
|
|
3896
|
+
-------
|
|
3897
|
+
`~numpy.ndarray`
|
|
3898
|
+
A 2D array of illumination values between 0-1, where 0 is
|
|
3899
|
+
completely in shadow and 1 is completely illuminated.
|
|
3900
|
+
"""
|
|
3901
|
+
|
|
3902
|
+
# Because most image and raster GIS data has the first row in the array
|
|
3903
|
+
# as the "top" of the image, dy is implicitly negative. This is
|
|
3904
|
+
# consistent to what `imshow` assumes, as well.
|
|
3905
|
+
dy = -dy
|
|
3906
|
+
|
|
3907
|
+
# compute the normal vectors from the partial derivatives
|
|
3908
|
+
e_dy, e_dx = np.gradient(vert_exag * elevation, dy, dx)
|
|
3909
|
+
|
|
3910
|
+
# .view is to keep subclasses
|
|
3911
|
+
normal = np.empty(elevation.shape + (3,)).view(type(elevation))
|
|
3912
|
+
normal[..., 0] = -e_dx
|
|
3913
|
+
normal[..., 1] = -e_dy
|
|
3914
|
+
normal[..., 2] = 1
|
|
3915
|
+
normal /= _vector_magnitude(normal)
|
|
3916
|
+
|
|
3917
|
+
return self.shade_normals(normal, fraction)
|
|
3918
|
+
|
|
3919
|
+
def shade_normals(self, normals, fraction=1.):
|
|
3920
|
+
"""
|
|
3921
|
+
Calculate the illumination intensity for the normal vectors of a
|
|
3922
|
+
surface using the defined azimuth and elevation for the light source.
|
|
3923
|
+
|
|
3924
|
+
Imagine an artificial sun placed at infinity in some azimuth and
|
|
3925
|
+
elevation position illuminating our surface. The parts of the surface
|
|
3926
|
+
that slope toward the sun should brighten while those sides facing away
|
|
3927
|
+
should become darker.
|
|
3928
|
+
|
|
3929
|
+
Parameters
|
|
3930
|
+
----------
|
|
3931
|
+
fraction : number, optional
|
|
3932
|
+
Increases or decreases the contrast of the hillshade. Values
|
|
3933
|
+
greater than one will cause intermediate values to move closer to
|
|
3934
|
+
full illumination or shadow (and clipping any values that move
|
|
3935
|
+
beyond 0 or 1). Note that this is not visually or mathematically
|
|
3936
|
+
the same as vertical exaggeration.
|
|
3937
|
+
|
|
3938
|
+
Returns
|
|
3939
|
+
-------
|
|
3940
|
+
`~numpy.ndarray`
|
|
3941
|
+
A 2D array of illumination values between 0-1, where 0 is
|
|
3942
|
+
completely in shadow and 1 is completely illuminated.
|
|
3943
|
+
"""
|
|
3944
|
+
|
|
3945
|
+
intensity = normals.dot(self.direction)
|
|
3946
|
+
|
|
3947
|
+
# Apply contrast stretch
|
|
3948
|
+
imin, imax = intensity.min(), intensity.max()
|
|
3949
|
+
intensity *= fraction
|
|
3950
|
+
|
|
3951
|
+
# Rescale to 0-1, keeping range before contrast stretch
|
|
3952
|
+
# If constant slope, keep relative scaling (i.e. flat should be 0.5,
|
|
3953
|
+
# fully occluded 0, etc.)
|
|
3954
|
+
if (imax - imin) > 1e-6:
|
|
3955
|
+
# Strictly speaking, this is incorrect. Negative values should be
|
|
3956
|
+
# clipped to 0 because they're fully occluded. However, rescaling
|
|
3957
|
+
# in this manner is consistent with the previous implementation and
|
|
3958
|
+
# visually appears better than a "hard" clip.
|
|
3959
|
+
intensity -= imin
|
|
3960
|
+
intensity /= (imax - imin)
|
|
3961
|
+
intensity = np.clip(intensity, 0, 1)
|
|
3962
|
+
|
|
3963
|
+
return intensity
|
|
3964
|
+
|
|
3965
|
+
def shade(self, data, cmap, norm=None, blend_mode='overlay', vmin=None,
|
|
3966
|
+
vmax=None, vert_exag=1, dx=1, dy=1, fraction=1, **kwargs):
|
|
3967
|
+
"""
|
|
3968
|
+
Combine colormapped data values with an illumination intensity map
|
|
3969
|
+
(a.k.a. "hillshade") of the values.
|
|
3970
|
+
|
|
3971
|
+
Parameters
|
|
3972
|
+
----------
|
|
3973
|
+
data : 2D array-like
|
|
3974
|
+
The height values used to generate a shaded map.
|
|
3975
|
+
cmap : `~matplotlib.colors.Colormap`
|
|
3976
|
+
The colormap used to color the *data* array. Note that this must be
|
|
3977
|
+
a `~matplotlib.colors.Colormap` instance. For example, rather than
|
|
3978
|
+
passing in ``cmap='gist_earth'``, use
|
|
3979
|
+
``cmap=plt.get_cmap('gist_earth')`` instead.
|
|
3980
|
+
norm : `~matplotlib.colors.Normalize` instance, optional
|
|
3981
|
+
The normalization used to scale values before colormapping. If
|
|
3982
|
+
None, the input will be linearly scaled between its min and max.
|
|
3983
|
+
blend_mode : {'hsv', 'overlay', 'soft'} or callable, optional
|
|
3984
|
+
The type of blending used to combine the colormapped data
|
|
3985
|
+
values with the illumination intensity. Default is
|
|
3986
|
+
"overlay". Note that for most topographic surfaces,
|
|
3987
|
+
"overlay" or "soft" appear more visually realistic. If a
|
|
3988
|
+
user-defined function is supplied, it is expected to
|
|
3989
|
+
combine an (M, N, 3) RGB array of floats (ranging 0 to 1) with
|
|
3990
|
+
an (M, N, 1) hillshade array (also 0 to 1). (Call signature
|
|
3991
|
+
``func(rgb, illum, **kwargs)``) Additional kwargs supplied
|
|
3992
|
+
to this function will be passed on to the *blend_mode*
|
|
3993
|
+
function.
|
|
3994
|
+
vmin : float or None, optional
|
|
3995
|
+
The minimum value used in colormapping *data*. If *None* the
|
|
3996
|
+
minimum value in *data* is used. If *norm* is specified, then this
|
|
3997
|
+
argument will be ignored.
|
|
3998
|
+
vmax : float or None, optional
|
|
3999
|
+
The maximum value used in colormapping *data*. If *None* the
|
|
4000
|
+
maximum value in *data* is used. If *norm* is specified, then this
|
|
4001
|
+
argument will be ignored.
|
|
4002
|
+
vert_exag : number, optional
|
|
4003
|
+
The amount to exaggerate the elevation values by when calculating
|
|
4004
|
+
illumination. This can be used either to correct for differences in
|
|
4005
|
+
units between the x-y coordinate system and the elevation
|
|
4006
|
+
coordinate system (e.g. decimal degrees vs. meters) or to
|
|
4007
|
+
exaggerate or de-emphasize topography.
|
|
4008
|
+
dx : number, optional
|
|
4009
|
+
The x-spacing (columns) of the input *elevation* grid.
|
|
4010
|
+
dy : number, optional
|
|
4011
|
+
The y-spacing (rows) of the input *elevation* grid.
|
|
4012
|
+
fraction : number, optional
|
|
4013
|
+
Increases or decreases the contrast of the hillshade. Values
|
|
4014
|
+
greater than one will cause intermediate values to move closer to
|
|
4015
|
+
full illumination or shadow (and clipping any values that move
|
|
4016
|
+
beyond 0 or 1). Note that this is not visually or mathematically
|
|
4017
|
+
the same as vertical exaggeration.
|
|
4018
|
+
**kwargs
|
|
4019
|
+
Additional kwargs are passed on to the *blend_mode* function.
|
|
4020
|
+
|
|
4021
|
+
Returns
|
|
4022
|
+
-------
|
|
4023
|
+
`~numpy.ndarray`
|
|
4024
|
+
An (M, N, 4) array of floats ranging between 0-1.
|
|
4025
|
+
"""
|
|
4026
|
+
if vmin is None:
|
|
4027
|
+
vmin = data.min()
|
|
4028
|
+
if vmax is None:
|
|
4029
|
+
vmax = data.max()
|
|
4030
|
+
if norm is None:
|
|
4031
|
+
norm = Normalize(vmin=vmin, vmax=vmax)
|
|
4032
|
+
|
|
4033
|
+
rgb0 = cmap(norm(data))
|
|
4034
|
+
rgb1 = self.shade_rgb(rgb0, elevation=data, blend_mode=blend_mode,
|
|
4035
|
+
vert_exag=vert_exag, dx=dx, dy=dy,
|
|
4036
|
+
fraction=fraction, **kwargs)
|
|
4037
|
+
# Don't overwrite the alpha channel, if present.
|
|
4038
|
+
rgb0[..., :3] = rgb1[..., :3]
|
|
4039
|
+
return rgb0
|
|
4040
|
+
|
|
4041
|
+
def shade_rgb(self, rgb, elevation, fraction=1., blend_mode='hsv',
|
|
4042
|
+
vert_exag=1, dx=1, dy=1, **kwargs):
|
|
4043
|
+
"""
|
|
4044
|
+
Use this light source to adjust the colors of the *rgb* input array to
|
|
4045
|
+
give the impression of a shaded relief map with the given *elevation*.
|
|
4046
|
+
|
|
4047
|
+
Parameters
|
|
4048
|
+
----------
|
|
4049
|
+
rgb : array-like
|
|
4050
|
+
An (M, N, 3) RGB array, assumed to be in the range of 0 to 1.
|
|
4051
|
+
elevation : array-like
|
|
4052
|
+
An (M, N) array of the height values used to generate a shaded map.
|
|
4053
|
+
fraction : number
|
|
4054
|
+
Increases or decreases the contrast of the hillshade. Values
|
|
4055
|
+
greater than one will cause intermediate values to move closer to
|
|
4056
|
+
full illumination or shadow (and clipping any values that move
|
|
4057
|
+
beyond 0 or 1). Note that this is not visually or mathematically
|
|
4058
|
+
the same as vertical exaggeration.
|
|
4059
|
+
blend_mode : {'hsv', 'overlay', 'soft'} or callable, optional
|
|
4060
|
+
The type of blending used to combine the colormapped data values
|
|
4061
|
+
with the illumination intensity. For backwards compatibility, this
|
|
4062
|
+
defaults to "hsv". Note that for most topographic surfaces,
|
|
4063
|
+
"overlay" or "soft" appear more visually realistic. If a
|
|
4064
|
+
user-defined function is supplied, it is expected to combine an
|
|
4065
|
+
(M, N, 3) RGB array of floats (ranging 0 to 1) with an (M, N, 1)
|
|
4066
|
+
hillshade array (also 0 to 1). (Call signature
|
|
4067
|
+
``func(rgb, illum, **kwargs)``)
|
|
4068
|
+
Additional kwargs supplied to this function will be passed on to
|
|
4069
|
+
the *blend_mode* function.
|
|
4070
|
+
vert_exag : number, optional
|
|
4071
|
+
The amount to exaggerate the elevation values by when calculating
|
|
4072
|
+
illumination. This can be used either to correct for differences in
|
|
4073
|
+
units between the x-y coordinate system and the elevation
|
|
4074
|
+
coordinate system (e.g. decimal degrees vs. meters) or to
|
|
4075
|
+
exaggerate or de-emphasize topography.
|
|
4076
|
+
dx : number, optional
|
|
4077
|
+
The x-spacing (columns) of the input *elevation* grid.
|
|
4078
|
+
dy : number, optional
|
|
4079
|
+
The y-spacing (rows) of the input *elevation* grid.
|
|
4080
|
+
**kwargs
|
|
4081
|
+
Additional kwargs are passed on to the *blend_mode* function.
|
|
4082
|
+
|
|
4083
|
+
Returns
|
|
4084
|
+
-------
|
|
4085
|
+
`~numpy.ndarray`
|
|
4086
|
+
An (m, n, 3) array of floats ranging between 0-1.
|
|
4087
|
+
"""
|
|
4088
|
+
# Calculate the "hillshade" intensity.
|
|
4089
|
+
intensity = self.hillshade(elevation, vert_exag, dx, dy, fraction)
|
|
4090
|
+
intensity = intensity[..., np.newaxis]
|
|
4091
|
+
|
|
4092
|
+
# Blend the hillshade and rgb data using the specified mode
|
|
4093
|
+
lookup = {
|
|
4094
|
+
'hsv': self.blend_hsv,
|
|
4095
|
+
'soft': self.blend_soft_light,
|
|
4096
|
+
'overlay': self.blend_overlay,
|
|
4097
|
+
}
|
|
4098
|
+
if blend_mode in lookup:
|
|
4099
|
+
blend = lookup[blend_mode](rgb, intensity, **kwargs)
|
|
4100
|
+
else:
|
|
4101
|
+
try:
|
|
4102
|
+
blend = blend_mode(rgb, intensity, **kwargs)
|
|
4103
|
+
except TypeError as err:
|
|
4104
|
+
raise ValueError('"blend_mode" must be callable or one of '
|
|
4105
|
+
f'{lookup.keys}') from err
|
|
4106
|
+
|
|
4107
|
+
# Only apply result where hillshade intensity isn't masked
|
|
4108
|
+
if np.ma.is_masked(intensity):
|
|
4109
|
+
mask = intensity.mask[..., 0]
|
|
4110
|
+
for i in range(3):
|
|
4111
|
+
blend[..., i][mask] = rgb[..., i][mask]
|
|
4112
|
+
|
|
4113
|
+
return blend
|
|
4114
|
+
|
|
4115
|
+
def blend_hsv(self, rgb, intensity, hsv_max_sat=None, hsv_max_val=None,
|
|
4116
|
+
hsv_min_val=None, hsv_min_sat=None):
|
|
4117
|
+
"""
|
|
4118
|
+
Take the input data array, convert to HSV values in the given colormap,
|
|
4119
|
+
then adjust those color values to give the impression of a shaded
|
|
4120
|
+
relief map with a specified light source. RGBA values are returned,
|
|
4121
|
+
which can then be used to plot the shaded image with imshow.
|
|
4122
|
+
|
|
4123
|
+
The color of the resulting image will be darkened by moving the (s, v)
|
|
4124
|
+
values (in HSV colorspace) toward (hsv_min_sat, hsv_min_val) in the
|
|
4125
|
+
shaded regions, or lightened by sliding (s, v) toward (hsv_max_sat,
|
|
4126
|
+
hsv_max_val) in regions that are illuminated. The default extremes are
|
|
4127
|
+
chose so that completely shaded points are nearly black (s = 1, v = 0)
|
|
4128
|
+
and completely illuminated points are nearly white (s = 0, v = 1).
|
|
4129
|
+
|
|
4130
|
+
Parameters
|
|
4131
|
+
----------
|
|
4132
|
+
rgb : `~numpy.ndarray`
|
|
4133
|
+
An (M, N, 3) RGB array of floats ranging from 0 to 1 (color image).
|
|
4134
|
+
intensity : `~numpy.ndarray`
|
|
4135
|
+
An (M, N, 1) array of floats ranging from 0 to 1 (grayscale image).
|
|
4136
|
+
hsv_max_sat : number, optional
|
|
4137
|
+
The maximum saturation value that the *intensity* map can shift the output
|
|
4138
|
+
image to. If not provided, use the value provided upon initialization.
|
|
4139
|
+
hsv_min_sat : number, optional
|
|
4140
|
+
The minimum saturation value that the *intensity* map can shift the output
|
|
4141
|
+
image to. If not provided, use the value provided upon initialization.
|
|
4142
|
+
hsv_max_val : number, optional
|
|
4143
|
+
The maximum value ("v" in "hsv") that the *intensity* map can shift the
|
|
4144
|
+
output image to. If not provided, use the value provided upon
|
|
4145
|
+
initialization.
|
|
4146
|
+
hsv_min_val : number, optional
|
|
4147
|
+
The minimum value ("v" in "hsv") that the *intensity* map can shift the
|
|
4148
|
+
output image to. If not provided, use the value provided upon
|
|
4149
|
+
initialization.
|
|
4150
|
+
|
|
4151
|
+
Returns
|
|
4152
|
+
-------
|
|
4153
|
+
`~numpy.ndarray`
|
|
4154
|
+
An (M, N, 3) RGB array representing the combined images.
|
|
4155
|
+
"""
|
|
4156
|
+
# Backward compatibility...
|
|
4157
|
+
if hsv_max_sat is None:
|
|
4158
|
+
hsv_max_sat = self.hsv_max_sat
|
|
4159
|
+
if hsv_max_val is None:
|
|
4160
|
+
hsv_max_val = self.hsv_max_val
|
|
4161
|
+
if hsv_min_sat is None:
|
|
4162
|
+
hsv_min_sat = self.hsv_min_sat
|
|
4163
|
+
if hsv_min_val is None:
|
|
4164
|
+
hsv_min_val = self.hsv_min_val
|
|
4165
|
+
|
|
4166
|
+
# Expects a 2D intensity array scaled between -1 to 1...
|
|
4167
|
+
intensity = intensity[..., 0]
|
|
4168
|
+
intensity = 2 * intensity - 1
|
|
4169
|
+
|
|
4170
|
+
# Convert to rgb, then rgb to hsv
|
|
4171
|
+
hsv = rgb_to_hsv(rgb[:, :, 0:3])
|
|
4172
|
+
hue, sat, val = np.moveaxis(hsv, -1, 0)
|
|
4173
|
+
|
|
4174
|
+
# Modify hsv values (in place) to simulate illumination.
|
|
4175
|
+
# putmask(A, mask, B) <=> A[mask] = B[mask]
|
|
4176
|
+
np.putmask(sat, (np.abs(sat) > 1.e-10) & (intensity > 0),
|
|
4177
|
+
(1 - intensity) * sat + intensity * hsv_max_sat)
|
|
4178
|
+
np.putmask(sat, (np.abs(sat) > 1.e-10) & (intensity < 0),
|
|
4179
|
+
(1 + intensity) * sat - intensity * hsv_min_sat)
|
|
4180
|
+
np.putmask(val, intensity > 0,
|
|
4181
|
+
(1 - intensity) * val + intensity * hsv_max_val)
|
|
4182
|
+
np.putmask(val, intensity < 0,
|
|
4183
|
+
(1 + intensity) * val - intensity * hsv_min_val)
|
|
4184
|
+
np.clip(hsv[:, :, 1:], 0, 1, out=hsv[:, :, 1:])
|
|
4185
|
+
|
|
4186
|
+
# Convert modified hsv back to rgb.
|
|
4187
|
+
return hsv_to_rgb(hsv)
|
|
4188
|
+
|
|
4189
|
+
def blend_soft_light(self, rgb, intensity):
|
|
4190
|
+
"""
|
|
4191
|
+
Combine an RGB image with an intensity map using "soft light" blending,
|
|
4192
|
+
using the "pegtop" formula.
|
|
4193
|
+
|
|
4194
|
+
Parameters
|
|
4195
|
+
----------
|
|
4196
|
+
rgb : `~numpy.ndarray`
|
|
4197
|
+
An (M, N, 3) RGB array of floats ranging from 0 to 1 (color image).
|
|
4198
|
+
intensity : `~numpy.ndarray`
|
|
4199
|
+
An (M, N, 1) array of floats ranging from 0 to 1 (grayscale image).
|
|
4200
|
+
|
|
4201
|
+
Returns
|
|
4202
|
+
-------
|
|
4203
|
+
`~numpy.ndarray`
|
|
4204
|
+
An (M, N, 3) RGB array representing the combined images.
|
|
4205
|
+
"""
|
|
4206
|
+
return 2 * intensity * rgb + (1 - 2 * intensity) * rgb**2
|
|
4207
|
+
|
|
4208
|
+
def blend_overlay(self, rgb, intensity):
|
|
4209
|
+
"""
|
|
4210
|
+
Combine an RGB image with an intensity map using "overlay" blending.
|
|
4211
|
+
|
|
4212
|
+
Parameters
|
|
4213
|
+
----------
|
|
4214
|
+
rgb : `~numpy.ndarray`
|
|
4215
|
+
An (M, N, 3) RGB array of floats ranging from 0 to 1 (color image).
|
|
4216
|
+
intensity : `~numpy.ndarray`
|
|
4217
|
+
An (M, N, 1) array of floats ranging from 0 to 1 (grayscale image).
|
|
4218
|
+
|
|
4219
|
+
Returns
|
|
4220
|
+
-------
|
|
4221
|
+
ndarray
|
|
4222
|
+
An (M, N, 3) RGB array representing the combined images.
|
|
4223
|
+
"""
|
|
4224
|
+
low = 2 * intensity * rgb
|
|
4225
|
+
high = 1 - 2 * (1 - intensity) * (1 - rgb)
|
|
4226
|
+
return np.where(rgb <= 0.5, low, high)
|
|
4227
|
+
|
|
4228
|
+
|
|
4229
|
+
def from_levels_and_colors(levels, colors, extend='neither'):
|
|
4230
|
+
"""
|
|
4231
|
+
A helper routine to generate a cmap and a norm instance which
|
|
4232
|
+
behave similar to contourf's levels and colors arguments.
|
|
4233
|
+
|
|
4234
|
+
Parameters
|
|
4235
|
+
----------
|
|
4236
|
+
levels : sequence of numbers
|
|
4237
|
+
The quantization levels used to construct the `BoundaryNorm`.
|
|
4238
|
+
Value ``v`` is quantized to level ``i`` if ``lev[i] <= v < lev[i+1]``.
|
|
4239
|
+
colors : sequence of colors
|
|
4240
|
+
The fill color to use for each level. If *extend* is "neither" there
|
|
4241
|
+
must be ``n_level - 1`` colors. For an *extend* of "min" or "max" add
|
|
4242
|
+
one extra color, and for an *extend* of "both" add two colors.
|
|
4243
|
+
extend : {'neither', 'min', 'max', 'both'}, optional
|
|
4244
|
+
The behaviour when a value falls out of range of the given levels.
|
|
4245
|
+
See `~.Axes.contourf` for details.
|
|
4246
|
+
|
|
4247
|
+
Returns
|
|
4248
|
+
-------
|
|
4249
|
+
cmap : `~matplotlib.colors.Colormap`
|
|
4250
|
+
norm : `~matplotlib.colors.Normalize`
|
|
4251
|
+
"""
|
|
4252
|
+
slice_map = {
|
|
4253
|
+
'both': slice(1, -1),
|
|
4254
|
+
'min': slice(1, None),
|
|
4255
|
+
'max': slice(0, -1),
|
|
4256
|
+
'neither': slice(0, None),
|
|
4257
|
+
}
|
|
4258
|
+
_api.check_in_list(slice_map, extend=extend)
|
|
4259
|
+
color_slice = slice_map[extend]
|
|
4260
|
+
|
|
4261
|
+
n_data_colors = len(levels) - 1
|
|
4262
|
+
n_extend_colors = color_slice.start - (color_slice.stop or 0) # 0, 1 or 2
|
|
4263
|
+
n_expected = n_data_colors + n_extend_colors
|
|
4264
|
+
if len(colors) != n_expected:
|
|
4265
|
+
raise ValueError(
|
|
4266
|
+
f'Expected {n_expected} colors ({n_data_colors} colors for {len(levels)} '
|
|
4267
|
+
f'levels, and {n_extend_colors} colors for extend == {extend!r}), '
|
|
4268
|
+
f'but got {len(colors)}')
|
|
4269
|
+
|
|
4270
|
+
data_colors = colors[color_slice]
|
|
4271
|
+
under_color = colors[0] if extend in ['min', 'both'] else 'none'
|
|
4272
|
+
over_color = colors[-1] if extend in ['max', 'both'] else 'none'
|
|
4273
|
+
cmap = ListedColormap(data_colors, under=under_color, over=over_color)
|
|
4274
|
+
|
|
4275
|
+
cmap.colorbar_extend = extend
|
|
4276
|
+
|
|
4277
|
+
norm = BoundaryNorm(levels, ncolors=n_data_colors)
|
|
4278
|
+
return cmap, norm
|