I’m wondering if it is possible to animate a Choroplethmapbox heat map? If tried to stitch together code based on animating scatter plots but substituting Choroplethmapbox in place of Scatter elements.
Here’s what I have written. It never finishes execution. I’m using plotly v4.6.
Thanks for any help!
-Chris
from urllib.request import urlopen
import json
with urlopen('https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json') as response:
counties = json.load(response)
state = "New York"
us_county_df = df[(df["Country/Region"] == "United States") & \
(df["Province/State"] == state) & \
(df.Date > pd.datetime(2020, 3, 21))]
days = np.sort(us_county_df.Date.unique())
fig_frames = []
for day in days:
day_df = us_county_df[us_county_df.Date == days[0]]
fig_frames.append([go.Choroplethmapbox(geojson=counties, locations=day_df.FIPS,
z=day_df.Confirmed, colorscale="Viridis",
marker_opacity=0.5, marker_line_width=0)])
day_df = us_county_df[us_county_df.Date == days[0]]
fig = go.Figure(
data=[go.Choroplethmapbox(geojson=counties, locations=day_df.FIPS,
z=day_df.Confirmed, colorscale="Viridis",
marker_opacity=0.5, marker_line_width=0)],
layout=go.Layout(
mapbox_style="carto-positron",
mapbox_zoom=3,
mapbox_center = {"lat": 37.0902, "lon": -95.7129},
title="Start Title",
updatemenus=[dict(type="buttons",
buttons=[dict(label="Play",
method="animate",
args=[None])])]
),
frames=fig_frames
)
I’ll note that the reference documentation is pretty slim for how to get sliders and buttons to work together. There’s no explanation for why the example code I mentioned actually works and the Python reference documentation for updatemenus, slider and frames leaves a lot unsaid. After much trial and error, here’s my final code.
Are you able to share the ‘us_county_geo.json’? I have applied the code to my problem but when I get to the last step fig.show() I get the following error: "TypeError: Object of type GeoDataFrame is not JSON serializable. I suspect I need to convert my geopandas dataframe to a simpler json format but knowing how ‘us_county_geo.json’ looks would help
I am not sure if this helps (if not, just ignore): I had been struggling with a similar problem until I understood that Plotly Choropleth expects the GeoJson file with a specific structure. I was using TopoJson and it didn’t work. I learned that I had to use a different Json file that must of type FeatureCollection and contain ids that match ids in the dataframe.
When I used a GeoDataframe (from Geopandas), this hint helped me:
The geojson argument expects a dictionary and you are passing a string. (…) turn your GeoJSON string to a dictionary.