循环 seaborn 热图时如何避免多个颜色条

How to avoid multiple colorbars when looping seaborn heatmap

我使用以下代码在 for 循环中绘制了 3 个图。但是我创建的第一个图形有 3 个颜色条,第二个有 2 个,第一个有 1 个。所以看起来上一个图在当前图上添加了一个颜色条。我怎样才能避免这种情况?

for f in files:
    #print(f)
    roi_signals = pd.read_csv(f, sep='\t')
   
    fig = sns.heatmap(roi_signals)
    fig_name = f.replace('.txt', '.png')
    plt.savefig(fig_name)

我刚刚用这个修复了它:

import matlabplot.pyplot as plt
import seaborn as sns
import pandas as pd

for f in files:
    #print(f)
    roi_signals = pd.read_csv(f, sep='\t')

    fig, ax = plt.subplots()
    ax = sns.heatmap(roi_signals)
    fig_name = f.replace('.txt', '.png')
    plt.savefig(fig_name)

默认情况下,sns.heatmap 绘制到现有轴上并为颜色条分配 space:

This will draw the heatmap into the currently-active Axes if none is provided to the ax argument. Part of this Axes space will be taken and used to plot a colormap, unless cbar is False or a separate Axes is provided to cbar_ax.


最简单的解决方案是使用 plt.clf:

每次迭代清除图形
for f in files:
    roi_signals = pd.read_csv(f, sep='\t')

    sns.heatmap(roi_signals)
    plt.savefig(f.replace('.txt', '.png')
    plt.clf() # clear figure before next iteration

或指定cbar_ax覆盖之前迭代的颜色条:

fig = plt.figure()
for i, f in enumerate(files):
    roi_signals = pd.read_csv(f, sep='\t')

    cbar_ax = fig.axes[-1] if i else None # retrieve previous cbar_ax (if exists)
    sns.heatmap(roi_signals, cbar_ax=cbar_ax)
    plt.savefig(f.replace('.txt', '.png')

或者每次迭代只创建一个新图形,但不建议多次迭代时这样做:

for f in files:
    roi_signals = pd.read_csv(f, sep='\t')

    fig = plt.figure() # create new figure each iteration
    sns.heatmap(roi_signals)
    plt.savefig(f.replace('.txt', '.png')