Skip to content

Instantly share code, notes, and snippets.

@ImportanceOfBeingErnest
Last active February 5, 2017 16:37
Show Gist options
  • Save ImportanceOfBeingErnest/5942b47054743c9b0805eea98f140e45 to your computer and use it in GitHub Desktop.
Save ImportanceOfBeingErnest/5942b47054743c9b0805eea98f140e45 to your computer and use it in GitHub Desktop.
Compare matplotlib contour and tricontour for randomized grid
# Code was written in an answer to this Stackoverflow question:
# http://stackoverflow.com/questions/42045921/why-does-pyplot-contour-require-z-to-be-a-2d-array
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
import numpy as np
fig, (ax, ax2) = plt.subplots(ncols=2, figsize=(6,3.7) )
plt.subplots_adjust(left=0.05, right=0.95, bottom=0.05, top=0.82, wspace=0.07)
def setup():
ax.clear()
ax2.clear()
ax.set_aspect("equal")
ax2.set_aspect("equal")
ax.set_xticks([])
ax.set_yticks([])
ax2.set_xticks([])
ax2.set_yticks([])
ax.set_title("contour")
ax2.set_title("tricontour")
axgrid = fig.add_axes([0.37, 0.95, 0.32, 0.03], facecolor="w")
axrand = fig.add_axes([0.37, 0.9, 0.32, 0.03], facecolor="w")
sgrid = Slider(axgrid, 'Grid', 3, 30, valinit=16)
srand = Slider(axrand, 'rand', 0, 1., valinit=0)
def update(val):
grid = int(sgrid.val)
rand = srand.val
setup()
x = np.linspace(0,5,grid)
y = np.linspace(0,5,grid)
X,Y = np.meshgrid(x,y)
Xr = np.random.rand(grid,grid)*5
Yr = np.random.rand(grid,grid)*5
X = (1-rand)*X + rand*Xr
Y = (1-rand)*Y + rand*Yr
Z = np.round(np.sin(X*1.1)*np.cos(Y*1.1), 2)
ax.contour(X,Y,Z, 10)
ax2.tricontour(X.ravel(),Y.ravel(),Z.ravel(), 10)
fig.canvas.draw_idle()
update(0)
sgrid.on_changed(update)
srand.on_changed(update)
plt.show()
@ImportanceOfBeingErnest
Copy link
Author

Creating the following matplotlib output

so_contourwithgrid2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment