【问题标题】:Seaborn heatmap keeps adding color bars in loop over datasets [duplicate]Seaborn热图不断在数据集上循环添加颜色条[重复]
【发布时间】:2022-01-26 01:16:57
【问题描述】:

我正在尝试在各种数据集上循环绘制热图,但是对于每个新的热图,都会添加一个新的颜色条(地图看起来很好,并且没有添加额外的地图)。我可以通过重置循环内的颜色条来使用解决方法,但我更愿意知道发生了什么并有一个更清洁的解决方案。提前感谢您的帮助!

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')

【问题讨论】:

  • 我找到了一个可行的解决方案(不知道这是否是一个好的解决方案,但它似乎完成了工作):添加“plt.figure()”作为第一行循环清除情节

标签: python plot seaborn heatmap


【解决方案1】:

TL;DR 您的plt.figure() 解决方案是正确的,正如here 所建议的那样。

seaborn 建立在 matplotlib 之上,使用图形和轴的概念。创建matplotlib.pyplot 图表的规范方法从使用f, ax = plt.subplots() 实例化图形和轴开始。当您调用坐标轴级别的绘图(例如heatmapseaborn calls matplotlib.pyplot.gca())时,它会获取当前坐标轴。如果它不存在,seaborn 会在后台实例化一个新的。

我猜想在您的循环中,热图相互覆盖,但 seaborn 正在动态调整图形以为每个颜色条留出空间。用plt.figure()(或f, ax = plt.subplots())清除数字就是你想要的。

【讨论】:

  • 非常感谢您的见解,了解那里发生的事情会很有帮助!
猜你喜欢
  • 2020-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-21
  • 2018-05-07
  • 2016-02-20
  • 2021-02-28
  • 2018-06-03
相关资源
最近更新 更多