我正在尝试通过 JuypterLab 中的 csv 文件制作一个动画 choloropleth 地图,以详细说明冠状病毒的传播。我得到了要输出的地图,但不仅日期错误,而且地图没有动画并且是静态图像。我尝试更改渲染器和一些值,就像在这行代码中一样,但它仍然没有产生正确的结果。
df_countrydate = df_countrydate.groupby(['Country','Date']).sum().reset_index()
我也尝试将 Ascended 值更改为 True,但仍然没有产生正确的结果
import numpy as np
import plotly.graph_objs as go
import plotly.io as pio
import pandas as pd
import plotly.express as px
from plotly.subplots import make_subplots
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
init_notebook_mode(connected=True)
def main():
graph()
def graph():
file = "covid_19_data.csv"
df = pd.read_csv(file)
df = df.rename(columns={'Country/Region': 'Country'})
df = df.rename(columns={'ObservationDate': 'Date'})
pio.renderers.default = "svg"
df_countries = df.groupby(['Country', 'Date']).sum().reset_index().sort_values('Date', ascending=False)
df_countries = df_countries.drop_duplicates(subset=['Country'])
df_countries = df_countries[df_countries['Confirmed'] > 0]
df_countrydate = df[df['Confirmed']>0]
df_countrydate = df_countrydate.groupby(['Date','Country']).sum().reset_index()
df_countrydate
fig = go.Figure(data=go.Choropleth(
locations=df_countries['Country'],
locationmode='country names',
z=df_countries['Confirmed'],
colorscale='Inferno',
))
fig = px.choropleth(df_countrydate,
locations="Country",
locationmode = "country names",
color="Confirmed",
hover_name="Country",
animation_frame="Date"
)
fig.update_layout(
title_text = 'Global Spread of Coronavirus',
title_x = 0.5,
geo=dict(
showframe = False,
showcoastlines = False,
))
fig.show()
main()
答案 0 :(得分:0)
choropleth 地图只能用 px.choropleth() 指定。数据是从 here 获得并重新计算以创建以年为单位的数据。这是因为以天为单位的动画非常缓慢。另外,滑块是一个数字字符串,所以我将其转换为字符串并对其进行了排序。
import plotly.graph_objects as go
import pandas as pd
row_data = pd.read_csv('./data/owid-covid-data.csv', sep=',')
df = row_data.loc[:,['iso_code','continent','location','date','total_cases']]
df['date'] = pd.to_datetime(df['date'])
df.set_index('date', inplace=True)
df = df.groupby(['iso_code','continent','location']).resample('1M')['total_cases'].sum().reset_index()
df['date'] = df['date'].astype(str)
df.sort_values('date', ascending=True, inplace=True)
import plotly.express as px
fig = px.choropleth(df,
locations="iso_code",
color="total_cases",
hover_name="location",
animation_frame="date",
color_continuous_scale='Plasma',
height=600
)
fig.update_layout(
title_text = 'Global Spread of Coronavirus',
title_x = 0.5,
geo=dict(
showframe = False,
showcoastlines = False,
))
fig.show()