我有一个使用seaborn库创建的基本热图,并且想要将颜色栏从默认值(垂直和右侧)移动到热图上方的水平位置.我该怎么办?
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?
以下是一些示例数据和默认示例:
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()推荐答案
查看文档我们找到一个参数cbar_kws.这允许指定传递给matplotlib的fig.colorbar方法的参数.
Looking at the documentation we find an argument cbar_kws. This allows to specify argument passed on to matplotlib's fig.colorbar method.
cbar_kws:键的字典,值映射,可选. fig.colorbar的关键字参数.
cbar_kws : dict of key, value mappings, optional. Keyword arguments for fig.colorbar.
因此,我们可以使用fig.colorbar的任何可能的参数,从而提供cbar_kws的字典.
So we can use any of the possible arguments to fig.colorbar, providing a dictionary to cbar_kws.
在这种情况下,您需要location="top"才能将颜色栏放置在顶部.因为默认情况下colorbar使用gridspec定位颜色栏,然后不允许设置位置,所以我们需要关闭该gridspec(use_gridspec=False).
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).
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 Heatmap:将色条移动到图的顶部
发布评论