pandas Seaborn 热图:将颜色条移动到图的顶部
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47916205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Seaborn Heatmap: Move colorbar on top of the plot
提问by r3robertson
I have a basic heatmap created using the seaborn
library, and want to move the colorbar from the default, vertical and on the right, to a horizontal one above the heatmap. How can I do this?
我有一个使用该seaborn
库创建的基本热图,并希望将颜色条从默认的、垂直的和右侧的颜色条移动到热图上方的水平颜色条。我怎样才能做到这一点?
Here's some sample data and an example of the default:
以下是一些示例数据和默认示例:
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()
回答by ImportanceOfBeingErnest
Looking at the documentationwe find an argument cbar_kws
. This allows to specify argument passed on to matplotlib's fig.colorbar
method.
查看文档,我们发现了一个论点cbar_kws
。这允许指定传递给 matplotlibfig.colorbar
方法的参数。
cbar_kws
: dict of key, value mappings, optional. Keyword arguments forfig.colorbar
.
cbar_kws
: 键的字典,值映射,可选。的关键字参数fig.colorbar
。
So we can use any of the possible arguments to fig.colorbar
, providing a dictionary to cbar_kws
.
所以我们可以使用任何可能的参数 to fig.colorbar
,提供一个字典 to cbar_kws
。
In this case you need location="top"
to place the colorbar on top. Because colorbar
by default positions the colorbar using a gridspec, which then does not allow for the location to be set, we need to turn that gridspec off (use_gridspec=False
).
在这种情况下,您需要location="top"
将颜色条放在顶部。因为colorbar
默认情况下使用 gridspec 定位颜色条,然后不允许设置位置,我们需要关闭该 gridspec ( use_gridspec=False
)。
sns.heatmap(df, cbar_kws = dict(use_gridspec=False,location="top"))
Complete example:
完整示例:
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()
回答by Serenity
You have to use axes divider to put colorbar on top of a seaborn figure. Look for the comments.
您必须使用轴分隔符将颜色条放在 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()
For more info read this official example of matplotlib: https://matplotlib.org/gallery/axes_grid1/demo_colorbar_with_axes_divider.html?highlight=demo%20colorbar%20axes%20divider
有关更多信息,请阅读 matplotlib 的这个官方示例:https://matplotlib.org/gallery/axes_grid1/demo_colorbar_with_axes_divider.html ?highlight =demo%20colorbar%20axes%20divider
Heatmapargument like sns.heatmap(df, cbar_kws = {'orientation':'horizontal'})
is useless because it put colorbar on bottom position.
热图参数 likesns.heatmap(df, cbar_kws = {'orientation':'horizontal'})
是无用的,因为它将颜色条放在底部位置。
回答by pcu
I would like to show example with subplots which allows to control size of plot to preserve square geometry of heatmap. This example is very short:
我想展示带有子图的示例,它允许控制图的大小以保留热图的方形几何形状。这个例子很短:
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()