Python Snippets

From Fluids Wiki
Revision as of 23:09, 13 December 2018 by Bastorer (talk | contribs) (Created page with " === Package abbreviations === Unless otherwise specified, the snippets use the following conventions for package abbreviations <syntaxhighlight lang="python"> import matplo...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search


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:

  1. Units are specified in line 20. Simply set to the empty string if you don't want units included.
  2. If you need more significant digits, modify the format string {0:.2g} by changing the 2 to be the desired number of digits
  3. 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')