Search code examples
pythonpandasplotly

Plotly choropleth shows color for US and not other countries


I've a pandas dataframe as following :
dataframe

column employee_residence contains an ISO 3166 country code for each unique country .

I want to plot a Choropleth map for the above dataframe which highlights the mean_salary as per the country on the map.

So I did the following :

fig = px.choropleth(
    data_frame=salary_location_df,
    locations="employee_residence",
    locationmode="country names",
    color="mean_salary",
    hover_data=["mean_salary", "count_jobs"],
    title="country wise salaries",
)
fig.show()

but in the output I am only able to see US residence colored and not others plotly chorolepth output

So I thought there might be something wrong with the country codes due to which only US is showing up thus I tried validating those country codes using ISO standard library located here: https://pypi.python.org/pypi/iso3166/

validating country codes

but seems like all the country codes are valid

So what can be done in order to resolve this problem ? Thank you


Solution

  • update: Now that the data has been published, I used that data to recreate the graph. Since the original data is the ISO3166-2 format country abbreviation, install the library to get the ISO-3166-3 format country abbreviation. Add it to the original data frame and draw a graph.

    import pandas as pd
    import numpy as np
    import plotly.express as px 
    
    df = pd.read_csv("/content/ds_salaries.csv", index_col=0)
    
    salary_location_df = df.groupby("employee_residence").agg(
        mean_salary=('salary_in_usd', 'mean'), count_jobs=('employee_residence', 'count')
    ).reset_index()
    
    from iso3166 import countries
    
    country_names =[]
    for country in salary_location_df['employee_residence']:
        #print(country)
        c_name = countries.get(country)
        country_names.append(c_name[2])
    
    salary_location_df['iso_alpha'] = country_names
    
    fig = px.choropleth(salary_location_df, locations="iso_alpha",
                        color="mean_salary", 
                        hover_data=["mean_salary", "count_jobs"],
                        title="country wise salaries",
                        color_continuous_scale=px.colors.sequential.Plasma)
    fig.show()
    

    enter image description here