Search code examples
pythonpandasplotlygeojsonchoropleth

Data visualization: Choropleth map not displaying color


I just get started with data visualization and now I want to create a choropleth map show the number of soccer play in Premiere League.

I use python 3.8.5 and have a dataset in a CSV file. I try to create a choropleth map using plotly. After that, I created a choropleth, but my problem is the map didn't show any color, it only showed the earth form.

The code is here: https://github.com/quockhanhcao/Question

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


country = json.load(open("countries.geojson", "r"))
df = pd.read_csv('forward_country.csv')
country_code_map = {}

#map the code in geojson file of each country in csv file
for feature in country['features']:
    feature['code'] = feature['properties']['ISO_A3']
    country_code_map[feature['properties']['ADMIN']] = feature['code']
df['code'] = df['Country'].apply(lambda x: country_code_map[x])


fig = px.choropleth(df, locations='code', geojson=country, color = 'Number')
fig.show()

Solution

  • We need to link the country abbreviation name to GeoJson's ISO_A3.

    from urllib.request import urlopen
    import json
    import pandas as pd
    import plotly.express as px
    
    with urlopen('https://raw.githubusercontent.com/quockhanhcao/Question/main/countries.geojson') as response:
        country = json.load(response)
    
    # country = json.load(open("./data/countries.geojson", "r"))
    df = pd.read_csv('./data/forward_country.csv')
    country_code_map = {}
    
    #map the code in geojson file of each country in csv file
    for feature in country['features']:
        feature['code'] = feature['properties']['ISO_A3']
        country_code_map[feature['properties']['ADMIN']] = feature['code']
    df['code'] = df['Country'].apply(lambda x: country_code_map[x])
    
    fig = px.choropleth(df, geojson=country,
                        locations='code',
                        featureidkey="properties.ISO_A3",
                        color='Number')
    
    fig.show()
    

    enter image description here