GeoDataFrame Plotting – How to Color Columns with ‘Explore’ Method in Python

colorfoliumgeopandaspython

I'd like to color the cities that belong to one hemisphere or another with the color specified at 'Color' column. All the cities of each hemisphere (each category) have the same value for that column. I'd like the legend to show the same colors too.

I'm not being able of getting it. Could anyone help me?

Note: This is a reproducible example of what I'm dealing with -based on geopandas examples.

import geopandas as gpd

gdf = gpd.read_file(gpd.datasets.get_path('naturalearth_cities'))
gdf['Hemisphere'] = gdf['geometry'].apply(lambda x: 'Norte'if x.y > 0 else 'Sur')
gdf['Color'] = gdf['Hemisphere'].apply(lambda x: '#D94325' if x=='Norte' else '#5CD925')

gdf.explore(column='Hemisferio', color='Color')

enter image description here

Also available at:

https://stackoverflow.com/q/71128054/13151511

Best Answer

Use the cmap argument rather than color - an example using naturalearth lowres dataset

gdf =gpd.read_file(gpd.datasets.get_path("naturalearth_lowres"))
gdf['color'] = gdf.index.map(lambda x : 'red' if x%2 == 0 else 'blue')
gdf.explore(column='color', cmap=['red', 'blue'], legend=True)

enter image description here