Colormaps

ProPlot defines colormaps as color palettes that sample some continuous function between two end colors. Colormaps are generally used to encode data values on a pseudo-third dimension. They are are implemented with the LinearSegmentedColormap and PerceptuallyUniformColormap classes, which are subclassed from matplotlib.colors.LinearSegmentedColormap.

ProPlot adds several features to help you use colormaps effectively in your figures. This section documents the new registered colormaps, explains how to make and modify colormaps, and shows how to apply them to your plots.

Included colormaps

On import, ProPlot registers a few sample perceptually uniform colormaps, plus several colormaps from other online data viz projects. Use show_cmaps to generate a table of registered maps. The figure is broken down into the following sections:

  • “User” colormaps, i.e. colormaps saved to your ~/.proplot/cmaps folder. You can use ProPlot to make new colormaps and add them to this folder.

  • Matplotlib and seaborn original colormaps.

  • ProPlot original perceptually uniform colormaps.

  • cmOcean colormaps designed for oceanographic data but useful for everyone.

  • Fabio Crameri’s “scientific colour maps”.

  • Cynthia Brewer’s ColorBrewer colormaps, included with matplotlib by default.

  • Colormaps from the SciVisColor online interactive tool. There are so many of these colormaps because they are intended to be merged into more complex colormaps.

ProPlot removes some default matplotlib colormaps with erratic color transitions.

Note

Colormap and color cycle identification is more flexible in ProPlot. The names are are case-insensitive (e.g. 'Viridis', 'viridis', and 'ViRiDiS' are equivalent), diverging colormap names can be specified in their “reversed” form (e.g. 'BuRd' is equivalent to 'RdBu_r'), and appending '_r' or '_s' to any colormap name will return a reversed or shifted version of the colormap or color cycle. See ColormapDatabase for more info.

  1. [1]:
  1. import proplot as plot
  2. fig, axs = plot.show_cmaps()

_images/colormaps_2_0.svg

Perceptually uniform colormaps

ProPlot’s custom colormaps are instances of the PerceptuallyUniformColormap class. These colormaps generate colors by interpolating between coordinates in any of the following three colorspaces:

  • HCL (a.k.a. CIE LChuv): A purely perceptually uniform colorspace, where colors are broken down into “hue” (color, range 0-360), “chroma” (saturation, range 0-100), and “luminance” (brightness, range 0-100). This space is difficult to work with due to impossible colors – colors that, when translated back from HCL to RGB, result in RGB channels greater than 1.

  • HPL (a.k.a. HPLuv): Hue and luminance are identical to HCL, but 100 saturation is set to the minimum maximum saturation across all hues for a given luminance. HPL restricts you to soft pastel colors, but is closer to HCL in terms of uniformity.

  • HSL (a.k.a. HSLuv): Hue and luminance are identical to HCL, but 100 saturation is set to the maximum saturation for a given hue and luminance. HSL gives you access to the entire RGB colorspace, but often results in sharp jumps in chroma.

The colorspace used by each PerceptuallyUniformColormap is set with the space keyword arg. To plot arbitrary cross-sections of these colorspaces, use show_colorspaces (the black regions represent impossible colors). To see how colormaps vary with respect to each channel, use show_channels. Some examples are shown below.

In theory, “uniform” colormaps should have straight lines in hue, chroma, and luminance (second figure, top row). In practice, this is difficult to accomplish due to impossible colors. Matplotlib and seaborn’s 'magma' and 'Rocket' colormaps are fairly linear with respect to hue and luminance, but not chroma. ProPlot’s 'Fire' is linear in hue, luminance, and HSL saturation (bottom left), while 'Dusk' is linear in hue, luminance, and HPL saturation (bottom right).

  1. [2]:
  1. # Colorspace demo
  2. import proplot as plot
  3. fig, axs = plot.show_colorspaces(axwidth=1.6, luminance=50)
  4. fig, axs = plot.show_colorspaces(axwidth=1.6, saturation=60)
  5. fig, axs = plot.show_colorspaces(axwidth=1.6, hue=0)

_images/colormaps_4_0.svg

_images/colormaps_4_1.svg

_images/colormaps_4_2.svg

  1. [3]:
  1. # Compare colormaps
  2. import proplot as plot
  3. for cmaps in (('magma', 'rocket'), ('fire', 'dusk')):
  4. fig, axs = plot.show_channels(
  5. *cmaps, axwidth=1.5, minhue=-180, maxsat=400, rgb=False
  6. )

_images/colormaps_5_0.svg

_images/colormaps_5_1.svg

Making new colormaps

ProPlot doesn’t just include new colormaps – it provides tools for merging colormaps, modifying colormaps, making perceptually uniform colormaps from scratch, and saving the results for future use. For your convenience, most of these features can be accessed via the Colormap constructor function. Note that every plotting command that accepts a cmap keyword passes it through this function (see cmap_changer).

To make PerceptuallyUniformColormaps from scratch, you have the following three options:

  • Pass a color name, hex string, or RGB tuple to Colormap. This builds a monochromatic (single hue) colormap by calling the from_color static method. The colormap colors will vary from the specified color to pure white or some shade near white (see the fade keyword arg).

  • Pass a list of colors to Colormap. This calls the from_list static method, which linearly interpolates between each color in hue, saturation, and luminance.

  • Pass a dictionary to Colormap. This calls the from_hsl static method, which draws lines between channel values specified by the keyword arguments hue, saturation, and luminance. The values can be numbers, color strings, or lists thereof. Numbers indicate the channel value. For color strings, the channel value is inferred from the specified color. You can end any color string with '+N' or '-N' to offset the channel value by the number N.

In the below example, we use all of these methods to make brand new PerceptuallyUniformColormaps in the 'hsl' and 'hpl' colorspaces.

  1. [4]:
  1. import proplot as plot
  2. import numpy as np
  3. state = np.random.RandomState(51423)
  4. data = state.rand(30, 30).cumsum(axis=1)
  5. # Initialize figure
  6. fig, axs = plot.subplots([[1, 1, 2, 2], [0, 3, 3, 0]], axwidth=2, span=0)
  7. axs.format(
  8. xlabel='x axis', ylabel='y axis',
  9. suptitle='Building your own PerceptuallyUniformColormaps'
  10. )
  11. # Colormap from named color
  12. # The trailing '_r' makes the colormap go dark-to-light instead of light-to-dark
  13. cmap1 = plot.Colormap('prussian blue_r', name='pacific', fade=100, space='hpl')
  14. axs[0].format(title='From single named color')
  15. axs[0].pcolormesh(data, cmap=cmap1)
  16. # Colormap from lists
  17. cmap2 = plot.Colormap(('maroon', 'light tan'), name='heatwave')
  18. axs[1].format(title='From list of colors')
  19. axs[1].pcolormesh(data, cmap=cmap2)
  20. # Colormaps from channel value dictionaries
  21. cmap3 = plot.Colormap(
  22. {
  23. 'hue': ['red', 'red-720'],
  24. 'saturation': [80, 20],
  25. 'luminance': [20, 100]
  26. },
  27. name='cubehelix',
  28. space='hpl',
  29. )
  30. axs[2].format(title='From channel values')
  31. axs[2].pcolormesh(data, cmap=cmap3)
  32. # Display the channels
  33. fig, axs = plot.show_channels(cmap1, cmap2, cmap3, axwidth=1.5, rgb=False)

_images/colormaps_7_0.svg

_images/colormaps_7_1.svg

Merging colormaps

To merge colormaps, simply pass multiple positional arguments to the Colormap constructor. Each positional argument can be a colormap name, a colormap instance, or a special argument that generates a new colormap on-the-fly. This lets you create new diverging colormaps and segmented SciVisColor style colormaps right inside ProPlot. Segmented colormaps are often desirable for complex datasets with complex statistical distributions.

In the below example, we create a new divering colormap and reconstruct the colormap from this SciVisColor example. We also save the results for future use by passing save=True to Colormap.

  1. [5]:
  1. import proplot as plot
  2. import numpy as np
  3. state = np.random.RandomState(51423)
  4. data = state.rand(30, 30).cumsum(axis=1)
  5. # Generate figure
  6. fig, axs = plot.subplots([[0, 1, 1, 0], [2, 2, 3, 3]], axwidth=2.4, span=False)
  7. axs.format(
  8. xlabel='xlabel', ylabel='ylabel',
  9. suptitle='Merging existing colormaps'
  10. )
  11. # Diverging colormap example
  12. title1 = 'Custom diverging map'
  13. cmap1 = plot.Colormap('Blue4_r', 'RedPurple3', name='Diverging', save=True)
  14. # SciVisColor examples
  15. title2 = 'Custom complex map'
  16. cmap2 = plot.Colormap(
  17. 'Green1_r', 'Orange5', 'Blue1_r', 'Blue6',
  18. name='Complex', save=True
  19. )
  20. title3 = 'SciVisColor example reproduction'
  21. cmap3 = plot.Colormap(
  22. 'Green1_r', 'Orange5', 'Blue1_r', 'Blue6',
  23. ratios=(1, 3, 5, 10), name='SciVisColor', save=True
  24. )
  25. # Plot examples
  26. for ax, cmap, title in zip(axs, (cmap1, cmap2, cmap3), (title1, title2, title3)):
  27. m = ax.pcolormesh(data, cmap=cmap, levels=500)
  28. ax.colorbar(m, loc='b', locator='null', label=cmap.name)
  29. ax.format(title=title)
  1. Saved colormap to '/home/docs/.proplot/cmaps/Diverging.json'.
  2. Saved colormap to '/home/docs/.proplot/cmaps/Complex.json'.
  3. Saved colormap to '/home/docs/.proplot/cmaps/SciVisColor.json'.

_images/colormaps_9_1.svg

Modifying colormaps

ProPlot allows you to create modified versions of existing colormaps using the Colormap constructor and the new LinearSegmentedColormap and ListedColormap classes, which are used to replace the native matplotlib colormap classes. They can be modified in the following ways:

  • To remove colors from the left or right ends of a colormap, pass left or right to Colormap. This calls the truncate method, and can be useful when you want to use colormaps as color cycles and need to remove the “white” part so that your lines stand out against the background.

  • To modify the central colors of a diverging colormap, pass cut to Colormap. This calls the cut method, and can be used to create a sharper cutoff between negative and positive values or (when cut is negative) to expand the “neutral” region of the colormap. This should generally be used without a central level.

  • To rotate a cyclic colormap, pass shift to Colormap. This calls the shifted method. ProPlot ensures the colors at the ends of “shifted” colormaps are distinct so that levels never blur together.

  • To change the opacity of a colormap or add an opacity gradation, pass alpha to Colormap. This calls the set_alpha method, and can be useful when layering filled contour or mesh elements.

  • To change the “gamma” of a PerceptuallyUniformColormap, pass gamma to Colormap. This calls the set_gamma method, and controls how the luminance and saturation channels vary between colormap segments. gamma > 1 emphasizes high luminance, low saturation colors, while gamma < 1 emphasizes low luminance, high saturation colors. This is similar to the effect of the HCL wizard “power” sliders.

  1. [6]:
  1. import proplot as plot
  2. import numpy as np
  3. state = np.random.RandomState(51423)
  4. data = state.rand(40, 40).cumsum(axis=0)
  5. # Generate figure
  6. fig, axs = plot.subplots(ncols=3, axwidth=1.7, span=False)
  7. axs.format(
  8. xlabel='x axis', ylabel='y axis',
  9. suptitle='Truncating sequential colormaps',
  10. )
  11. # Cutting left and right
  12. for ax, coord in zip(axs, (None, 0.3, 0.7)):
  13. cmap = 'grays'
  14. if coord is None:
  15. title, cmap_kw = 'Original', {}
  16. elif coord < 0.5:
  17. title, cmap_kw = f'left={coord}', {'left': coord}
  18. else:
  19. title, cmap_kw = f'right={coord}', {'right': coord}
  20. ax.format(title=title)
  21. ax.pcolormesh(
  22. data, cmap=cmap, cmap_kw=cmap_kw,
  23. colorbar='b', colorbar_kw={'locator': 'null'}
  24. )

_images/colormaps_11_0.svg

  1. [7]:
  1. import proplot as plot
  2. import numpy as np
  3. state = np.random.RandomState(51423)
  4. data = (state.rand(40, 40) - 0.5).cumsum(axis=0).cumsum(axis=1)
  5. # Generate figure
  6. fig, axs = plot.subplots(ncols=2, nrows=2, axwidth=1.7, span=False)
  7. axs.format(
  8. xlabel='x axis', ylabel='y axis',
  9. suptitle='Modifying diverging colormaps',
  10. )
  11. # Cutting out central colors
  12. levels = plot.arange(-10, 10, 2)
  13. for i, (ax, cut) in enumerate(zip(axs, (None, None, 0.2, -0.1))):
  14. levels = plot.arange(-10, 10, 2)
  15. if i == 1 or i == 3:
  16. levels = plot.edges(levels)
  17. if i == 0:
  18. title = 'Even number of levels'
  19. elif i == 1:
  20. title = 'Odd number of levels'
  21. else:
  22. title = 'Sharper cutoff' if cut > 0 else 'Expanded center'
  23. title = f'{title}\ncut = ${cut}$'
  24. ax.format(title=title)
  25. m = ax.contourf(
  26. data, cmap='Div', cmap_kw={'cut': cut},
  27. extend='both', levels=levels,
  28. colorbar='b', colorbar_kw={'locator': 'null'},
  29. )

_images/colormaps_12_0.svg

  1. [8]:
  1. import proplot as plot
  2. import numpy as np
  3. state = np.random.RandomState(51423)
  4. data = (state.rand(50, 50) - 0.48).cumsum(axis=0).cumsum(axis=1) % 30
  5. # Rotating cyclic colormaps
  6. fig, axs = plot.subplots(ncols=3, axwidth=1.7)
  7. for ax, shift in zip(axs, (0, 90, 180)):
  8. m = ax.pcolormesh(data, cmap='romaO', cmap_kw={'shift': shift}, levels=12)
  9. ax.format(
  10. xlabel='x axis', ylabel='y axis', title=f'shift = {shift}',
  11. suptitle='Rotating cyclic colormaps'
  12. )
  13. ax.colorbar(m, loc='b', locator='null')

_images/colormaps_13_0.svg

  1. [9]:
  1. import proplot as plot
  2. import numpy as np
  3. state = np.random.RandomState(51423)
  4. data = state.rand(20, 20).cumsum(axis=1)
  5. # Changing the colormap opacity
  6. # Use pcolorfast because AxesImage does not have issue where pixels
  7. # appear to have "outline" when colors are not 100% opaque
  8. fig, axs = plot.subplots(ncols=3, axwidth=1.7)
  9. for ax, alpha in zip(axs, (1.0, 0.5, 0.0)):
  10. alpha = (alpha, 1.0)
  11. cmap = plot.Colormap('batlow_r', alpha=alpha)
  12. m = ax.pcolorfast(data, cmap=cmap, levels=10, extend='both')
  13. ax.colorbar(m, loc='b', locator='none')
  14. ax.format(
  15. title=f'alpha = {alpha}', xlabel='x axis', ylabel='y axis',
  16. suptitle='Adding opacity gradations'
  17. )
  1. /home/docs/checkouts/readthedocs.org/user_builds/proplot/conda/v0.6.4/lib/python3.8/site-packages/proplot/axes/plot.py:3877: ProPlotWarning: Using manual alpha-blending for 'batlow_r_copy' colorbar solids.
  2. /home/docs/checkouts/readthedocs.org/user_builds/proplot/conda/v0.6.4/lib/python3.8/site-packages/proplot/axes/plot.py:3877: ProPlotWarning: Using manual alpha-blending for 'batlow_r_copy' colorbar solids.

_images/colormaps_14_1.svg

  1. [10]:
  1. import proplot as plot
  2. import numpy as np
  3. state = np.random.RandomState(51423)
  4. data = state.rand(20, 20).cumsum(axis=1)
  5. # Changing the colormap gamma
  6. fig, axs = plot.subplots(ncols=3, axwidth=1.7)
  7. for ax, gamma in zip(axs, (0.7, 1.0, 1.4)):
  8. cmap = plot.Colormap('boreal', gamma=gamma)
  9. m = ax.pcolormesh(data, cmap=cmap, levels=10, extend='both')
  10. ax.colorbar(m, loc='b', locator='none')
  11. ax.format(
  12. title=f'gamma = {gamma}', xlabel='x axis', ylabel='y axis',
  13. suptitle='Changing the PerceptuallyUniformColormap gamma'
  14. )

_images/colormaps_15_0.svg

Downloading colormaps

There are plenty of online interactive tools for generating perceptually uniform colormaps, including Chroma.js, HCLWizard, HCL picker, the CCC-tool, and SciVisColor.

To add colormaps downloaded from any of these sources, save the colormap data to a file in your ~/.proplot/cmaps folder and call register_cmaps (or restart your python session), or use from_file. The file name is used as the registered colormap name. See from_file for a table of valid file extensions.