Interactive COVID-19 visualizations using Plotly with 4 lines of code | by Priya Dwivedi | Towards Data Science

In this age of technology, data is the new oil. Organizations all over the world are transforming their environments, processes and infrastructures to become more data-driven. A major reason is that data analytics and machine learning gives organizations visibility into how to run their business better. The push to remote work through COVID-19 will accelerate this trend towards technology and data.
A big part of analytics is presenting data in meaningful forms to the relevant decision makers so that they can easily comprehend the story. Traditionally organizations use software like Tableau to present cool interactive dashboards. In this blog, we show that open source libraries like Plotly Express can be used to do the same with just a few lines of code. We also coded all this in Bokeh but found the code was quite complex. Plotly, on the other hand, has built-in functionality that allows changing many things with parameters.
We have used the CDC data on Coronavirus to generate interactive plots. See below the plot of daily change in Coronavirus cases by country. This is a very interesting diagram that shows which countries have peaked and the number of daily cases are starting to decrease. The full code is available on Github. I hope you pull it and give it a shot.
At Deep Learning Analytics, we are very passionate about using data science and machine learning to solve problems. Please reach out to us through here if you are a Health Services company and looking for data science help in fighting this crisis.
Data visualizations is the “art” of presenting your data in an interesting, accurate and comprehensible manner. There are many types of visualizations that are used across all industries; the most common ones being bar graphs, pie charts, line graphs and histograms. But in many cases, these basic visualizations are not sufficient to effectively present the data. So more analysts are gravitating to visualizations like choropleths, time-series, heat maps, radial trees, word clouds etc.
In this blog, we will explore a specific type of visualization called the choropleths, and show how you can create these visualizations in python with only a few lines of code.
Choropleths are thematic maps in which different areas are shaded on a map to show different statistics. Below is choropleth map of a fraction of Australians that identify as Anglicans as of 2011. This map is from Wikipedia Chloropeths page.
Choropleths can be of any granularity: from as small as a neighbourhood to the entire world, depending on what needs to be projected.
In this blog, we will be exploring how to create a choropleth in python using the Plotly Express library. We will do a visualization of cases for countries in the World and then deep dive into cases in the United States. So let's get started!
First, we will install the dependencies required to run this code: pandas and plotly
pip install pandaspip install plotly
Once we have these libraries downloaded, we will download and load the data. The data used in this blog is from the website called ourworldindata.org . The data available here is updated daily. You can download the data using wget as shown below:
!wget https://covid.ourworldindata.org/data/owid-covid-data.csv
Please follow along with the code at my Github link
The output of the above code is the first 5 rows of the data as shown below:
The dataset has information on country code, location, date, total cases, new cases, total deaths, new deaths and cases per million.
We want to remove the entries corresponding to the country “World” which is sum total for all countries and sort the data by date.
df = pd.read_csv('owid-covid-data.csv')## Drop rows corresponding to the Worlddf = df[df.location != 'World']## Sort df by datedf = df.sort_values(by=['date'])
Making choropleth maps requires two main types of input:
Geometry information supplied through a GeoJson file that has coordinates for the state, area, country that you are plottingData frame with values for that geometry
Geometry information supplied through a GeoJson file that has coordinates for the state, area, country that you are plotting
Data frame with values for that geometry
Plotly has built in geometries for World and US maps and we will use them here.
To create an interactive word map of daily new COVID-19 confirmed cases, the command is:
fig = px.choropleth(df, locations="iso_code",                    color="new_cases",                    hover_name="location",                    animation_frame="date",                    title = "Daily new COVID cases",                   color_continuous_scale=px.colors.sequential.PuRd)fig["layout"].pop("updatemenus")fig.show()
Here :
df — Our data frame with COVID data
Location — Countries are identified by their iso code. Plotly is able to get geo data using the iso code
color — Column we want to plot. New cases here
animation_frame: column you want to run animation on. In our case this is the date
color_continuous_scale — Allows plotly to continuously change the axis and the colors as the slider is moved
fig[“layout”].pop(“updatemenus”) — This creates a slider for date that can be manually toggled. If this line is commented out then the plot has a video type start, stop button
The plot below shows output for March 2, 2020. This is the trigger point where new case growth rate is slowing in China but increasing in Iran, Italy and South Korea.
In the notebook, I have also added a plot of total cumulative cases by week. To do this we add another line of code that adds a week number in pandas
df['new_date'] = pd.to_datetime(df['date'])df['Year-Week'] = df['new_date'].dt.strftime('%Y-%U')
Looking at this it is hard to believe the US had only around 100K cases a month back!.
To add data for US, we need two things — 1. Data source that has US state and county level data and 2. Geo mapping of states and counties
The COVID-19 US data is from NYtimes COVID-19-data. Thanks to the NY Times to make it public for use by analysts. You can download the data using
!git clone https://github.com/nytimes/covid-19-data.git
We can get geo data for counties using the script below. This data has polygon coordinates for all the counties in the US.
from urllib.request import urlopenimport jsonwith urlopen('https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json') as response:    counties = json.load(response)
We can plot total cases in Plotly using the command below. The main difference from our earlier plots is that we use FIPS code for different counties instead of iso country codes as before.
df_us_week = df_us_week.sort_values(by=['Year-Week'])fig = px.choropleth(df_us_week,                        geojson=counties,                       locations='fips',                       color='cases',                     color_continuous_scale="Viridis",                     title = "Total Weekly Cases by Counties",                     scope="usa",                     animation_frame="Year-Week",                          )fig["layout"].pop("updatemenus")fig.show()
The output is below. It shows how severe impact has been localized to a few counties.
The Github link also has details on creating visualizations on a state level.
It was amazing how easily map plotting can be done using Plotly Express. If you have a custom map, you can also plot on it using geojson data. This is explained here.
I hope you give the code a try and create more interesting visualizations.
At Deep Learning Analytics, we are extremely passionate about using Machine Learning to solve real-world problems. We have helped many businesses deploy innovative AI-based solutions. Contact us through our website here if you see an opportunity to collaborate. This blog was written by Priya Dwivedi and Faizan Khan.
Plotly Express Chloropeths Visualization