Skip to content

Instantly share code, notes, and snippets.

@laurencee9
Created August 22, 2018 00:59
Show Gist options
  • Save laurencee9/c1ff874890f28af641ce480a2a9a0ac1 to your computer and use it in GitHub Desktop.
Save laurencee9/c1ff874890f28af641ce480a2a9a0ac1 to your computer and use it in GitHub Desktop.
Construct a contour plot from a random landscape.
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as stats
import random as rdm
def add_mountain(V, idx, idy, height):
w,h = V.shape
X = np.broadcast_to(range(w), (h,w))
Y = np.transpose(np.broadcast_to(range(h), (w,h)))
R = np.sqrt((X-idx)**2.0+(Y-idy)**2.0)
V += stats.norm.pdf(np.transpose(R), 0, height)
return V
def add_random_mountain(V, margin=[0,0]):
w, h = V.shape
idx = rdm.randint(margin[1],w-margin[1])
idy = rdm.randint(margin[0],h-margin[0])
height = (rdm.random()+0.5)*12
V = add_mountain(V, idx, idy, height)
return V
def get_cmap():
import matplotlib as mpl
C = ['white', '#31a354']
cm = mpl.colors.LinearSegmentedColormap.from_list("test", C)
return cm
#============================
# Parameters
#============================
figscale = 8.0 # Scaling of the figure
scaling = 200 # Number of pixels
aspect_ratio = 3 # Ratio width/height
margin = [0,20] # x,y margin. Mountains are spanned inside the margins.
n_mountains = 90 # Number of mountains
n_contours = 8 # Controls the number of contours
contour_color = "#3182bd"
output_name = "./gist_test.png"
with_cmap = False
#============================
# Routine
#============================
# Init potential
h,w = int(scaling*aspect_ratio),int(scaling)
V = np.zeros((w,h))
# Add mountains
for k in range(n_mountains):
V = add_random_mountain(V, margin=margin)
X, Y = np.meshgrid(range(h), range(w))
fig = plt.figure(figsize=(aspect_ratio*figscale,figscale))
ax = plt.gca()
CS = plt.contour(X, Y, V, n_contours, colors=contour_color)
if with_cmap: plt.imshow(V, interpolation='bilinear', origin='lower', cmap=get_cmap(), alpha=0.3)
ax.axis("off")
plt.savefig(output_name, dpi=100)
@laurencee9
Copy link
Author

example

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