【问题标题】:Plotly: How to set choropleth map color for a discrete categorical variable?Plotly:如何为离散分类变量设置等值线图颜色?
【发布时间】:2020-12-17 11:10:38
【问题描述】:

我正在尝试绘制一张世界地图,其中所有国家都具有不同的风险水平(低、中和高)。我想为每个风险级别设置不同的颜色,但不知道如何更改配色方案,以便每个风险类别都有我选择的颜色。

df.risk 变量目前低为 1,中等为 2,高为 3,因此它是一个连续变量,但我想使用离散变量,


fig = go.Figure(data=go.Choropleth(
    locations = df['code'],
    z = df['risk'],
    text = df['COUNTRY'],
    colorscale = 'Rainbow',
    autocolorscale=False,
    reversescale=True,
    marker_line_color='darkgray',
    marker_line_width=0.5,
    colorbar_tickprefix = '',
    colorbar_title = 'Risk level',
))

fig.update_layout(
    title_text='Risk map',
    geo=dict(
        showframe=False,
        showcoastlines=False,
        projection_type='equirectangular'
    ),
    annotations = [dict(
        x=0.55,
        y=0.15,
        xref='paper',
        yref='paper',
        text='Source: <a href="www.google.com">\
            Google</a>',
        showarrow = False
    )]
)

fig.show()

我的样本df是:

{'Country': {0: 'Afghanistan',
  1: 'Albania',
  2: 'Algeria',
  3: 'American Samoa',
  4: 'Andorra'},
 'code': {0: 'AFG', 1: 'ALB', 2: 'DZA', 3: 'ASM', 4: 'AND'},
 'risk': {0: 'High', 1: 'Moderate', 2: 'High', 3: 'Low', 4: 'High'}}

【问题讨论】:

    标签: python mapping plotly gis geopandas


    【解决方案1】:

    在这种情况下,我宁愿将plotly.expresscolor=df['risk'] 一起使用,然后设置color_discrete_map={'High':'red', 'Moderate':'Yellow','Low':'Green'}

    剧情:

    完整代码:

    import plotly.express as px
    import pandas as pd
    
    fig = px.choropleth(locations=df['Country'], 
                        locationmode="country names",
                        color=df['risk'],
                        color_discrete_map={'High':'red',
                                            'Moderate':'Yellow',
                                            'Low':'Green'}
                        #scope="usa"
                       )
    fig.show()
    

    【讨论】:

      猜你喜欢
      • 2021-03-11
      • 2020-12-22
      • 2020-12-04
      • 2020-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-05
      • 2023-03-21
      相关资源
      最近更新 更多