3

I'm trying to plot heatmaps in a loop over various datasets but with every new heatmap, a new color bar gets added (the map looks fine and no extra maps are added). I could use a workaround by resetting the color bar inside the loop but I would prefer to know what is going on and have a cleaner solution. Thanks in advance for any help!

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns; 

# read file
atlas = ['A','B','C','D']
output_path = '/Users/polo/Desktop/Heatmaps/'

for at in range(len(atlas)):
    data = pd.read_csv('/Users/polo/Desktop/correl_input_{}.csv'.format(atlas[at]))
    hmap = sns.heatmap(data,cmap='seismic',linewidths=.5,vmin=-0.1, vmax=0.1)
    hmap.set_ylim(0, 5)
    plt.savefig(output_path + 'Heatmap_{}.png'.format(atlas[at]), dpi=1200,bbox_inches='tight')
    #plt.savefig('{}_plot.png', format='png', dpi=1200,bbox_inches='tight')
RBG
  • 69
  • 1
  • 5
  • 1
    I found one solution that works (don't know if this is a good one or not but it seems to get the job done): adding "plt.figure()" as the first line of the loop clears the plot – RBG Dec 26 '21 at 20:14

1 Answers1

1

TL;DR your solution of plt.figure() is the correct one, as suggested here.

Being built on top of matplotlib, seaborn uses the concepts of figures and axes. The canonical way to create a matplotlib.pyplot chart begins with instantiating a figure and axes with f, ax = plt.subplots(). When you call an axes-level plot such as heatmap, seaborn calls matplotlib.pyplot.gca(), which gets the current axes. If it doesn't exist seaborn instantiates a new one under the hood.

I'm guessing that in your loop the heatmaps are covering one another, but seaborn is dynamically adjusting the figure to leave space for each colorbar. Clearing the figure with plt.figure() (or f, ax = plt.subplots()) is what you want.

Josh Friedlander
  • 10,870
  • 5
  • 35
  • 75