Reputation: 107
I am trying to construct an interactive coronavirus map that can change over time. I have data on cases by country and date. The data type for values in the 'Date' column are datetime64.
However, when I try to plot an interactive map, it seems that the date values are causing an error. How should I fix it?
import numpy as np
import pandas as pd
import plotly as py
import datetime
import plotly.express as px
import plotly.graph_objs as go
from plotly.subplots import make_subplots
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
init_notebook_mode(connected = True)
df = pd.read_csv(r'C:\Users\Public\Documents\covid_19_data.csv')
df = df.rename(columns = {'Country/Region' : 'Country'})
df = df.rename(columns = {'ObservationDate' : 'Date'})
df['Date'] = pd.to_datetime(df['Date'])
df.info()
df_datecountry = df.groupby(['Date', 'Country']).sum().reset_index().sort_values('Date', ascending = True)
fig = px.choropleth(df_datecountry,
locations = 'Country',
locationmode = 'country names',
color = 'Confirmed',
hover_name = 'Country',
animation_frame = 'Date')
error:
KeyError Traceback (most recent call last)
<ipython-input-12-69e836d40d17> in <module>
----> 1 fig = px.choropleth(df_datecountry,
2 locations = 'Country',
3 locationmode = 'country names',
4 color = 'Confirmed',
5 hover_name = 'Country',
~\anaconda3\lib\site-packages\plotly\express\_chart_types.py in choropleth(data_frame, lat, lon, locations, locationmode, geojson, featureidkey, color, facet_row, facet_col, facet_col_wrap, facet_row_spacing, facet_col_spacing, hover_name, hover_data, custom_data, animation_frame, animation_group, category_orders, labels, color_discrete_sequence, color_discrete_map, color_continuous_scale, range_color, color_continuous_midpoint, projection, scope, center, fitbounds, basemap_visible, title, template, width, height)
1071 colored region mark on a map.
1072 """
-> 1073 return make_figure(
1074 args=locals(),
1075 constructor=go.Choropleth,
~\anaconda3\lib\site-packages\plotly\express\_core.py in make_figure(args, constructor, trace_patch, layout_patch)
2021 val = group_name[i]
2022 try:
-> 2023 m.updater(trace, m.val_map[val]) # covers most cases
2024 except ValueError:
2025 # this catches some odd cases like marginals
KeyError: Timestamp('2020-01-22 00:00:00')
Ideas? Thanks
Upvotes: 2
Views: 4625
Reputation: 31236
import plotly.express as px
import pandas as pd
import io
import requests
# get OWID data
df = pd.read_csv(io.StringIO(
requests.get("https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/owid-covid-data.csv").text))
# used for filtering
dt = pd.to_datetime(df["date"])
# last 30 days and exclude regional aggregations
fig = px.choropleth(df.loc[dt.ge(dt.max()-pd.Timedelta(days=30))].dropna(subset=["continent"]),
locations = 'location',
locationmode = 'country names',
color = 'new_deaths',
hover_name = 'location',
animation_frame = 'date')
fig.update_layout(margin={"t":0,"b":0,"l":0,"r":0})
Upvotes: 2