创建Matplotlib渐变图例

5
我正在尝试创建一个图表,其中图例位于绘图中的右下角。
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

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

1个回答

5
你可以使用inset_axes将色条移动到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')

enter image description here


太好了!我能够使用cbar.set_ticks([1, 5]); cbar.set_ticklabels(['below', 'above'])为图例制作自定义标签,但是有没有办法将刻度值更改为颜色条范围的百分位数?例如,如果我想要“below”和“above”刻度在cbar范围的第25和第75百分位数中呢? - Ethan
我编辑了以添加自定义刻度。colorbar有一个 tick 参数,您可以使用 set_xticklabels 进行标记。 - busybear
我能够设置刻度标签,但我想找到刻度本身的实际值。有没有办法查看色条表示的数字范围,以便我可以动态设置刻度? - Ethan
hexbins.get_clim 返回最小和最大值。 - busybear
感谢您的帮助!@busybear - Ethan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接