Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relocating legend from GeoPandas plot

I'm plotting a map with legends using the GeoPandas plotting function. When I plot, my legends appear in the upper right corner of the figure. Here is how it looks like: enter image description here

I wanted to move the legends to the lower part of the graph. I would normally would have done something like this for a normal matplotlib plot:

fig, ax = plt.subplots(1, figsize=(4.5,10))
lima_bank_num.plot(ax=ax, column='quant_cuts', cmap='Blues', alpha=1, legend=True)
ax.legend(loc='lower left')

However, this modification is not taken into account.

like image 327
josecoto Avatar asked Oct 02 '16 12:10

josecoto


People also ask

How do you move the legend on a plot?

To change the position of a legend in Matplotlib, you can use the plt. legend() function. The default location is “best” – which is where Matplotlib automatically finds a location for the legend based on where it avoids covering any data points.

How do I add a legend on Geopandas?

Replace Missing Data Values If you plot your data using the standard geopandas . plot() , geopandas will select colors for your lines. You can add a legend using the legend=True argument however notice that the legend is composed of circles representing each line type rather than a line.

How do you plot Choropleth with Geopandas?

geopandas makes it easy to create Choropleth maps (maps where the color of each shape is based on the value of an associated variable). Simply use the plot command with the column argument set to the column whose values you want used to assign colors.


2 Answers

This could be done using the legend_kwds argument:

df.plot(column='values', legend=True, legend_kwds={'loc': 'lower right'});
like image 129
lincolnfrias Avatar answered Oct 09 '22 06:10

lincolnfrias


You can access the legend defined on the ax instance with ax.get_legend(). You can then update the location of the legend using the method set_bbox_to_anchor. This doesn't provide the same ease of use as the loc keyword when creating a legend from scratch, but does give control over placement. So, for your example, something like:

leg = ax.get_legend()
leg.set_bbox_to_anchor((0., 0., 0.2, 0.2))

A bit of documentation of set_bbox_to_anchor, though I don't find it extraordinarily helpful.

like image 30
jdmcbr Avatar answered Oct 09 '22 05:10

jdmcbr