使用 Python 的等值线图

Choropleth Map Using Python

我使用 python 创建了一个分区统计图,它根据纬度和经度显示每个州的确诊病例。但是,我无法从我的数据集中输入我想要的数据。

这是我试过的代码:

import plotly.graph_objects as go
import pandas as pd

df = pd.read_csv("COVID19-DATA-01-ONLYSTATES.csv")

fig = go.Figure(data=go.Choropleth(
    locations = df["AdminRegion1"],
    z = df["Confirmed"],
    locationmode = 'USA-states', # set of locations match entries in `locations`
    colorscale = 'Reds',

))

fig.update_layout(
    geo_scope='usa', 
)

fig.show()

这是我的数据集的图片。

如所提供的数据所示,此代码适用于所有国家/地区,而且您也没有提及。 如果您想要特定国家/地区,请在数据框中添加 STATE_CODE。(现在,缺少 STATE_CODE)check

在将原始数据绘制成地图之前,您需要进行一些数据预处理。

数据预处理:

import pandas as pd
import plotly.graph_objs as go

df = pd.read_csv("Bing-COVID19-Data.csv")

selected_columns = ["ID", "Country_Region", "ISO3", "Updated", "Confirmed", "Deaths", "Recovered"] # select columns for plot
sdf = df[selected_columns] 
sdf = sdf[sdf.ISO3.notnull()] # remove null from ISO3, like worldwide wont have any ISO code etc
sdf["Updated"] = pd.to_datetime(sdf.Updated) # Convert Updated column type from str to datetime

sdf = (sdf
       .loc[sdf.groupby('ISO3').Updated.idxmax()] # select only latest date for each contry as you have cumalative sum  
       .reset_index(drop=True)
       .sort_values(["Country_Region"])
      )

剧情:

sdf = sdf.astype(str) # convert columns type to styr to make hover data in plot

sdf["hover_data"] = sdf['Country_Region'] + '<br>' + \
    'Updated: ' + sdf['Updated'] + '<br>' + \
    'Confirmed: ' + sdf['Confirmed'] + '<br>' + \
    'Deaths: ' + sdf['Deaths'] + '<br>' + 'Recovered: ' + sdf['Recovered']

fig = go.Figure(data=go.Choropleth(
    locations = sdf['ISO3'],
    z = sdf['Confirmed'],
    text = sdf['hover_data'],
    colorscale = 'Reds',
    autocolorscale=False,
    marker_line_color='darkgray',
    marker_line_width=0.5,
    colorbar_title = 'Confirmed Cases',
))

fig.update_layout(
    title_text='COVID-19 Cases',
    geo=dict(
        showframe=False,
        showcoastlines=False    )
)

fig.show()