Skip to content
Advertisement

format/round numerical legend label in GeoPandas

I’m looking for a way to format/round the numerical legend labels in those maps produced by .plot() function in GeoPandas. For example:

JavaScript

This gives me a legend with many decimal places:

enter image description here

I want the legend label to be integers.

Advertisement

Answer

As I recently encountered the same issue, and a solution does not appear to be readily available on Stack Overflow or other sites, I thought I would post the approach I took in case it is useful.

First, a basic plot using the geopandas world map:

JavaScript

world map v1

The method I used relied on the get_texts() method for the matplotlib.legend.Legend object, then iterating over the items in leg.get_texts(), splitting the text element into the lower and upper bounds, and then creating a new string with formatting applied and setting this with the set_text() method.

JavaScript

This is very much a ‘trial and error’ approach, so I wouldn’t be surprised if there were a better way. Still, perhaps this will be helpful.

world map v2

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement