Skip to content

Instantly share code, notes, and snippets.

@airalcorn2
Last active April 13, 2018 17:40
Show Gist options
  • Save airalcorn2/72201fbcc486b570b357b7b8424f8c1b to your computer and use it in GitHub Desktop.
Save airalcorn2/72201fbcc486b570b357b7b8424f8c1b to your computer and use it in GitHub Desktop.
Python code to generate the plots used to make this GIF --> http://imgur.com/BjgN6UA.
# Michael A. Alcorn
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import multiprocessing
import numpy as np
import pandas as pd
import seaborn as sns
import time
import tqdm
from datetime import datetime, timedelta
from mpl_toolkits.basemap import Basemap
df = pd.read_csv("species.csv")
gps_col = "GPS (Approximate)"
counts = df.groupby(gps_col).count()
coordinates = [x.split(", ") for x in counts.index]
coordinates = np.array(coordinates, dtype = "float32")
lat = coordinates[:, 0]
lng = coordinates[:, 1]
z = np.array(counts["Common"])
max_obs = z.max()
cmap = sns.cubehelix_palette(n_colors = max_obs, as_cmap = True)
(center_lat, center_long) = (0, -98)
m = Basemap(lat_0 = center_lat, lon_0 = center_long)
m.drawmapboundary()
m.drawcoastlines()
(x, y) = m(lng, lat)
m.scatter(x, y, c = z / max_obs, s = 5 * z, cmap = cmap)
plt.show()
df["Date"] = pd.to_datetime(df["Date"])
start_date = df["Date"].min()
df["Day Count"] = df["Date"] - start_date
df["Day Count"] = df["Day Count"].apply(lambda x: x.days)
end_date = datetime.today()
total_days = (end_date - start_date).days + 1
def create_plot(day_count):
plt.close("all")
counts = df[df["Day Count"] <= day_count].groupby([gps_col, "Locality"]).count()
coordinates = [x[0].split(", ") for x in counts.index]
coordinates = np.array(coordinates, dtype = "float32")
lat = coordinates[:, 0]
lng = coordinates[:, 1]
count = np.array(counts["Common"])
labels = [x[1] for x in counts.index]
text = ["{0}: {1}".format(labels[i], count[i]) for i in range(len(counts))]
z = count
m = Basemap(lat_0 = center_lat, lon_0 = center_long)
m.drawmapboundary()
m.drawcoastlines()
(x, y) = m(lng, lat)
m.scatter(x, y, c = z / max_obs, s = 5 * z, cmap = cmap, vmin = 0, vmax = 1)
date_str = str(start_date + timedelta(days = day_count)).split()[0]
plt.title(date_str)
plt.savefig("{0}".format(day_count).zfill(5), bbox_inches = "tight", dpi = 199)
start = time.time()
pool = multiprocessing.Pool(multiprocessing.cpu_count())
for _ in tqdm.tqdm(pool.imap_unordered(create_plot, list(range(total_days))), total = total_days):
pass
pool.close()
pool.join()
print("Total Time: {0:.0f} s".format(time.time() - start))
# Create GIF with:
# convert -loop 0 *.png species.gif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment