%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import scipy.ndimage
import scipy.spatial
Make 50 random points with X and Y coordinates from 0 to 256.
point_count = 50
points = np.random.rand(point_count, 2) * 256
points[:3]
Look at the last three points.
# Type your solution here and press CTRL-ENTER
Make a scatter plot of the 50 random points.
values = np.random.rand(point_count) * 300
plt.scatter(points[:, 0], points[:, 1], c=values, s=values, cmap=plt.cm.Greens)
plt.axis('tight');
Set points with an area greater than 50 to a different color using the Paired colormap.
# Type your solution here and press CTRL-ENTER
Paint a heatmap of the 50 random points.
def get_heatmap(points):
image = np.zeros((256, 256))
for x, y in points:
image[int(y), int(x)] += 1
return scipy.ndimage.gaussian_filter(image, (10, 10))
plt.imshow(get_heatmap(points), origin='lower');
Overlay a scatter plot on the heatmap.
# Type your solution here and press CTRL-ENTER
Pick a random point.
import random
random_point = random.choice(points)
random_point
Get the five points closest to the random point.
import scipy.spatial
kd_tree = scipy.spatial.KDTree(points)
neighbor_distances, neighbor_indices = kd_tree.query(random_point, k=5)
points[neighbor_indices]
Generate fifty heatmaps where the first heatmap contains a random point and the next heatmap adds a point that is close to the random point.
target_path = '/tmp/points%03d.png'
kd_tree = scipy.spatial.KDTree(points)
image = get_heatmap([random_point])
plt.imsave(target_path % 1, image, origin='lower')
for point_count in range(2, len(points) + 1):
nearest_points = points[kd_tree.query(random_point, k=point_count - 1)[1]]
image = get_heatmap(np.vstack([random_point, nearest_points]))
plt.imsave(target_path % point_count, image, origin='lower')
print(target_path % point_count)
Combine the fifty heatmaps into an animated GIF.
import subprocess
subprocess.call('sudo dnf -y install GraphicsMagick'.split())
subprocess.call('gm convert -delay 1 /tmp/points*.png /tmp/points.gif'.split())
from IPython.display import Image
Image('/tmp/points.gif')