Skip to content
Snippets Groups Projects
Dashboard.ipynb 13.2 KiB
Newer Older
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "from IPython.display import display, HTML, Markdown\n",
    "import covid_19_dashboard as helper"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "parameters"
    ]
   },
   "outputs": [],
   "source": [
    "ts_folder = \"../data/covid-19_jhu-csse/\"\n",
    "rates_folder = \"../data/covid-19_rates/\"\n",
    "geodata_path = \"../data/geodata/geo_data.csv\"\n",
    "out_folder = None\n",
    "PAPERMILL_OUTPUT_PATH = None"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Read in the data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "jhu_frames_map = helper.read_jhu_frames_map(ts_folder)\n",
    "rates_frames_map = helper.read_rates_frames_map(rates_folder)\n",
    "geodata_df = helper.read_geodata(geodata_path)\n",
    "\n",
    "# Identify countries with 100 or more cases\n",
    "countries_over_thresh = helper.countries_with_number_of_cases(jhu_frames_map, 'confirmed', 100)\n",
    "# Filter out some countries with very high case/population ratio\n",
    "countries_over_thresh = [c for c in countries_over_thresh if c not in set(['San Marino', 'Iceland'])]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Questions About COVID-19 and Its Spread\n",
    "\n",
    "Understanding the spread, distribution, and deadliness of COVID-19 is difficult, despite the data available about it. Differences in rates of testing, quality of data, demographics, etc. make it difficult to compare data between countries. \n",
    "\n",
    "All this needs to be considered when looking at the plots below. But despite those caveats, I found it helpful to plot the raw data, even though direct comparisons between countries might not be inaccurate."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "source": [
    "data_ts = jhu_frames_map['confirmed'].iloc[:,-1].name.strftime(\"%b %d %Y\")\n",
    "display(HTML(f\"<em>Data up to {data_ts}; countries with 100 or more confirmed cases.</em>\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## How are cases per 100,000 distributed geographically?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import altair as alt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "map_df = helper.compute_map_df(rates_frames_map, jhu_frames_map, geodata_df, countries_over_thresh)"
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "display(helper.map_of_variable(map_df, 'Confirmed/100k', 'Confirmed'))\n",
    "display(HTML('''\n",
    "<p style=\"font-size: smaller\">Data Sources: \n",
    "  <a href=\"https://github.com/CSSEGISandData/COVID-19\">JHU CSSE</a>,\n",
    "  <a href=\"https://data.worldbank.org/indicator/SP.POP.TOTL\">World Bank</a>,\n",
    "  <a href=\"https://worldmap.harvard.edu/data/geonode:country_centroids_az8\">Harvard Worldmap</a>\n",
    "</p>'''))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "source": [
    "bars = alt.Chart(map_df).mark_bar().encode(\n",
    "    x='Confirmed/100k:Q',\n",
    "    y=alt.Y(\"Country/Region:N\", sort='-x'),\n",
    "    tooltip=[\"Country/Region:N\", \n",
    "         \"Confirmed:Q\", \"Deaths:Q\", \"Recovered:Q\",\n",
    "         \"Confirmed/100k:Q\", \"Deaths/100k:Q\", \"Recovered/100k:Q\"]\n",
    ")\n",
    "\n",
    "text = bars.mark_text(\n",
    "    align='left',\n",
    "    baseline='middle',\n",
    "    dx=3  # Nudges text to right so it doesn't appear on top of the bar\n",
    ").encode(\n",
    "    text=alt.Text('Confirmed/100k:Q', format=\".3\")\n",
    "chart = (bars + text).properties(height=900, title=f\"Confirmed cases per 100k inhabitants\")\n",
    "display(chart)\n",
    "display(HTML('''\n",
    "<p style=\"font-size: smaller\">Data Sources: \n",
    "  <a href=\"https://github.com/CSSEGISandData/COVID-19\">JHU CSSE</a>,\n",
    "  <a href=\"https://data.worldbank.org/indicator/SP.POP.TOTL\">World Bank</a>,\n",
    "  <a href=\"https://worldmap.harvard.edu/data/geonode:country_centroids_az8\">Harvard Worldmap</a>\n",
    "</p>'''))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## How have cases been growing?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "confirmed_rate_df = helper.growth_df(rates_frames_map, geodata_df, 'confirmed', countries_over_thresh, 2)\n",
    "latest_confirmed_ser = confirmed_rate_df.set_index(\n",
    "    ['Country/Region', 'Geo Region', 'Date']).drop(\n",
    "    ['Longitude', 'Latitude'], axis=1).unstack().iloc[:,-1]\n",
    "sort_order = latest_confirmed_ser.groupby('Geo Region').mean().sort_values(ascending=False).index.tolist()"
   "execution_count": null,
    "base = alt.Chart(confirmed_rate_df).properties(\n",
    "    width=300, height=200, title=\"Countries with 2 or more cases per 100k\")\n",
    "line = base.mark_line().encode(\n",
    "    x='Date',\n",
    "    y='Confirmed/100k',\n",
    "    color='Country/Region',\n",
    "    facet=alt.Facet('Geo Region:N', columns=1, sort=alt.SortArray(sort_order), title='Geographic Region'),\n",
    "    tooltip=[\"Country/Region:N\", \"Date:T\", \"Confirmed/100k:Q\"]\n",
    ")\n",
    "line\n",
    "display(line)\n",
    "display(HTML('''\n",
    "<p style=\"font-size: smaller\">Data Sources: \n",
    "  <a href=\"https://github.com/CSSEGISandData/COVID-19\">JHU CSSE</a>,\n",
    "  <a href=\"https://data.worldbank.org/indicator/SP.POP.TOTL\">World Bank</a>,\n",
    "  <a href=\"https://worldmap.harvard.edu/data/geonode:country_centroids_az8\">Harvard Worldmap</a>\n",
    "</p>'''))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def country_increase_df(c, df_nominal, growth_in_rate_df):\n",
    "    over_100 = df_nominal[df_nominal['Confirmed'] >= 100]\n",
    "    tdf = (over_100[['Date', 'Confirmed']] - over_100.iloc[0][['Date', 'Confirmed']]).reset_index()\n",
    "    tdfr = growth_in_rate_df[(growth_in_rate_df['Date'] >= over_100.iloc[0]['Date']) &\n",
    "                             (growth_in_rate_df['Country/Region'] == c)].reset_index()\n",
    "    tdf['Confirmed/100k'] = tdfr['Confirmed/100k']\n",
    "    tdf['Country/Region'] = c\n",
    "    tdf['Days'] = (tdf['Date'] / np.timedelta64(1, 'D')).astype(int)\n",
    "    return tdf[['Country/Region', 'Days', 'Confirmed', 'Confirmed/100k']]\n",
    "\n",
    "\n",
    "growth_in_rate_df = helper.growth_df(rates_frames_map, geodata_df, 'confirmed', countries_over_thresh, 0)\n",
    "frame_map = {'confirmed': jhu_frames_map['confirmed'].groupby(level='Country/Region').sum()}\n",
    "growth_in_value_df = helper.growth_df(frame_map, geodata_df, 'confirmed', countries_over_thresh, 1000)\n",
    "growth_in_value_df = growth_in_value_df.rename({'Confirmed/100k':'Confirmed'}, axis=1)\n",
    "increase_df = pd.concat([country_increase_df(c, df_nominal, growth_in_rate_df) for \n",
    "                         c, df_nominal in growth_in_value_df.groupby('Country/Region')])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def facetted_growth_plot(df, variable, sort_order, ref_country, title, yscale='linear'):\n",
    "    base = alt.Chart(df).properties(\n",
    "        width=250, height=150)\n",
    "    line = base.mark_line().encode(\n",
    "        x='Days',\n",
    "        y=variable,\n",
    "        color='Country/Region',\n",
    "        tooltip=[\"Country/Region:N\", \"Days:Q\", f\"{variable}:Q\"]\n",
    "    )\n",
    "    label_loc = increase_df[increase_df['Country/Region'] == ref_country]['Days'].iloc[-2]\n",
    "    ref = base.mark_line(opacity=0.3).encode(\n",
    "        x='Days',\n",
    "        y=alt.Y(variable, scale=alt.Scale(type=yscale)),\n",
    "        color=alt.ColorValue('steelblue'),\n",
    "    ).transform_filter(f\"datum['Country/Region'] == '{ref_country}'\")\n",
    "    ref += ref.mark_text().encode(text='Country/Region:N').transform_filter(f\"datum['Days'] == {label_loc}\")\n",
    "    charts = []\n",
    "    # make our small multiples\n",
    "    for country in sort_order:\n",
    "        smallm = line.transform_filter(f\"datum['Country/Region'] == '{country}'\").properties(\n",
    "            title=country)\n",
    "        smallm += ref\n",
    "        charts.append(smallm)\n",
    "\n",
    "    # group the small multiples into 3 horizontal charts\n",
    "    groups = []\n",
    "    c = None\n",
    "    for i, chart in enumerate(charts):\n",
    "        if not i%3:\n",
    "            if c != None:\n",
    "                groups.append(c)\n",
    "            c = alt.hconcat()\n",
    "        c |= chart\n",
    "    # vertically combine the horizontal charts\n",
    "    chart = alt.vconcat(title=title)\n",
    "    for c in groups:\n",
    "        chart &= c\n",
    "    return chart"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sort_order = growth_in_value_df.groupby(\n",
    "    'Country/Region').max().sort_values(\n",
    "    'Confirmed', ascending=False).index.tolist()\n",
    "# Exclude China in this plot because its numbers are far greater then everywhere else\n",
    "sort_order = [o for o in sort_order if o != 'China']\n",
    "chart = facetted_growth_plot(increase_df[increase_df['Country/Region'] != 'China'], \n",
    "                             'Confirmed',\n",
    "                             sort_order,\n",
    "                             'Italy',\n",
    "                             \"Growth of cases from case 100, compared to Italy\")\n",
    "display(chart)\n",
    "display(HTML('''\n",
    "<p style=\"font-size: smaller\">Data Sources: \n",
    "  <a href=\"https://github.com/CSSEGISandData/COVID-19\">JHU CSSE</a>,\n",
    "  <a href=\"https://data.worldbank.org/indicator/SP.POP.TOTL\">World Bank</a>,\n",
    "  <a href=\"https://worldmap.harvard.edu/data/geonode:country_centroids_az8\">Harvard Worldmap</a>\n",
    "</p>\n",
    "<p style=\"font-size: smaller\">Inspired by <a href=\"https://covid19dashboards.com/growth-analysis/\">Thomas Wiecki</a>'''))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sort_order = growth_in_value_df.groupby(\n",
    "    'Country/Region').max().sort_values(\n",
    "    'Confirmed', ascending=False).index.tolist()\n",
    "chart = facetted_growth_plot(increase_df, \n",
    "                             'Confirmed/100k',\n",
    "                             sort_order,\n",
    "                             'Italy',\n",
    "                             \"Growth of cases/100k from case 100, compared to Italy\")\n",
    "display(chart)\n",
    "display(HTML('''\n",
    "<p style=\"font-size: smaller\">Data Sources: \n",
    "  <a href=\"https://github.com/CSSEGISandData/COVID-19\">JHU CSSE</a>,\n",
    "  <a href=\"https://data.worldbank.org/indicator/SP.POP.TOTL\">World Bank</a>,\n",
    "  <a href=\"https://worldmap.harvard.edu/data/geonode:country_centroids_az8\">Harvard Worldmap</a>\n",
    "</p>'''))"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Same with log scale\n",
    "sort_order = growth_in_value_df.groupby(\n",
    "    'Country/Region').max().sort_values(\n",
    "    'Confirmed', ascending=False).index.tolist()\n",
    "chart = facetted_growth_plot(increase_df, \n",
    "                             'Confirmed/100k',\n",
    "                             sort_order,\n",
    "                             'Italy',\n",
    "                             \"Growth of cases/100k from case 100, compared to Italy (log scale)\",\n",
    "                             'log')\n",
    "display(chart)\n",
    "display(HTML('''\n",
    "<p style=\"font-size: smaller\">Data Sources: \n",
    "  <a href=\"https://github.com/CSSEGISandData/COVID-19\">JHU CSSE</a>,\n",
    "  <a href=\"https://data.worldbank.org/indicator/SP.POP.TOTL\">World Bank</a>,\n",
    "  <a href=\"https://worldmap.harvard.edu/data/geonode:country_centroids_az8\">Harvard Worldmap</a>\n",
    "</p>'''))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}