【问题标题】:Color map based on countries' frequency counts基于国家频率计数的彩色地图
【发布时间】:2023-03-26 15:55:01
【问题描述】:

我有带有 Country 列的用户数据集,并且想绘制一张用户在各个国家/地区的分布图。我将数据集转换为字典,其中键是国家/地区名称,值是国家/地区的频率计数。字典是这样的:

'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)

这是我得到的结果:

着色错误;它表明所有国家都在0-20K范围内,这是错误的。有没有办法来解决这个问题?谢谢

【问题讨论】:

    标签: python plotly choropleth


    【解决方案1】:

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

    情节 1:

    在这里,您可以简单地将lifeExp 替换为您的数据,只要您的数据格式正确,一切都应该没问题。在下面的 sn-p 中,我为每个国家/地区创建了随机整数来表示您的 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:

    让我知道这对你有什么影响。

    编辑:建议您的数据:

    如果您有一个包含国家名称和计数的字典,您可以轻松地构建它的数据框并执行左连接来获得:

    情节 2:

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

    代码 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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-04
      相关资源
      最近更新 更多