簡體   English   中英

創建漸變圖例 matplotlib

[英]Create gradient legend matplotlib

我正在嘗試創建一個 plot 在 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')

陰謀

我可以創建一個自定義圖例,但我不知道如何更改圖例以顯示 cmap 漸變。 或者我可以創建一個顏色條,但我不知道如何將它放置在 plot 的側面而不是圖中。 有沒有辦法在圖例中獲得漸變比例?

您可以使用inset_axes將顏色條移動到軸中。 不完全是傳說 object 但實際上相同。

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')

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM