首页 > 解决方案 > 基于具有国家计数值的数据框的彩色地图

问题描述

我有一个名为 country 的数据框,其中包含国家/地区的 country_code 和频率计数。

国家代码 频率
0 我们 17600
1 中国 8572
2 韩国 1121
3 J.P 299
4 199

我写了一个代码来绘制世界地图上的国家分布:

import plotly.express as px

np.random.seed(12)
gapminder = country
gapminder['counts'] = np.random.uniform(low=100000, high=200000, size=len(gapminder)).tolist()

fig = px.choropleth(gapminder, locations="country_code",
                    color="frequency", 
                    hover_name="country_code",
                    color_continuous_scale=px.colors.sequential.Blues)

fig.show()

我得到的结果:

输出数据

代码有问题,我找不到地图上根本没有显示分布的原因。你能帮我纠正一下吗?谢谢!

标签: pythonplotly

解决方案


plotly 中的 choroplethmap 需要指定以哪种格式表示国家名称数据。

locationmode: str 'ISO-3'、'USA-states' 或 'country names' 中的一个 确定用于将条目匹配locations到地图上的区域的一组位置。

国名栏是两个字母的缩写,所以需要转换成三个字母的缩写。我不得不手动更正它,因为我有少量数据。

import pandas as pd
import numpy as np
import io

data = '''
 country_code frequency
0 USA 17600
1 CHN 8572
2 KOR 1121
3 JPN 299
4 DNK 199
'''

country = pd.read_csv(io.StringIO(data), delim_whitespace=True)

import plotly.express as px

np.random.seed(12)
gapminder = country
gapminder['counts'] = np.random.uniform(low=100000, high=200000, size=len(gapminder)).tolist()

fig = px.choropleth(gapminder, locations="country_code",
                    locationmode='ISO-3',
                    color="frequency", 
                    hover_name="country_code",
                    color_continuous_scale=px.colors.sequential.Blues)

fig.show()

在此处输入图像描述


推荐阅读