Plotly:如何为离散分类变量设置等值线图颜色?

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


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


慕沐林林
浏览 187回答 1
1回答

繁花如伊

在这种情况下,我宁愿使用plotly.expresswithcolor=df['risk']然后设置color_discrete_map={'High':'red', 'Moderate':'Yellow','Low':'Green'}:阴谋:完整代码:import plotly.express as pximport pandas as pdfig = px.choropleth(locations=df['Country'],&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; locationmode="country names",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; color=df['risk'],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; color_discrete_map={'High':'red',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'Moderate':'Yellow',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'Low':'Green'}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; #scope="usa"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;)fig.show()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python