Create gradient legend matplotlib

Viewed 5485

I'm trying to create a plot that has a legend in the bottom right corner inside the plot

import numpy as np
import matplotlib.pyplot as plt
np.random.seed(23)

df = pd.DataFrame()
df['x'] = np.random.randint(1, 50, 100)
df['y'] = np.random.randint(1, 50, 100)
df['c'] = [1,2,3,4,5] * 20

# 1 is blue 5 is red
fig, ax = plt.subplots(figsize=(7,7))
hexbins = ax.hexbin(df['x'], df['y'], C=df['c'], 
                 bins=20, gridsize=50, cmap=cm.get_cmap('RdYlBu_r'))

# legend
plt.legend(handles=[mpatches.Patch(color='#A70022', label='1'),
                    mpatches.Patch(color='#303297', label='5')], 
                    loc='lower right', edgecolor='black', framealpha=1)

# colorscale
cb = fig.colorbar(hexbins, ax=ax)
cb.set_label('Color Scale')

plot

I can create a custom legend, but I can't figure out how to change the legend to show a cmap gradient. Or I can create a colorbar, but I can't figure out how to place it on the side of the plot and not inside the figure. Is there a way to get a gradient scale inside the legend?

1 Answers

You can use inset_axes to move the colorbar into the Axes. Not exactly a legend object but effectively the same.

from mpl_toolkits.axes_grid1.inset_locator import inset_axes

fig, ax = plt.subplots(figsize=(7,7))
axins1 = inset_axes(ax, width='10%', height='2%', loc='lower right')

hexbins = ax.hexbin(df['x'], df['y'], C=df['c'], 
                 bins=20, gridsize=50, cmap=cm.get_cmap('RdYlBu_r'))
cmin, cmax = hexbins.get_clim()
below = 0.25 * (cmax - cmin) + cmin
above = 0.75 * (cmax - cmin) + cmin

cbar = fig.colorbar(hexbins, cax=axins1, orientation='horizontal', ticks=[below, above])
cbar.ax.set_xticklabels(['25', '75'])
axins1.xaxis.set_ticks_position('top')

enter image description here

Related