TrueCactus
TrueCactus

Reputation: 131

How to use and block a specific color for a location in plotly chloropeth map (python)

I'm trying to set a map of European country with their result in Eurovision. I have a button to choose the different countries ( Italy, France, Portugal, UK , etc ...)

For Example, if I choose to see the Result of Sweden, I want to see on the map the numbers of points given by the others according to a color scale. I success to do it !

But I want to visualize Sweden, for example in black on the map, to better see where it is, and the "neighborhood effect of notation" .

fig3 = go.Figure(data=go.Choropleth(
    locations=Euro_tr['Country_code'], # Spatial coordinates
    z = Euro_tr['Italy'], # Data to be color-coded
    locationmode = "ISO-3",
    colorbar_title = "Points donnés",
    text=Euro_tr['Country'],
   ))


fig3.update_layout(
    title_text = 'Score Eurovision',
    margin={"r":55,"t":55,"l":55,"b":55},
    height=500,
    geo_scope="europe" ,
 
    
)

#Make a button for each country
button=[]
for country in Euro_tr.columns[1:-1] :
    dico=dict (
                    label=country,
                    method="update",
                    args = [{'z': [ Euro_tr[country] ] }],)
    button.append(dico)

fig3.update_layout(
     updatemenus=[
        dict(
            buttons=button,
            
            
            
         y=0.9,
         x=0,
         xanchor='right',
         yanchor='top',
         active=0,
    ),
        ])

As you see in this example showing the points given to Sweden, I want Sweden to be in a specific color, independently to others countries, the ones that have given points and the ones that have given no points.

Example map with click on button "Sweden"

Thanks for your help !

Upvotes: 2

Views: 1339

Answers (2)

TrueCactus
TrueCactus

Reputation: 131

I followed the answers from @vestland, and I succeed to put my country of interest in one color , independently to others by using fig.add_traces(go.Choropleth)

To have the possibility to change the data and the trace according to my country of interest, I use streamlit and buttons.

import streamlit as st
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go 

# Creation of graphes for each country 
Graphes=[]
for country in Euro_tr.columns[1:-1] : #To pass each country 

    Graphe=go.Figure(data=go.Choropleth(
    locations=Euro_tr['Country_code'], # Spatial coordinates
    z = Euro_tr[country], # Data to be color-coded
    locationmode = "ISO-3",
    colorbar_title = "Points donnés",
    autocolorscale= False,
    colorscale="viridis",
    text=Euro_tr['Country'],
   ))
    
    # customisation : title according to the country and its points
    Graphe.update_layout(
    title_text = "Total :Points donnés à {fcountry} qui a remporté {fpoints} points".format(fcountry = country, fpoints = Eurovision_tot['Result_tot'][Eurovision_tot["Country"]==country].values[0]),
    margin={"r":55,"t":55,"l":55,"b":55},
    height=500,
    )
 )
    # block a specific zoom on the map ( scope "europe" isn't complete for eurovision countries xD!)
    Graphe.update_geos(
    center=dict(lon= 23, lat= 54),
    lataxis_range=[31.0529,-40.4296], lonaxis_range=[-24, 88.2421],
    projection_scale=3
    )
    
    # add trace for the specific country.
    Graphe.add_traces(go.Choropleth(locations=Country_df['Country_code'][Country_df["Country"]==country],
                            z = [1],
                            colorscale = [[0, col_swe],[1, col_swe]],
                            colorbar=None,
                            showscale = False))
    
    Graphes.append(Graphe)

#creation selectbox to select country
col12, col22 = st.beta_columns([0.2,0.8])   # I use columns to put the selector on a  side and the graph on other side 
Pays=list(Euro_tr.columns[1:-1]) # List containing country's name
Selection_Pays = col12.selectbox('',(Pays)) #create a multiple selector with the different countries as possible choice


# define action according to the selection.
for country in Pays :
        if Selection_Pays== country : #if country is selected
            col22.plotly_chart(Graphes[Pays.index(country)]) # plot the corresponding map.

enter image description here

Upvotes: 3

vestland
vestland

Reputation: 61204

Even though you've built your choropleth map using px.express you can always add a trace using plotly.graph_objects with fig.add_traces(go.Choropleth) such as this:

col_swe = 'Black'
fig.add_traces(go.Choropleth(locations=df_swe['iso_alpha'],
                            z = [1],
                            colorscale = [[0, col_swe],[1, col_swe]],
                            colorbar=None,
                            showscale = False)
              )

To my knowledge it's not possible to define a single color for a single country directly, and thats why I've assigned z=[1] as a value, and a custom scale colorscale = [[0, col_swe],[1, col_swe]] to make sure that Sweden always is illustrated in 'Black'.

enter image description here

Code:

import plotly.express as px
import plotly.graph_objects as go

df = px.data.gapminder().query("year==2007")
fig = px.choropleth(df, locations="iso_alpha",
                    color="lifeExp", # lifeExp is a column of gapminder
                    hover_name="country", # column to add to hover information
                    color_continuous_scale=px.colors.sequential.Plasma)

df_swe = df[df['country']=='Sweden']
col_swe = 'Black'

fig.add_traces(go.Choropleth(locations=df_swe['iso_alpha'],
                            z = [1],
                            colorscale = [[0, col_swe],[1, col_swe]],
                            colorbar=None,
                            showscale = False)
              )

f = fig.full_figure_for_development(warn=False)

fig.show()

Upvotes: 2

Related Questions