diff --git a/doc/api/pyplot_summary.rst b/doc/api/pyplot_summary.rst index f3f4c88b78e8..8d18c8b67e3e 100644 --- a/doc/api/pyplot_summary.rst +++ b/doc/api/pyplot_summary.rst @@ -29,4 +29,5 @@ For a more in-depth look at colormaps, see the .. currentmodule:: matplotlib.pyplot -.. autofunction:: colormaps +.. autodata:: colormaps + :no-value: diff --git a/doc/users/next_whats_new/colormaps.rst b/doc/users/next_whats_new/colormaps.rst index 5262fab305da..b4e92877b1f0 100644 --- a/doc/users/next_whats_new/colormaps.rst +++ b/doc/users/next_whats_new/colormaps.rst @@ -1,18 +1,22 @@ -Colormap registry ------------------- +Colormap registry (experimental) +-------------------------------- -Colormaps are now managed via `matplotlib.colormaps`, which is a -`.ColormapRegistry`. +Colormaps are now managed via `matplotlib.colormaps` (or `.pyplot.colormaps`), +which is a `.ColormapRegistry`. While we are confident that the API is final, +we formally mark it as experimental for 3.5 because we want to keep the option +to still adapt the API for 3.6 should the need arise. Colormaps can be obtained using item access:: - import matplotlib as mpl - cmap = mpl.colormaps['viridis'] + import matplotlib.pyplot as plt + cmap = plt.colormaps['viridis'] To register new colormaps use:: - mpl.colormaps.register(my_colormap) + plt.colormaps.register(my_colormap) -The use of `matplotlib.cm.get_cmap` and `matplotlib.cm.register_cmap` is -discouraged in favor of the above. Within `.pyplot` the use of -``plt.get_cmap()`` and ``plt.register_cmap()`` will continue to be supported. \ No newline at end of file +We recommend to use the new API instead of the `~.cm.get_cmap` and +`~.cm.register_cmap` functions for new code. `matplotlib.cm.get_cmap` and +`matplotlib.cm.register_cmap` will eventually be deprecated and removed. +Within `.pyplot` ``plt.get_cmap()`` and ``plt.register_cmap()`` will continue +to be supported for backward compatibility. \ No newline at end of file diff --git a/examples/images_contours_and_fields/contourf_demo.py b/examples/images_contours_and_fields/contourf_demo.py index acab13d1c578..2309c171a5f8 100644 --- a/examples/images_contours_and_fields/contourf_demo.py +++ b/examples/images_contours_and_fields/contourf_demo.py @@ -6,7 +6,6 @@ How to use the `.axes.Axes.contourf` method to create filled contour plots. """ import numpy as np -import matplotlib as mpl import matplotlib.pyplot as plt origin = 'lower' @@ -87,7 +86,7 @@ # Illustrate all 4 possible "extend" settings: extends = ["neither", "both", "min", "max"] -cmap = mpl.colormaps["winter"].with_extremes(under="magenta", over="yellow") +cmap = plt.colormaps["winter"].with_extremes(under="magenta", over="yellow") # Note: contouring simply excludes masked or nan regions, so # instead of using the "bad" colormap value for them, it draws # nothing at all in them. Therefore the following would have diff --git a/examples/images_contours_and_fields/demo_bboximage.py b/examples/images_contours_and_fields/demo_bboximage.py index cbc57a04c39d..0d43e328cb38 100644 --- a/examples/images_contours_and_fields/demo_bboximage.py +++ b/examples/images_contours_and_fields/demo_bboximage.py @@ -7,7 +7,6 @@ a bounding box. This demo shows how to show an image inside a `.text.Text`'s bounding box as well as how to manually create a bounding box for the image. """ -import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np from matplotlib.image import BboxImage @@ -39,7 +38,7 @@ a = np.vstack((a, a)) # List of all colormaps; skip reversed colormaps. -cmap_names = sorted(m for m in mpl.colormaps if not m.endswith("_r")) +cmap_names = sorted(m for m in plt.colormaps if not m.endswith("_r")) ncol = 2 nrow = len(cmap_names) // ncol + 1 diff --git a/examples/images_contours_and_fields/pcolormesh_levels.py b/examples/images_contours_and_fields/pcolormesh_levels.py index 143a83cf2683..d42643f15574 100644 --- a/examples/images_contours_and_fields/pcolormesh_levels.py +++ b/examples/images_contours_and_fields/pcolormesh_levels.py @@ -94,7 +94,7 @@ # pick the desired colormap, sensible levels, and define a normalization # instance which takes data values and translates those into levels. -cmap = plt.get_cmap('PiYG') +cmap = plt.colormaps['PiYG'] norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True) fig, (ax0, ax1) = plt.subplots(nrows=2) diff --git a/examples/images_contours_and_fields/quadmesh_demo.py b/examples/images_contours_and_fields/quadmesh_demo.py index 9bddaf1e1595..430c428f5170 100644 --- a/examples/images_contours_and_fields/quadmesh_demo.py +++ b/examples/images_contours_and_fields/quadmesh_demo.py @@ -9,7 +9,6 @@ This demo illustrates a bug in quadmesh with masked data. """ -import matplotlib as mpl from matplotlib import pyplot as plt import numpy as np @@ -30,7 +29,7 @@ axs[0].set_title('Without masked values') # You can control the color of the masked region. -cmap = mpl.colormaps[mpl.rcParams['image.cmap']].with_extremes(bad='y') +cmap = plt.colormaps[plt.rcParams['image.cmap']].with_extremes(bad='y') axs[1].pcolormesh(Qx, Qz, Zm, shading='gouraud', cmap=cmap) axs[1].set_title('With masked values') diff --git a/examples/lines_bars_and_markers/horizontal_barchart_distribution.py b/examples/lines_bars_and_markers/horizontal_barchart_distribution.py index 8bb4ed7d4f0d..3a22ce3ed4ae 100644 --- a/examples/lines_bars_and_markers/horizontal_barchart_distribution.py +++ b/examples/lines_bars_and_markers/horizontal_barchart_distribution.py @@ -43,7 +43,7 @@ def survey(results, category_names): labels = list(results.keys()) data = np.array(list(results.values())) data_cum = data.cumsum(axis=1) - category_colors = plt.get_cmap('RdYlGn')( + category_colors = plt.colormaps['RdYlGn']( np.linspace(0.15, 0.85, data.shape[1])) fig, ax = plt.subplots(figsize=(9.2, 5)) diff --git a/examples/mplot3d/polys3d.py b/examples/mplot3d/polys3d.py index fd56d13fbe9a..ce9905958bd6 100644 --- a/examples/mplot3d/polys3d.py +++ b/examples/mplot3d/polys3d.py @@ -32,7 +32,7 @@ def polygon_under_graph(x, y): # verts[i] is a list of (x, y) pairs defining polygon i. verts = [polygon_under_graph(x, poisson.pmf(l, x)) for l in lambdas] -facecolors = plt.get_cmap('viridis_r')(np.linspace(0, 1, len(verts))) +facecolors = plt.colormaps['viridis_r'](np.linspace(0, 1, len(verts))) poly = PolyCollection(verts, facecolors=facecolors, alpha=.7) ax.add_collection3d(poly, zs=lambdas, zdir='y') diff --git a/examples/pie_and_polar_charts/nested_pie.py b/examples/pie_and_polar_charts/nested_pie.py index 92b66124ab8f..5a31ab1ffdc8 100644 --- a/examples/pie_and_polar_charts/nested_pie.py +++ b/examples/pie_and_polar_charts/nested_pie.py @@ -8,7 +8,6 @@ """ -import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np @@ -31,7 +30,7 @@ size = 0.3 vals = np.array([[60., 32.], [37., 40.], [29., 10.]]) -cmap = mpl.colormaps["tab20c"] +cmap = plt.colormaps["tab20c"] outer_colors = cmap(np.arange(3)*4) inner_colors = cmap([1, 2, 5, 6, 9, 10]) @@ -62,7 +61,7 @@ # Obtain the ordinates of the bar edges valsleft = np.cumsum(np.append(0, valsnorm.flatten()[:-1])).reshape(vals.shape) -cmap = mpl.colormaps["tab20c"] +cmap = plt.colormaps["tab20c"] outer_colors = cmap(np.arange(3)*4) inner_colors = cmap([1, 2, 5, 6, 9, 10]) diff --git a/examples/userdemo/colormap_interactive_adjustment.py b/examples/userdemo/colormap_interactive_adjustment.py index bb392daf8464..47563b79328a 100644 --- a/examples/userdemo/colormap_interactive_adjustment.py +++ b/examples/userdemo/colormap_interactive_adjustment.py @@ -54,7 +54,7 @@ def adjust_colorbar(mouseevent): Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2) Z = (0.9*Z1 - 0.5*Z2) * 2 -cmap = plt.get_cmap('viridis').with_extremes( +cmap = plt.colormaps['viridis'].with_extremes( over='xkcd:orange', under='xkcd:dark red') axesimage = plt.imshow(Z, cmap=cmap) colorbar = plt.colorbar(axesimage, ax=ax, use_gridspec=True) diff --git a/lib/matplotlib/cm.py b/lib/matplotlib/cm.py index 76c1c5d4f7f2..1d1de723ebe0 100644 --- a/lib/matplotlib/cm.py +++ b/lib/matplotlib/cm.py @@ -102,6 +102,12 @@ class ColormapRegistry(Mapping): r""" Container for colormaps that are known to Matplotlib by name. + .. admonition:: Experimental + + While we expect the API to be final, we formally mark it as + experimental for 3.5 because we want to keep the option to still adapt + the API for 3.6 should the need arise. + The universal registry instance is `matplotlib.colormaps`. There should be no need for users to instantiate `.ColormapRegistry` themselves. @@ -136,6 +142,16 @@ def __str__(self): return ('ColormapRegistry; available colormaps:\n' + ', '.join(f"'{name}'" for name in self)) + def __call__(self): + """ + Return a list of the registered colormap names. + + This exists only for backward-compatibilty in `.pyplot` which had a + ``plt.colormaps()`` method. The recommended way to get this list is + now ``list(colormaps)``. + """ + return list(self) + def register(self, cmap, *, name=None, force=False): """ Register a new colormap. diff --git a/lib/matplotlib/pyplot.py b/lib/matplotlib/pyplot.py index b222466dda45..fc339eae3690 100644 --- a/lib/matplotlib/pyplot.py +++ b/lib/matplotlib/pyplot.py @@ -52,7 +52,7 @@ from matplotlib.scale import get_scale_names from matplotlib import cm -from matplotlib.cm import get_cmap, register_cmap +from matplotlib.cm import _colormaps as colormaps, get_cmap, register_cmap import numpy as np @@ -1996,7 +1996,7 @@ def get_plot_commands(): exclude = {'colormaps', 'colors', 'connect', 'disconnect', 'get_plot_commands', 'get_current_fig_manager', 'ginput', 'plotting', 'waitforbuttonpress'} - exclude |= set(colormaps()) + exclude |= set(colormaps) this_module = inspect.getmodule(get_plot_commands) return sorted( name for name, obj in globals().items() @@ -2005,253 +2005,6 @@ def get_plot_commands(): and inspect.getmodule(obj) is this_module) -def colormaps(): - """ - Matplotlib provides a number of colormaps, and others can be added using - :func:`~matplotlib.cm.register_cmap`. This function documents the built-in - colormaps, and will also return a list of all registered colormaps if - called. - - You can set the colormap for an image, pcolor, scatter, etc, - using a keyword argument:: - - imshow(X, cmap=cm.hot) - - or using the :func:`set_cmap` function:: - - imshow(X) - pyplot.set_cmap('hot') - pyplot.set_cmap('jet') - - In interactive mode, :func:`set_cmap` will update the colormap post-hoc, - allowing you to see which one works best for your data. - - All built-in colormaps can be reversed by appending ``_r``: For instance, - ``gray_r`` is the reverse of ``gray``. - - There are several common color schemes used in visualization: - - Sequential schemes - for unipolar data that progresses from low to high - Diverging schemes - for bipolar data that emphasizes positive or negative deviations from a - central value - Cyclic schemes - for plotting values that wrap around at the endpoints, such as phase - angle, wind direction, or time of day - Qualitative schemes - for nominal data that has no inherent ordering, where color is used - only to distinguish categories - - Matplotlib ships with 4 perceptually uniform colormaps which are - the recommended colormaps for sequential data: - - ========= =================================================== - Colormap Description - ========= =================================================== - inferno perceptually uniform shades of black-red-yellow - magma perceptually uniform shades of black-red-white - plasma perceptually uniform shades of blue-red-yellow - viridis perceptually uniform shades of blue-green-yellow - ========= =================================================== - - The following colormaps are based on the `ColorBrewer - `_ color specifications and designs developed by - Cynthia Brewer: - - ColorBrewer Diverging (luminance is highest at the midpoint, and - decreases towards differently-colored endpoints): - - ======== =================================== - Colormap Description - ======== =================================== - BrBG brown, white, blue-green - PiYG pink, white, yellow-green - PRGn purple, white, green - PuOr orange, white, purple - RdBu red, white, blue - RdGy red, white, gray - RdYlBu red, yellow, blue - RdYlGn red, yellow, green - Spectral red, orange, yellow, green, blue - ======== =================================== - - ColorBrewer Sequential (luminance decreases monotonically): - - ======== ==================================== - Colormap Description - ======== ==================================== - Blues white to dark blue - BuGn white, light blue, dark green - BuPu white, light blue, dark purple - GnBu white, light green, dark blue - Greens white to dark green - Greys white to black (not linear) - Oranges white, orange, dark brown - OrRd white, orange, dark red - PuBu white, light purple, dark blue - PuBuGn white, light purple, dark green - PuRd white, light purple, dark red - Purples white to dark purple - RdPu white, pink, dark purple - Reds white to dark red - YlGn light yellow, dark green - YlGnBu light yellow, light green, dark blue - YlOrBr light yellow, orange, dark brown - YlOrRd light yellow, orange, dark red - ======== ==================================== - - ColorBrewer Qualitative: - - (For plotting nominal data, `.ListedColormap` is used, - not `.LinearSegmentedColormap`. Different sets of colors are - recommended for different numbers of categories.) - - * Accent - * Dark2 - * Paired - * Pastel1 - * Pastel2 - * Set1 - * Set2 - * Set3 - - A set of colormaps derived from those of the same name provided - with Matlab are also included: - - ========= ======================================================= - Colormap Description - ========= ======================================================= - autumn sequential linearly-increasing shades of red-orange-yellow - bone sequential increasing black-white colormap with - a tinge of blue, to emulate X-ray film - cool linearly-decreasing shades of cyan-magenta - copper sequential increasing shades of black-copper - flag repetitive red-white-blue-black pattern (not cyclic at - endpoints) - gray sequential linearly-increasing black-to-white - grayscale - hot sequential black-red-yellow-white, to emulate blackbody - radiation from an object at increasing temperatures - jet a spectral map with dark endpoints, blue-cyan-yellow-red; - based on a fluid-jet simulation by NCSA [#]_ - pink sequential increasing pastel black-pink-white, meant - for sepia tone colorization of photographs - prism repetitive red-yellow-green-blue-purple-...-green pattern - (not cyclic at endpoints) - spring linearly-increasing shades of magenta-yellow - summer sequential linearly-increasing shades of green-yellow - winter linearly-increasing shades of blue-green - ========= ======================================================= - - A set of palettes from the `Yorick scientific visualisation - package `_, an evolution of - the GIST package, both by David H. Munro are included: - - ============ ======================================================= - Colormap Description - ============ ======================================================= - gist_earth mapmaker's colors from dark blue deep ocean to green - lowlands to brown highlands to white mountains - gist_heat sequential increasing black-red-orange-white, to emulate - blackbody radiation from an iron bar as it grows hotter - gist_ncar pseudo-spectral black-blue-green-yellow-red-purple-white - colormap from National Center for Atmospheric - Research [#]_ - gist_rainbow runs through the colors in spectral order from red to - violet at full saturation (like *hsv* but not cyclic) - gist_stern "Stern special" color table from Interactive Data - Language software - ============ ======================================================= - - A set of cyclic colormaps: - - ================ ================================================= - Colormap Description - ================ ================================================= - hsv red-yellow-green-cyan-blue-magenta-red, formed by - changing the hue component in the HSV color space - twilight perceptually uniform shades of - white-blue-black-red-white - twilight_shifted perceptually uniform shades of - black-blue-white-red-black - ================ ================================================= - - Other miscellaneous schemes: - - ============= ======================================================= - Colormap Description - ============= ======================================================= - afmhot sequential black-orange-yellow-white blackbody - spectrum, commonly used in atomic force microscopy - brg blue-red-green - bwr diverging blue-white-red - coolwarm diverging blue-gray-red, meant to avoid issues with 3D - shading, color blindness, and ordering of colors [#]_ - CMRmap "Default colormaps on color images often reproduce to - confusing grayscale images. The proposed colormap - maintains an aesthetically pleasing color image that - automatically reproduces to a monotonic grayscale with - discrete, quantifiable saturation levels." [#]_ - cubehelix Unlike most other color schemes cubehelix was designed - by D.A. Green to be monotonically increasing in terms - of perceived brightness. Also, when printed on a black - and white postscript printer, the scheme results in a - greyscale with monotonically increasing brightness. - This color scheme is named cubehelix because the (r, g, b) - values produced can be visualised as a squashed helix - around the diagonal in the (r, g, b) color cube. - gnuplot gnuplot's traditional pm3d scheme - (black-blue-red-yellow) - gnuplot2 sequential color printable as gray - (black-blue-violet-yellow-white) - ocean green-blue-white - rainbow spectral purple-blue-green-yellow-orange-red colormap - with diverging luminance - seismic diverging blue-white-red - nipy_spectral black-purple-blue-green-yellow-red-white spectrum, - originally from the Neuroimaging in Python project - terrain mapmaker's colors, blue-green-yellow-brown-white, - originally from IGOR Pro - turbo Spectral map (purple-blue-green-yellow-orange-red) with - a bright center and darker endpoints. A smoother - alternative to jet. - ============= ======================================================= - - The following colormaps are redundant and may be removed in future - versions. It's recommended to use the names in the descriptions - instead, which produce identical output: - - ========= ======================================================= - Colormap Description - ========= ======================================================= - gist_gray identical to *gray* - gist_yarg identical to *gray_r* - binary identical to *gray_r* - ========= ======================================================= - - .. rubric:: Footnotes - - .. [#] Rainbow colormaps, ``jet`` in particular, are considered a poor - choice for scientific visualization by many researchers: `Rainbow Color - Map (Still) Considered Harmful - `_ - - .. [#] Resembles "BkBlAqGrYeOrReViWh200" from NCAR Command - Language. See `Color Table Gallery - `_ - - .. [#] See `Diverging Color Maps for Scientific Visualization - `_ by Kenneth Moreland. - - .. [#] See `A Color Map for Effective Black-and-White Rendering of - Color-Scale Images - `_ - by Carey Rappaport - """ - return sorted(cm._cmap_registry) - - def _setup_pyplot_info_docstrings(): """ Setup the docstring of `plotting` and of the colormap-setting functions. @@ -2293,7 +2046,7 @@ def _setup_pyplot_info_docstrings(): ] plotting.__doc__ = '\n'.join(lines) - for cm_name in colormaps(): + for cm_name in colormaps: if cm_name in globals(): globals()[cm_name].__doc__ = f""" Set the colormap to {cm_name!r}.