bismo
bismo

Reputation: 1439

How to pad a legend in matplotlib

I have the following code that uses GeoPandas to visualize columns on a shape file

cols = ['UrbanPop','Murder','Assault','Rape']

for i in cols:
  fig, ax = plt.subplots(figsize=(12,12))
  
  merged.plot(column=i,
            ax=ax,
            legend=True,
            legend_kwds={'label': i,
                         'orientation': "horizontal"})
  plt.axis("off")

This does exactly what I want, except for the fact that the colorbars are far from their respective shapefile. Is there a a parameter that lets me control this? I figured it might be a pad of some sort but I can't get it to work.

GeoPandas documentation says that legend_kwds() are "Keyword arguments to pass to matplotlib.pyplot.legend() or matplotlib.pyplot.colorbar()" however, upon checking the documentaion for both of those, I still can't seem to figure it out. I've always had trouble with the parameters for these x_kwds parameters, I can't seem to find a list of them in one place. Same for scatter_kws and line_kws in seaborn.

enter image description here

Upvotes: 0

Views: 1548

Answers (1)

steven
steven

Reputation: 2519

What's the version of your geopandas? For 0.8.1, you can simply pass a pad arg in legend_kwds.

import geopandas as gpd
import matplotlib.pyplot as plt

gdf = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))

fig, ax = plt.subplots(figsize=(15, 5))
legend_kwds = dict(orientation='horizontal', label='Murder', pad=-0.5)
gdf.plot(column='gdp_md_est', legend=True, legend_kwds=legend_kwds, ax=ax)

You can check matplotlib doc here

enter image description here

Upvotes: 2

Related Questions