【问题标题】:Color map based on dataframe with countries' counts values基于具有国家计数值的数据框的彩色地图
【发布时间】:2021-06-17 22:02:52
【问题描述】:

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

country_code frequency
0 US 17600
1 CN 8572
2 KR 1121
3 JP 299
4 DE 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()

我得到的结果:

Output data

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

【问题讨论】:

    标签: python plotly


    【解决方案1】:

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

    定位模式: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()
    

    【讨论】:

    • 如果我的回答对您有帮助,请采纳为正确答案。点击下方三角形下方的复选标记。
    猜你喜欢
    • 2023-03-26
    • 1970-01-01
    • 2018-02-15
    • 2019-04-16
    • 2020-05-03
    • 2019-05-19
    • 2020-08-11
    • 2020-03-04
    • 1970-01-01
    相关资源
    最近更新 更多