子图中的seaborn热图的一个颜色条 [英] One colorbar for seaborn heatmaps in subplot
问题描述
以下是显示每个子图的颜色条的示例:
Here is an example that shows a colorbar for each subplot:
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.random((10,10,)))
fig,axn = plt.subplots(2, 2, sharex=True, sharey=True)
for ax in axn.flat:
sns.heatmap(df, ax=ax)
如何删除每个子图的颜色条?我只希望有一个垂直或水平方向的颜色条.我知道我可以通过fig.get_axes()[:-4]
访问每个颜色条轴,但是如何从绘图中将其完全删除呢?我认为在调用热图时,没有选择退出绘制颜色栏的选项.
How can I remove the colorbars for each subplot? I'd like to have only one colorbar that is either vertically or horizontally oriented. I know I have access to each colorbar axes via fig.get_axes()[:-4]
, but how can I remove it from them entirely from the plot? I don't think there is an option to opt out of drawing the colorbar when heatmap is called.
推荐答案
cbar
参数控制是否应添加颜色条,并且cbar_ax
参数可以有选择地指定颜色条应移动的轴.因此,您可以这样做:
The cbar
parameter controls whether a colorbar should be added, and the cbar_ax
parameter can optionally specify the axes where the colorbar should go. So, you could do:
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.random((10,10,)))
fig, axn = plt.subplots(2, 2, sharex=True, sharey=True)
cbar_ax = fig.add_axes([.91, .3, .03, .4])
for i, ax in enumerate(axn.flat):
sns.heatmap(df, ax=ax,
cbar=i == 0,
vmin=0, vmax=1,
cbar_ax=None if i else cbar_ax)
fig.tight_layout(rect=[0, 0, .9, 1])
(您将在此处收到有关tight_layout
的警告,但实际上是正确的,因为我们明确放置了cbar_ax
.如果您不喜欢看到警告,也可以在绘图前调用tight_layout
,但是它不会那么紧).
(You'll get a warning about tight_layout
here, but it actually is correct because we placed cbar_ax
explicitly. If you don't like seeing the warning, you can also call tight_layout
before plotting, but it won't be as tight).
这篇关于子图中的seaborn热图的一个颜色条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!