Plotting 2D data

ProPlot adds new features to various Axes plotting methods using a set of wrapper functions. When a plotting method like contourf is “wrapped” by one of these functions, it accepts the same parameters as the wrapper. These features are a strict superset of the matplotlib API. This section documents the features added by wrapper functions to 2D plotting commands like contour, contourf, pcolor, and pcolormesh.

Colormaps and normalizers

It is often desirable to create ProPlot colormaps on-the-fly, without explicitly using the Colormap constructor function. To enable this, the cmap_changer wrapper adds the cmap and cmap_kw arguments to every 2D plotting method. These arguments are passed to the Colormap constructor function, and the resulting colormap is used for the input data. For example, to create and apply a monochromatic colormap, you can simply use cmap='color name'.

The cmap_changer wrapper also adds the norm and norm_kw arguments. They are passed to the Norm constructor function, and the resulting normalizer is used for the input data. For more information on colormaps and normalizers, see the colormaps section and this matplotlib tutorial.

  1. [1]:
  1. import proplot as plot
  2. import numpy as np
  3. N = 20
  4. state = np.random.RandomState(51423)
  5. data = 10 ** (0.25 * np.cumsum(state.rand(N, N), axis=0))
  6. fig, axs = plot.subplots(ncols=2, span=False)
  7. axs.format(
  8. xlabel='xlabel', ylabel='ylabel', grid=True,
  9. suptitle='On-the-fly colormaps and normalizers'
  10. )
  11. # On-the-fly colormaps and normalizers
  12. axs[0].pcolormesh(data, cmap=('orange0', 'blood'), colorbar='b')
  13. axs[1].pcolormesh(data, norm='log', cmap=('orange0', 'blood'), colorbar='b')
  14. axs[0].format(title='Linear normalizer')
  15. axs[1].format(title='Logarithmic normalizer')

_images/2dplots_2_0.svg

Discrete colormap levels

The cmap_changer wrapper also applies the DiscreteNorm normalizer to every colormap plot. DiscreteNorm converts data values to colormap colors by (1) transforming data using an arbitrary continuous normalizer (e.g. LogNorm), then (2) mapping the normalized data to discrete colormap levels (just like BoundaryNorm).

By applying DiscreteNorm to every plot, ProPlot permits distinct “levels” even for commands like pcolor and pcolormesh. Distinct levels can help the reader discern exact numeric values and tends to reveal qualitative structure in the figure. They are also critical for users that would prefer contours, but have complex 2D coordinate matrices that trip up the contouring algorithm. DiscreteNorm also fixes the colormap end-colors by ensuring the following conditions are met (this may seem nitpicky, but it is crucial for plots with very few levels):

  1. All colormaps always span the entire color range, independent of the extend setting.

  2. Cyclic colormaps always have distinct color levels on either end of the colorbar.

  1. [2]:
  1. import proplot as plot
  2. import numpy as np
  3. # Pcolor plot with and without distinct levels
  4. fig, axs = plot.subplots(ncols=2, axwidth=2)
  5. state = np.random.RandomState(51423)
  6. data = (state.normal(0, 1, size=(33, 33))).cumsum(axis=0).cumsum(axis=1)
  7. axs.format(suptitle='Pcolor plot with levels')
  8. for ax, n, mode, side in zip(axs, (200, 10), ('Ambiguous', 'Discernible'), 'lr'):
  9. ax.pcolor(data, cmap='spectral_r', N=n, symmetric=True, colorbar=side)
  10. ax.format(title=f'{mode} level boundaries', yformatter='null')

_images/2dplots_4_0.svg

  1. [3]:
  1. import proplot as plot
  2. import numpy as np
  3. fig, axs = plot.subplots(
  4. [[0, 0, 1, 1, 0, 0], [2, 3, 3, 4, 4, 5]],
  5. wratios=(1.5, 0.5, 1, 1, 0.5, 1.5), axwidth=1.7, ref=1, right='2em'
  6. )
  7. axs.format(suptitle='DiscreteNorm color-range standardization')
  8. levels = plot.arange(0, 360, 45)
  9. state = np.random.RandomState(51423)
  10. data = (20 * (state.rand(20, 20) - 0.4).cumsum(axis=0).cumsum(axis=1)) % 360
  11. # Cyclic colorbar with distinct end colors
  12. ax = axs[0]
  13. ax.pcolormesh(
  14. data, levels=levels, cmap='phase', extend='neither',
  15. colorbar='b', colorbar_kw={'locator': 90}
  16. )
  17. ax.format(title='cyclic colormap\nwith distinct end colors')
  18. # Colorbars with different extend values
  19. for ax, extend in zip(axs[1:], ('min', 'max', 'neither', 'both')):
  20. ax.pcolormesh(
  21. data[:, :10], levels=levels, cmap='oxy',
  22. extend=extend, colorbar='b', colorbar_kw={'locator': 90}
  23. )
  24. ax.format(title=f'extend={extend!r}')

_images/2dplots_5_0.svg

Special normalizers

The LinearSegmentedNorm colormap normalizer provides even color gradations with respect to index for an arbitrary monotonically increasing list of levels. This is automatically applied if you pass unevenly spaced levels to a plotting command, or it can be manually applied using e.g. norm='segmented'.

The DivergingNorm normalizer ensures the colormap midpoint lies on some central data value (usually 0), even if vmin, vmax, or levels are asymmetric with respect to the central value. This can be applied using e.g. norm='diverging' and be configured to scale colors “fairly” or “unfairly”:

  • With fair scaling (the default), the gradations on either side of the midpoint have equal intensity. If vmin and vmax are not symmetric about zero, the most intense colormap colors on one side of the midpoint will be truncated.

  • With unfair scaling, the gradations on either side of the midpoint are warped so that the full range of colormap colors is traversed. This configuration should be used with care, as it may lead you to misinterpret your data!

The below example demonstrates how these normalizers can be used for datasets with unusual statistical distributions.

  1. [4]:
  1. import proplot as plot
  2. import numpy as np
  3. # Linear segmented norm
  4. state = np.random.RandomState(51423)
  5. data = 10**(2 * state.rand(20, 20).cumsum(axis=0) / 7)
  6. fig, axs = plot.subplots(ncols=2, axwidth=2.4)
  7. ticks = [5, 10, 20, 50, 100, 200, 500, 1000]
  8. for i, (norm, title) in enumerate(zip(
  9. ('linear', 'segmented'),
  10. ('Linear normalizer', 'LinearSegmentedNorm')
  11. )):
  12. m = axs[i].contourf(
  13. data, levels=ticks, extend='both',
  14. cmap='Mako', norm=norm,
  15. colorbar='b', colorbar_kw={'ticks': ticks},
  16. )
  17. axs[i].format(title=title)
  18. axs.format(suptitle='Linear segmented normalizer demo')

_images/2dplots_7_0.svg

  1. [5]:
  1. import proplot as plot
  2. import numpy as np
  3. # Diverging norm
  4. state = np.random.RandomState(51423)
  5. data1 = (state.rand(20, 20) - 0.43).cumsum(axis=0)
  6. data2 = (state.rand(20, 20) - 0.57).cumsum(axis=0)
  7. fig, axs = plot.subplots(nrows=2, ncols=2, axwidth=2.4, order='F')
  8. cmap = plot.Colormap('DryWet', cut=0.1)
  9. axs.format(suptitle='Diverging normalizer demo')
  10. i = 0
  11. for data, mode, fair in zip(
  12. (data1, data2),
  13. ('positive', 'negative'),
  14. ('fair', 'unfair')
  15. ):
  16. for fair in ('fair', 'unfair'):
  17. norm = plot.Norm('diverging', fair=(fair == 'fair'))
  18. ax = axs[i]
  19. m = ax.contourf(data, cmap=cmap, norm=norm)
  20. ax.colorbar(m, loc='b', locator=1)
  21. ax.format(title=f'Skewed {mode} data, {fair!r} scaling')
  22. i += 1

_images/2dplots_8_0.svg

Standardized arguments

The standardize_2d wrapper is used to standardize positional arguments across all 2D plotting methods. Among other things, it guesses coordinate edges for pcolor and pcolormesh plots when you supply coordinate centers, and calculates coordinate centers for contourf and contour plots when you supply coordinate edges. Notice the locations of the rectangle edges in the pcolor plots shown below.

  1. [6]:
  1. import proplot as plot
  2. import numpy as np
  3. # Figure and sample data
  4. state = np.random.RandomState(51423)
  5. x = y = np.array([-10, -5, 0, 5, 10])
  6. xedges = plot.edges(x)
  7. yedges = plot.edges(y)
  8. data = state.rand(y.size, x.size) # "center" coordinates
  9. lim = (np.min(xedges), np.max(xedges))
  10. with plot.rc.context({'image.cmap': 'Grays', 'image.levels': 21}):
  11. fig, axs = plot.subplots(ncols=2, nrows=2, share=False)
  12. axs.format(
  13. xlabel='xlabel', ylabel='ylabel',
  14. xlim=lim, ylim=lim, xlocator=5, ylocator=5,
  15. suptitle='Standardized input demonstration'
  16. )
  17. axs[0].format(title='Supplying coordinate centers')
  18. axs[1].format(title='Supplying coordinate edges')
  19. # Plot using both centers and edges as coordinates
  20. axs[0].pcolormesh(x, y, data)
  21. axs[1].pcolormesh(xedges, yedges, data)
  22. axs[2].contourf(x, y, data)
  23. axs[3].contourf(xedges, yedges, data)

_images/2dplots_10_0.svg

Pandas and xarray integration

The standardize_2d wrapper also integrates 2D plotting methods with pandas DataFrames and xarray DataArrays. When you pass a DataFrame or DataArray to any plotting command, the x-axis label, y-axis label, legend label, colorbar label, and/or title are configured from the metadata. This restores some of the convenience you get with the builtin pandas and xarray plotting functions. This feature is optional; installation of pandas and xarray are not required.

  1. [7]:
  1. import xarray as xr
  2. import numpy as np
  3. import pandas as pd
  4. # DataArray
  5. state = np.random.RandomState(51423)
  6. linspace = np.linspace(0, np.pi, 20)
  7. data = 50 * state.normal(1, 0.2, size=(20, 20)) * (
  8. np.sin(linspace * 2) ** 2
  9. * np.cos(linspace + np.pi / 2)[:, None] ** 2
  10. )
  11. lat = xr.DataArray(
  12. np.linspace(-90, 90, 20),
  13. dims=('lat',),
  14. attrs={'units': 'deg_north'}
  15. )
  16. plev = xr.DataArray(
  17. np.linspace(1000, 0, 20),
  18. dims=('plev',),
  19. attrs={'long_name': 'pressure', 'units': 'mb'}
  20. )
  21. da = xr.DataArray(
  22. data,
  23. name='u',
  24. dims=('plev', 'lat'),
  25. coords={'plev': plev, 'lat': lat},
  26. attrs={'long_name': 'zonal wind', 'units': 'm/s'}
  27. )
  28. # DataFrame
  29. data = state.rand(12, 20)
  30. df = pd.DataFrame(
  31. (data - 0.4).cumsum(axis=0).cumsum(axis=1),
  32. index=list('JFMAMJJASOND'),
  33. )
  34. df.name = 'temporal data'
  35. df.index.name = 'month'
  36. df.columns.name = 'variable (units)'
  1. [8]:
  1. import proplot as plot
  2. fig, axs = plot.subplots(nrows=2, axwidth=2.5, share=0)
  3. axs.format(collabels=['Automatic subplot formatting'])
  4. # Plot DataArray
  5. cmap = plot.Colormap('RdPu', left=0.05)
  6. axs[0].contourf(da, cmap=cmap, colorbar='l', linewidth=0.7, color='k')
  7. axs[0].format(yreverse=True)
  8. # Plot DataFrame
  9. axs[1].contourf(df, cmap='YlOrRd', colorbar='r', linewidth=0.7, color='k')
  10. axs[1].format(xtickminor=False)

_images/2dplots_13_0.svg

Contour and gridbox labels

The cmap_changer wrapper also allows you to quickly add labels to heatmap, pcolor, pcolormesh, contour, and contourf plots by simply using labels=True. The label text is colored black or white depending on the luminance of the underlying grid box or filled contour.

cmap_changer draws contour labels with clabel and grid box labels with text. You can pass keyword arguments to these functions using the labels_kw dictionary keyword argument, and change the label precision with the precision keyword argument. See cmap_changer for details.

  1. [9]:
  1. import proplot as plot
  2. import pandas as pd
  3. import numpy as np
  4. fig, axs = plot.subplots(
  5. [[1, 1, 2, 2], [0, 3, 3, 0]],
  6. axwidth=2.2, share=1, span=False, hratios=(1, 0.9)
  7. )
  8. state = np.random.RandomState(51423)
  9. data = state.rand(6, 6)
  10. data = pd.DataFrame(data, index=pd.Index(['a', 'b', 'c', 'd', 'e', 'f']))
  11. axs.format(xlabel='xlabel', ylabel='ylabel', suptitle='Labels demo')
  12. # Heatmap with labeled boxes
  13. ax = axs[0]
  14. m = ax.heatmap(
  15. data, cmap='rocket', labels=True,
  16. precision=2, labels_kw={'weight': 'bold'}
  17. )
  18. ax.format(title='Heatmap plot with labels')
  19. # Filled contours with labels
  20. ax = axs[1]
  21. m = ax.contourf(
  22. data.cumsum(axis=0), labels=True,
  23. cmap='rocket', labels_kw={'weight': 'bold'}
  24. )
  25. ax.format(title='Filled contour plot with labels')
  26. # Line contours with labels
  27. ax = axs[2]
  28. ax.contour(
  29. data.cumsum(axis=1) - 2, color='gray8',
  30. labels=True, lw=2, labels_kw={'weight': 'bold'}
  31. )
  32. ax.format(title='Line contour plot with labels')

_images/2dplots_15_0.svg

Heatmap plots

The new heatmap command calls pcolormesh and configures the axes with settings that are suitable for heatmaps – fixed aspect ratio, no gridlines, no minor ticks, and major ticks at the center of each box. Among other things, this is useful for displaying covariance and correlation matrices, as shown below.

  1. [10]:
  1. import proplot as plot
  2. import numpy as np
  3. import pandas as pd
  4. # Covariance data
  5. state = np.random.RandomState(51423)
  6. data = state.normal(size=(10, 10)).cumsum(axis=0)
  7. data = (data - data.mean(axis=0)) / data.std(axis=0)
  8. data = (data.T @ data) / data.shape[0]
  9. data[np.tril_indices(data.shape[0], -1)] = np.nan # fill half with empty boxes
  10. data = pd.DataFrame(data, columns=list('abcdefghij'), index=list('abcdefghij'))
  11. # Covariance matrix plot
  12. fig, ax = plot.subplots(axwidth=4.5)
  13. m = ax.heatmap(
  14. data, cmap='ColdHot', vmin=-1, vmax=1, N=100,
  15. lw=0.5, edgecolor='k', labels=True, labels_kw={'weight': 'bold'},
  16. clip_on=False, # turn off clipping so box edges are not cut in half
  17. )
  18. ax.format(
  19. suptitle='Heatmap demo', title='Table of correlation coefficients', alpha=0,
  20. xloc='top', yloc='right', yreverse=True, ticklabelweight='bold', linewidth=0,
  21. ytickmajorpad=4, # the ytick.major.pad rc setting; adds extra space
  22. )

_images/2dplots_17_0.svg