Skip to content

Instantly share code, notes, and snippets.

@fperez
Created March 9, 2011 20:23
Show Gist options
  • Save fperez/862919 to your computer and use it in GitHub Desktop.
Save fperez/862919 to your computer and use it in GitHub Desktop.
Matplotlib contours with overlap control
"""Contours with overlap control.
This script generates widely spaced black contours, with a gray patch in a
subregion where more finely-spaced colored contours are visible. The gray
patch covers the black contours.
"""
import numpy as np
import matplotlib.mlab as mlab
from matplotlib.patches import Rectangle
import matplotlib.pyplot as plt
def xy(x1, x2, y1, y2, npts):
x = np.linspace(x1, x2, npts)
y = np.linspace(y1, y2, npts)
X, Y = np.meshgrid(x, y)
return X, Y
def z(x, y):
Z1 = mlab.bivariate_normal(x, y, 1.0, 1.0, 0.0, 0.0)
Z2 = mlab.bivariate_normal(x, y, 1.5, 0.5, 1, 1)
# difference of Gaussians
return 10.0 * (Z2 - Z1)
# Main script
npts = 250
X, Y = xy(-3,3,-2,2, npts)
Z = z(X, Y)
plt.close('all')
# Create a simple contour plot with labels using default colors. The
# inline argument to clabel will control whether the labels are draw
# over the line segments of the contour, removing the lines beneath
# the label
plt.figure()
ax = plt.gca()
cs = plt.contour(X, Y, Z, colors='k', linewidths=3, zorder=1)
cs.clabel(inline=1, fontsize=10)
ax = plt.gca()
ax.set_title('Coarse/fine contours with overlap control')
# Rectangular box over subregion. Left opacity at 0.95 so we can still see the
# covered contours underneath; in practice if full coverage is desired, simply
# omit the alpha parameter
rect = Rectangle((0,0), 2, 1.5, facecolor="#aaaaaa", alpha=0.95, zorder=5)
ax.add_patch(rect)
# Second patch of more finely spaced contours in a subregion (over box)
Xs, Ys = xy(0, 2, 0, 1.5, npts)
Zs = z(Xs, Ys)
cs2 = ax.contour(Xs, Ys, Zs, 15, zorder=10)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment