簡體   English   中英

Seaborn Heatmap:在繪圖頂部移動顏色條

[英]Seaborn Heatmap: Move colorbar on top of the plot

我有一個使用seaborn庫創建的基本熱圖,並希望將seaborn從默認,垂直和右側移動到熱圖上方的水平條。 我怎樣才能做到這一點?

這是一些示例數據和默認示例:

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np

# Create data
df = pd.DataFrame(np.random.random((5,5)), columns=["a","b","c","d","e"])

# Default heatma
ax = sns.heatmap(df)
plt.show()

默認熱圖

查看文檔,我們找到了一個參數cbar_kws 這允許指定傳遞給matplotlib的fig.colorbar方法的參數。

cbar_kws :鍵,值映射的dict,可選。 fig.colorbar關鍵字參數。

因此,我們可以使用任何可能的參數fig.colorbar ,提供字典cbar_kws

在這種情況下,您需要location="top"將顏色條放在頂部。 因為colorbar默認使用gridspec定位顏色條,然后不允許設置位置,我們需要關閉gridspec( use_gridspec=False )。

sns.heatmap(df, cbar_kws = dict(use_gridspec=False,location="top"))

完整的例子:

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.random((5,5)), columns=["a","b","c","d","e"])

ax = sns.heatmap(df, cbar_kws = dict(use_gridspec=False,location="top"))

plt.show()

在此輸入圖像描述

你必須使用軸分隔器將顏色條放在一個seaborn圖上。 尋找評論。

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable
from mpl_toolkits.axes_grid1.colorbar import colorbar

# Create data
df = pd.DataFrame(np.random.random((5,5)), columns=["a","b","c","d","e"])

# Use axes divider to put cbar on top
# plot heatmap without colorbar
ax = sns.heatmap(df, cbar = False)
# split axes of heatmap to put colorbar
ax_divider = make_axes_locatable(ax)
# define size and padding of axes for colorbar
cax = ax_divider.append_axes('top', size = '5%', pad = '2%')
# make colorbar for heatmap. 
# Heatmap returns an axes obj but you need to get a mappable obj (get_children)
colorbar(ax.get_children()[0], cax = cax, orientation = 'horizontal')
# locate colorbar ticks
cax.xaxis.set_ticks_position('top')

plt.show()

在此輸入圖像描述

欲了解更多信息,請閱讀matplotlib的官方示例: https ://matplotlib.org/gallery/axes_grid1/demo_colorbar_with_axes_divider.html highlight = demo%20colorbar%20axes%20divider

sns.heatmap(df, cbar_kws = {'orientation':'horizontal'})類的熱圖參數是無用的,因為它將顏色條放在底部位置。

我想展示子圖的示例,它允許控制圖的大小以保留熱圖的方形幾何。 這個例子非常簡短:

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np

# Create data
df = pd.DataFrame(np.random.random((5,5)), columns=["a","b","c","d","e"])

# Define two rows for subplots
fig, (cax, ax) = plt.subplots(nrows=2, figsize=(5,5.025),  gridspec_kw={"height_ratios":[0.025, 1]})

# Draw heatmap
sns.heatmap(df, ax=ax, cbar=False)

# colorbar
fig.colorbar(ax.get_children()[0], cax=cax, orientation="horizontal")

plt.show()

在此輸入圖像描述

暫無
暫無

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

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