Search code examples
pythonmatplotlibgisshapefilegeopandas

How to return legend data from matplotlib


I created a dataframe from shapefile using geopandas and then plotted using the gdf.plot function. I want the color values assigned to the categories of data in the following format or similar:

{'1':'black(or color hex code)', 
'2':'color/#hexcode'....,
'7':'color/#hexcode'}

The plot is created using the following code:

plot = geodataframe.plot(
               column='map_c',
               categorical=True,
               legend=True,
               ax=ax,
               cmap='Accent_r')

Output of the code

Is it possible to get this metadata from the plot?


Solution

  • This is a workaround I found out using pylab

    from pylab import cm
    from matplotlib.colors import rgb2hex
    
    cmap = cm.get_cmap('Accent_r', 7) #7 categories I had
    plot = geodataframe.plot(
                   column='map_c',
                   categorical=True,
                   legend=True,
                   ax=ax,
                   cmap= cmap)
    hexes = [rgb2hex(cmap(i)) for i in range(cmap.N)]
    

    Refering to this answer: https://stackoverflow.com/a/33597599/15408580