[Python] Plotly Choropleth Map: Colors Not Mapping Correctly from Color Dictionary

Discussão em 'Python' iniciado por Stack, Dezembro 7, 2024.

  1. Stack

    Stack Membro Participativo

    I am trying to create a choropleth map using Plotly with a custom color dictionary, where specific states should be colored red and green. However, when trying to apply these colors, the chart is showing unexpected colors (such as pink and light blue) instead of the colors I defined in the dictionary.

    The goal is to ensure that the states defined in the dictionary are colored red or green, while states not in the dictionary should be colored gray.

    Code:

    import geopandas as gpd
    import plotly.express as px

    # Path to the shapefile of Brazilian states
    shapefile_path = 'brasil_estados.json'

    # Load the shapefile using geopandas
    brasil_mapa = gpd.read_file(shapefile_path, encoding='utf-8')

    # Custom color dictionary (red and green)
    color_dict = {
    'Minas Gerais': 'green',
    'Tocantins': 'red',
    'Amapá': 'red',
    'Roraima': 'red',
    'Goiás': 'red',
    'Distrito Federal': 'red'
    }

    # Map colors according to the dictionary
    # If the state is not in the dictionary, it will be colored 'gray'
    brasil_mapa['color'] = brasil_mapa['name'].map(color_dict).fillna('gray')

    # Plot the map using Plotly
    fig = px.choropleth(
    brasil_mapa,
    geojson=brasil_mapa.geometry.__geo_interface__, # Using geometry directly
    locations=brasil_mapa.index,
    color='color', # Color of the states based on the dictionary
    color_discrete_map=color_dict, # Explicit color dictionary
    labels={'color': 'State'},
    scope='south america',
    title='Map of Brazilian States with Custom Colors',
    width=1200,
    height=800
    )

    # Adjusting map visualization
    fig.update_geos(fitbounds="locations", visible=False)

    # Show the plot
    fig.show()



    [​IMG]

    Continue reading...

Compartilhe esta Página