Skip to content

Instantly share code, notes, and snippets.

@sqeezy
Created November 1, 2019 07:13
Show Gist options
  • Save sqeezy/9b8544f17eb269acb9973452a29dfe0b to your computer and use it in GitHub Desktop.
Save sqeezy/9b8544f17eb269acb9973452a29dfe0b to your computer and use it in GitHub Desktop.
EngFormatter
import matplotlib
import numpy as np
import matplotlib.cm as cm
import matplotlib.pyplot as plt
from matplotlib.ticker import EngFormatter
delta = 0.025
x = np.arange(-3.0, 3.0, delta)
y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (Z1 - Z2) * 2
fig, ax = plt.subplots()
im = ax.imshow(Z, interpolation='bilinear', origin='lower',
cmap=cm.gray, extent=(-3, 3, -2, 2))
levels = np.arange(-1.2, 1.6, 0.2)
CS = ax.contour(Z, levels, origin='lower', cmap='flag',
linewidths=2, extent=(-3, 3, -2, 2))
# Thicken the zero contour.
zc = CS.collections[6]
plt.setp(zc, linewidth=4)
ax.clabel(CS, levels[1::2], # label every second level
inline=1, fmt='%1.1f', fontsize=14)
# make a colorbar for the contour lines
formatter0 = EngFormatter(unit='m')
CB = fig.colorbar(CS, shrink=0.8, extend='both', format=formatter0)
ax.set_title('Lines with colorbar')
# We can still add a colorbar for the image, too.
CBI = fig.colorbar(im, orientation='horizontal', shrink=0.8)
# This makes the original colorbar look a bit out of place,
# so let's improve its position.
l, b, w, h = ax.get_position().bounds
ll, bb, ww, hh = CB.ax.get_position().bounds
CB.ax.set_position([ll, b + 0.1*h, ww, h*0.8])
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment