matplotlib 将热图颜色条移动到图的顶部

j13ufse2  于 12个月前  发布在  其他
关注(0)|答案(3)|浏览(127)

我有一个使用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()

字符串


的数据

f4t66c6m

f4t66c6m1#

查看the documentation,我们发现参数cbar_kws。这允许指定传递给matplotlib的fig.colorbar方法的参数。
cbar_kws:键的dict,值Map,可选。fig.colorbar的关键字参数。
因此,我们可以使用fig.colorbar的任何可能的参数,为cbar_kws提供一个字典。
在本例中,您需要location="top"将颜色条放置在顶部。因为colorbar默认使用gridspec定位颜色条,而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()


的数据

avwztpqn

avwztpqn2#

我想展示一个子图的例子,它允许控制图的大小以保持热图的正方形几何形状。这个例子很短:

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

字符串


的数据

7kqas0il

7kqas0il3#

你必须使用轴分隔符把颜色条放在一个海运图的顶部。查看注解。

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'})这样的Heatmap参数是无用的,因为它把colorbar放在底部位置。

相关问题