Python Snippets
Package abbreviations
Unless otherwise specified, the snippets use the following conventions for package abbreviations
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
Improving exponential notation in colour bars
The default behaviour for handling exponents in colour bars isn't the prettiest, and can sometimes overlap the plot window itself. While there are options for shifting it exponent around to fit better, I find it looks a lot better to simply place it in the ylabel for the colour bar. This also provides a nice opportunity to add units!
Notes:
- Units are specified in line 20. Simply set to the empty string if you don't want units included.
- If you need more significant digits, modify the format string
{0:.2g}
by changing the2
to be the desired number of digits - This setting only permits 5 ticks along the colour bar: this is to avoid clutter while giving basic information on scaling. If you need / want more, simply modify line 9.
# Create colour bar in usual fashion
# the second and third line are useful
# for pdf outputs
cbar = plt.colorbar(plot_handle, ...)
cbar.solids.set_rasterized(True)
cbar.solids.set_edgecolor("face")
# Limit the number of ticks on the colour bar
tick_locator = mpl.ticker.MaxNLocator(nbins=5)
cbar.locator = tick_locator
cbar.update_ticks()
ticks = cbar.get_ticks()
# Re-scale the values to avoid the poorly-placed exponent
# above the colour bar
scale = np.log10(np.max(np.abs(ticks)))
scale = np.floor(scale)
# Specify units
units = 's$^{-1}$'
# Instead, simply add a ylabel to the colour bar giving the scale.
if scale != 0.:
cbar.ax.set_yticklabels(["{0:.2g}".format(tick/(10**scale)) for tick in ticks])
cbar.ax.set_ylabel('$\\times10^{' + '{0:d}'.format(int(scale)) + '}$ ' + units,
rotation = '-90', va='bottom')