Can choropleth graph of Plotly Express in Python accept colors in CSS format?

Viewed 836

I am making a choropleth graph on Plotly Express in Python to map the Government Respond on COVID-19; particularly in Africa.

The data source can be found here.
It is an Oxford University dataset on Government Respond Tracker.

The example of the data source content (for your convenience):

CountryName|CountryCode|Date     |...|EconomicSupportIndexForDisplay
Algeria    | DZA       |20200101 |...| 0
Algeria    | DZA       |20200102 |...| 0
.........................................
Algeria    | DZA       |20200724 |...| 50
.........................................

In actuality, there are 42 columns with 30,000+ rows; where these rows are updated daily.
However, not all of the countries are equally up to date (source Oxford GitHub page)

In my case, I have already build a database from it in PostgreSQL.
This is my code so far;

import psycopg2
import pandas as pd
import plotly.express as px

''' PostgreSQL Variables '''
# PostgreSQL Login Variables (edited out)

''' PostgreSQL Connection '''
# PostgreSQL DB Connection code (edited out)

African_Query = pd.read_sql_query(
'''
# SQL Query to pull all African countries from the DB (e.g. 'Algeria, 'Angola', 'Benin', 'etc')
''', conn)
# except ('Comoros', 'Equatorial Guinea', 'Guinea Bissau', and 'Sao Tome and Principe')
# those countries were not exist in the datasource

African = pd.DataFrame(African_Query,
                       columns=['all column names from the datasource'])

''' Plotly graph '''
# Government Respond - School Closing
african_figure1 = px.choropleth(African,
                                locations="countrycode",
                                color="c1_school_closing",
                                color_continuous_scale="Blues",
                                range_color=[0, 3],
                                hover_data={"c1_school_closing": False,
                                            "countrycode": False,
                                            "countryname": False},
                                hover_name="countryname",
                                labels={"c1_school_closing": "SCALE"})

african_figure1.update_layout(geo_scope='africa',
                              title_text="Government Respond - SCHOOL CLOSING")

african_figure1.show()

The map is successfully created. Now I wanted to do the following things;

  • I wanted to change the color that I used. From initially using the in-built color picker in Plotly to one of the CSS style color. For instance into the (#4c5c73)

*edit: I have been trying to modify the value in the 'color_continuous_scale="some_color_value"', to no avail. Or was I wrong to edit this?

Many thanks for your time!

2 Answers

Changed to CSS color format based on the official reference. All you have to do is specify the colors you want to use in list format.

from urllib.request import urlopen
import json
with urlopen('https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json') as response:
    counties = json.load(response)

import pandas as pd
df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/fips-unemp-16.csv",
                   dtype={"fips": str})

import plotly.express as px

fig = px.choropleth_mapbox(df, geojson=counties, locations='fips', color='unemp',
                           color_continuous_scale=["#dc143c", "#ffd700", "#4169e1"],
                           range_color=(0, 12),
                           mapbox_style="carto-positron",
                           zoom=3, center = {"lat": 37.0902, "lon": -95.7129},
                           opacity=0.5,
                           labels={'unemp':'unemployment rate'}
                          )
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
fig.show()

enter image description here

To anyone bumping on this question,

I figured out the fix; thanks to the clue given by @r-beginners. This is what I want;

my_color_scale = [[0.0, '#4c5c73'], [0.1, '#445267'], [0.2, '#3C495C'], [0.3, '#354050'], 
                 [0.4, '#2D3745'], [0.5, '#262D39'], [0.6, '#1E242E'], [0.7, '#161B22'], 
                 [0.8, '#0F1217'], [0.9, '#07090B'], [1.0, '#000000']]

I wanted my list of colour with shades/tints and that is essentially what you need to add in your code.
The 0.0, 0.1, ...., 1.0 next to the Hex Code is used to index your colour and its shades, so later Plotly can use it.

If you use the standard choropleth (the other one is choropleth_mapbox) in plotly.express, this is how you define it. Then just type the variable with the hex codes of your color into the color_continouos_scale; e.g. color_continuous_scale=my_color_scale.


I found it after re-reading the documentation and asking others in different space about this.

Many thanks for your time!

Edit 1: Useful website for Hex Codes: https://color-hex.org/

Edit 2: Full code

import psycopg2
import pandas as pd
import plotly.express as px

''' PostgreSQL Variables '''
# your postgres login variables

''' PostgreSQL Connection '''
# your postgres connection code

''' SQL Query '''
# your SQL Query 

''' Load SQL Queries into Pandas DataFrame '''
African = pd.DataFrame(SQL_Query_Code,
                       columns=['list-of-all-columns'])

''' Variable for Personal Colours '''
# e.g. HTML/HEx code : '#4c5c73'
# List all of the shades/tints codes; in this example I am using the tints codes
my_color_scale = [[0.0, '#4c5c73'], [0.1, '#5D6C81'], [0.2, '#6F7C8F'], [0.3, '#818C9D'], [0.4, '#939DAB'],
                  [0.5, '#A5ADB9'], [0.6, '#B7BDC7'], [0.7, '#C9CED5'], [0.8, '#DBDEE3'], [0.9, '#EDEEF1'],
                  [1.0, '#FFFFFF']]

''' Plotly graph '''
# Government Respond - School Closing
african_figure1 = px.choropleth(African,
                                locations='countrycode',
                                color='c1_school_closing',
                                color_continuous_scale=my_color_scale,
                                range_color=[0, 3],
                                hover_data={'c1_school_closing': False,
                                            'countrycode': False,
                                            'countryname': False},
                                hover_name='countryname',
                                labels={'c1_school_closing': 'SCALE'})

african_figure1.update_layout(geo_scope='africa',
                              coloraxis_reversescale=True, # To reverse the order of color shades/tints
                              title_text='Government Respond - SCHOOL CLOSING <br> '
                                     'Source: <a href="https://www.bsg.ox.ac.uk/research/research-projects'
                                     '/coronavirus-government-response-tracker#data"> Oxford University '
                                     'CORONAVIRUS '
                                     'Government Respond Tracker</a>')

# african_figure1.show()
# african_figure1.write_html('file/path/file_name.html')

The result:

The resulting image Hope this helps.

Related