#!/usr/bin/env python # coding: utf-8 # # Activity 8 - Interaction and Animation # # We saw in our previous notebook how to create visualisations using matplotlib, seaborn, and pandas - however, in most cases these were static. We did get some interaction through the 3D plots and through using the Plotly library. Here, we are going to pursue this further, and look at how we can incorporate interaction and animation into our tools. # # In particular, interaction techniques are useful for creatng dashboards (visual analytics) interfaces. Animations can be useful for conveying the story, by linking multiple still images together or by showing the analytical process. # # In this example notebook, we demonstrate how to create interactive widgets that can be used to filter data from a dataframe, either based on range selection or by item selection. We also demonstrate how an animated GIF can be constructed by taking frames of a plot to build an animation. We use a live data set based on COVID-19 to illustrate the concepts in this notebook. # # Further details are in the following blog post: https://towardsdatascience.com/interactive-controls-for-jupyter-notebooks-f5c94829aee6 # In[15]: import pandas as pd from datetime import datetime, timedelta import matplotlib.pyplot as plt # In[17]: get_ipython().system('pip install ipywidgets') # In[16]: import ipywidgets as widgets from ipywidgets import interact, interact_manual # In[18]: df = pd.read_csv('https://coronavirus.data.gov.uk/downloads/csv/coronavirus-cases_latest.csv') df # In[23]: @interact def show_articles_more_than(column='Daily lab-confirmed cases', x=20): return df.loc[df[column] > x] # In[22]: # What if we want a custom min-max range for our slider? # https://ipywidgets.readthedocs.io/en/latest/examples/Using%20Interact.html @interact def show_articles_more_than(column='Daily lab-confirmed cases', x=widgets.IntSlider(min=0, max=1000, step=1, value=10)): return df.loc[df[column] > x] # In[25]: @interact def show_for_place(column='Area name', x=sorted(df['Area name'].unique())): return df.loc[df[column] == x] # In[26]: get_ipython().system('pip install moviepy') import glob import moviepy.editor as mpy # In[27]: plt.figure(figsize=(20,10)) data = df[df['Area type'] == 'utla'] plt.xticks(rotation=90) plt.plot(data.groupby('Specimen date').sum()['Daily lab-confirmed cases']) # In[29]: data = df[df['Area type'] == 'utla'] output = data.groupby('Specimen date').sum()['Daily lab-confirmed cases'] output # In[30]: for i in range(len(output)): oo = output[:i] plt.xticks(rotation=90) plt.plot(oo) plt.savefig(f"./pngs/{i}.png") plt.close() # In[31]: import os gif_name = 'COVID.gif' fps = 6 file_list = sorted(glob.glob('./pngs/*.png'), key=os.path.getmtime) clip = mpy.ImageSequenceClip(file_list, fps=fps) clip.write_gif('{}'.format(gif_name), fps=fps) # In[ ]: