python - Seaborn 热图 : Move colorbar on top of the plot

标签 python python-2.7 pandas matplotlib 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()

default heatmap

最佳答案

看着 the documentation我们找到了一个论点 cbar_kws .这允许指定传递给 matplotlib 的 fig.colorbar 的参数方法。

cbar_kws : dict of key, value mappings, optional. Keyword arguments for fig.colorbar.



所以我们可以对 fig.colorbar 使用任何可能的参数。 , 提供字典给 cbar_kws .

在这种情况下,您需要 location="top"将颜色条放在顶部。因为 colorbar默认情况下,使用 gridspec 定位颜色条,然后不允许设置位置,我们需要关闭该 gr​​idspec ( 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()

enter image description here

关于python - Seaborn 热图 : Move colorbar on top of the plot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47916205/

相关文章:

python - 带有身份验证数据的公共(public) FTP 站点的 scrapy,出现 FTP 错误

Python,解析列数据,pandas

python - 将 Pandas 数据框转换为结构化数组

python - 使用最后一组的最后一个值填充组列

python - TCP 通信 Python 上的 ValueError

javascript - 使用 COM + IE 自动化进行 JavaScript 回发后保存文本文件

python - wxPython-Python :Serial port problems

python - WxFormBuilder 没有 Python 选项

python - Bottle + nginx : connect() failed (111: Connection refused) while connecting to upstream

python - 映射不同长度的迭代器