创建渐变图例 matplotlib

Eth*_*han 5 python matplotlib legend

我正在尝试创建一个图,该图的右下角有一个图例

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')
Run Code Online (Sandbox Code Playgroud)

阴谋

我可以创建自定义图例,但我不知道如何更改图例以显示 cmap 渐变。或者我可以创建一个颜色条,但我不知道如何将其放置在图的一侧而不是图的内部。有没有办法在图例中获得渐变比例?

bus*_*ear 5

您可以使用inset_axes将颜色条移动到轴中。不完全是图例对象,但实际上是相同的。

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')
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述