#!/usr/bin/env python # coding: utf-8 # In[1]: import numpy as np import matplotlib.pyplot as plt # In[2]: get_ipython().run_line_magic('matplotlib', 'inline') # The population of Hares, Lynxes and carrots in Canada is in the file [population.txt](http://www.scipy-lectures.org/_downloads/populations.txt). Download that file and place it in this directory. # Once this is done, execute the code below to load the data in the variable `data`. # Important remark: **you should not use any `for` loop in this exercise!** :-) # In[3]: data = np.loadtxt('populations.txt') # In[4]: year, hares, lynxes, carrots = data.T # trick: columns to variables # In[5]: year, hares, lynxes, carrots = data.T populations = data[:,1:] # In[6]: data # Plot the data (year vs each population item), using `label` and `legend`. # In[7]: for elt, name in zip(populations.T, ["hares", "lynxes", "carrots"]): plt.plot(year, elt, label=name, lw=.5) plt.legend() plt.grid(ls='-', alpha=.2) # Compute the mean (`np.mean?`) and standard deviation (`np.std?`) of each piece of data # In[8]: np.mean(data, axis=0) # In[9]: np.std(data, axis=0) # Which year each species had the largest population? (`np.argmax?` and use fancy indexing) # In[10]: year[np.argmax(data[:,1:], axis=0)] # Which year any of the population is over 50000? # In[11]: mask = data[:,1:] > 50000 # In[12]: year[np.any(mask, axis=1)] # The top two years for each species when they had the lowest population # You may use `argsort`, which gives the indices for which the array value would be sorted. # In[13]: get_ipython().run_line_magic('pinfo', 'np.argsort') # In[14]: year[np.argsort(data[:,1:], axis=0)[:2]] # Compare (plot) the change in hare population (see `np.gradient?`) and the number of lynxes. # In[15]: np.gradient(hares) # In[16]: dhares = np.gradient(hares) plt.plot(dhares, lynxes, 'o', mfc='gray', mec='black') plt.grid(ls='-', alpha=.2) # In[17]: plt.plot(year, -dhares, lw=.5) plt.plot(year, lynxes, lw=.5) plt.grid(ls='-', alpha=.2) # In[ ]: