数据结构如下。
我们用第一个csv文件。列信息如下。
导入依赖。
import numpy as np import pandas as pd import plotly.graph_objs as go import plotly.io as pio pio.renderers.default = "browser"
# Read Data
df = pd.read_csv("dataset/covid_19_data.csv")
# Rename columns
df = df.rename(columns={'Country/Region': 'Country'})
df = df.rename(columns={'ObservationDate': 'Date'})
# Manipulate Dataframe
df_countries = df.groupby(['Country', 'Date']).sum().reset_index().sort_values('Date', ascending=False)
print(df_countries)
df_countries = df_countries.drop_duplicates(subset=['Country'])
df_countries = df_countries[df_countries['Confirmed'] > 0]
# Create the Choropleth
fig = go.Figure(data=go.Choropleth(
locations=df_countries['Country'],
locationmode='country names',
z=df_countries['Confirmed'],
colorscale='reds',
marker_line_color='black',
marker_line_width=0.5,
))
fig.update_layout(
title_text='Confirmed Cases as of 2021/5/3',
title_x=0.5,
geo=dict(
showframe=False,
showcoastlines=False,
projection_type='equirectangular'
)
)
fig.show()
第一部分先读取数据
# Read Data
df = pd.read_csv("dataset/covid_19_data.csv")
为列改名,便于操作
df = df.rename(columns={'Country/Region': 'Country'})
df = df.rename(columns={'ObservationDate': 'Date'})
重排数据并清洗
df_countries = df.groupby(['Country', 'Date']).sum().reset_index().sort_values('Date', ascending=False)
print(df_countries)
df_countries = df_countries.drop_duplicates(subset=['Country'])
df_countries = df_countries[df_countries['Confirmed'] > 0]
# Create the Choropleth
画图
fig = go.Figure(data=go.Choropleth(
locations=df_countries['Country'],
locationmode='country names',
z=df_countries['Confirmed'],
colorscale='reds',
marker_line_color='black',
marker_line_width=0.5,
))
fig.update_layout(
title_text='Confirmed Cases as of 2021/5/3',
title_x=0.5,
geo=dict(
showframe=False,
showcoastlines=False,
projection_type='equirectangular'
)
)
fig.show()
上面的是静态图,没有交互动能。但是相对的,渲染、画图的速度都会变快,同时保存下来的数据占用也小了。
导入依赖
import numpy as np import plotly.express as px import pandas as pd import plotly.graph_objs as go import plotly.io as pio
读数据、改列名
pio.renderers.default = "browser"
df = pd.read_csv("dataset/covid_19_data.csv")
df = df.rename(columns={'Country/Region': 'Country'})
df = df.rename(columns={'ObservationDate': 'Date'})
清洗
# Manipulating the original dataframe
df_countrydate = df[df['Confirmed'] > 0]
df_countrydate['Date'] = pd.to_datetime(df_countrydate['Date']).apply(lambda x: x.strftime('%Y-%m-%d'))
df_countrydate = df_countrydate.groupby(['Country', 'Date']).sum().reset_index().sort_values('Date', ascending=True)
print(df_countrydate)
画图
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()
上述是使用python生成展示为html形式的图。
此外,还可以使用前端绘图,例如Echarts。
1 2 3 4 5 6疫情地图展示 7 20 21 22 23 24 25 26 27 28 2930 累计确诊人数如下: 31 32 3334 35 36 155 156



