'How to change the font size of the color bar of a GeoPandas choropleth plot

When I try to use the legend_kwds argument to change the font size of my colorbar, I keep getting this error

TypeError: init() got an unexpected keyword argument 'fontsize'

ax = df.plot(figsize=(20,16), alpha=0.8, column='value', legend=True, cmap='OrRd', legend_kwds={'fontsize':20})
    
plt.show()

Does anyone know how I can increase the font size of the colorbar with GeoPandas? I can't seem to find a keyword that works. I'm using GeoPandas 0.8.1 and Matplotlib 3.3.1.



Solution 1:[1]

You can use matplotlib workaround rather than passing all the complicate parameters in a single statement geopandas' plot function does.

import numpy as np
import geopandas as gpd
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable

# for demo purposes, use the builtin data
world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
africa = world[world.continent=='Africa']
maxv, minv = max(africa.pop_est), min(africa.pop_est)

fig, ax = plt.subplots(figsize=(7,6))
divider = make_axes_locatable(ax)

# create `cax` for the colorbar
cax = divider.append_axes("right", size="5%", pad=0.1)

# plot the geodataframe specifying the axes `ax` and `cax` 
africa.plot(column="pop_est", cmap='magma', legend=True, \
            vmin=minv, vmax=maxv, ax=ax, cax=cax)

# manipulate the colorbar `cax`
cax.set_ylabel('pop_est', rotation=90)
# set `fontsize` on the colorbar `cax`
cax.set_yticklabels(np.linspace(minv, maxv, 10, dtype=np.dtype(np.uint64)), {'fontsize': 8})

plt.show()

The output plot:

africa

Solution 2:[2]

I encountered the same problem, and I found that the answer does not work correctly - the labels on the legend are actually wrong.

So using the same idea, you can call

cax.tick_params(labelsize='20')

this will keep the default ticks that the plot creates, but you can change the details.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 swatchai
Solution 2 Olevam