Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotly: How to set choropleth map color for a discrete categorical variable?

I am trying to plot a world map with all the countries having different risk levels (low, moderate and high). I would like to make each risk level a different color but am not sure how to change the color scheme so that each risk category has a color of my choice.

The df.risk variable currently has low as 1, moderate as 2 and high as 3 so that it is a continuous variable, however I would like to use discrete,


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

My sample df is:

{'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'}}
like image 408
Sanch Avatar asked Aug 28 '20 13:08

Sanch


1 Answers

In this case I would rather use plotly.express with color=df['risk'] and then set color_discrete_map={'High':'red', 'Moderate':'Yellow','Low':'Green'}:

Plot:

enter image description here

Complete code:

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()
like image 60
vestland Avatar answered Nov 15 '22 07:11

vestland