基于国家频率统计的彩色地图

2024-10-02 22:35:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个带有国家栏的用户数据集,我想绘制一张用户在各国分布的地图。我将数据集转换成字典,其中键是国家名称,值是国家的频率计数。字典如下所示:

'usa': 139421,
'canada': 21601, 
'united kingdom': 18314,
'germany': 17024,
'spain': 13096,
 [...]

为了在世界地图上绘制分布图,我使用了以下代码:

#Convert to dictionary
counts = users['Country'].value_counts().to_dict()

#Country names
def getList(dict): 
    return [*dict]

countrs = getList(counts)

#Frequency counts
freqs = list(counts.values())

#Plotting
data = dict(
        type = 'choropleth',
        colorscale = 'Viridis',
        reversescale = True,
        locations = countrs,
        locationmode = "country names",
        z = freqs,
        text = users['Country'],
        colorbar = {'title' : 'Number of Users'},
      ) 

layout = dict(title = 'Number of Users per Country',
                geo = dict(showframe = False)
             )

choromap = go.Figure(data = [data],layout = layout)
iplot(choromap,validate=False)

这是我得到的结果: enter image description here

颜色是错误的;它表明所有国家都属于0-20K范围,这是错误的。有办法解决这个问题吗?谢谢


Tags: to数据用户data字典names绘制国家
1条回答
网友
1楼 · 发布于 2024-10-02 22:35:45

如果不能访问完整的数据集,这真的很难回答。我建议从这个例子开始:

绘图1:

enter image description here

在这里,您可以简单地用yout数据替换lifeExp,只要您的数据格式正确,一切都应该正常。在下面的代码片段中,我为每个国家创建了随机整数来表示counts变量。你知道吗

代码:

import plotly.express as px
import numpy as np

np.random.seed(12)
gapminder = px.data.gapminder().query("year==2007")
gapminder['counts'] = np.random.uniform(low=100000, high=200000, size=len(gapminder)).tolist()

fig = px.choropleth(gapminder, locations="iso_alpha",
                    color="counts", 
                    hover_name="country", # column to add to hover information
                    color_continuous_scale=px.colors.sequential.Plasma)

fig.show()

绘图2:

enter image description here

告诉我这对你有什么好处。你知道吗

编辑:对您的数据提出建议:

如果您有一个包含国家名称和计数的字典,您可以轻松地构造它的数据帧,并执行左联接以获得以下结果:

绘图2:

enter image description here

只需确保您的字典值是列表,并且国家名称的拼写和格式正确即可。你知道吗

代码2:

import plotly.express as px
import numpy as np
import pandas as pd

np.random.seed(12)
gapminder = px.data.gapminder().query("year==2007")
#gapminder['counts'] = np.nan

d = {'United States': [139421],
    'Canada': [21601], 
    'United Kingdom': [18314],
    'Germany': [17024],
    'Spain': [13096]}

yourdata = pd.DataFrame(d).T.reset_index()
yourdata.columns=['country', 'count']

df=pd.merge(gapminder, yourdata, how='left', on='country')

fig = px.choropleth(df, locations="iso_alpha",
                    color="count", 
                    hover_name="country", # column to add to hover information
                    color_continuous_scale=px.colors.sequential.Plasma)

fig.show()

相关问题 更多 >