海洋热图中的轮廓线(iso-z)或阈值线 [英] Contour (iso-z) or threshold lines in seaborn heatmap

查看:65
本文介绍了海洋热图中的轮廓线(iso-z)或阈值线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法自动将等高线(iso-z)线添加到具有具体 x 和 y 值的热图中?

请考虑官方的seaborn航班数据集:

导入 seaborn 为 sns航班 = sns.load_dataset(航班")航班=航班.pivot(月"、年"、乘客")sns.heatmap(航班,annot = True,fmt ='d')

我想象阶梯状线条看起来像下面的图所示(lhs),表示阈值(此处为200和400).不需要以任何方式对它们进行插值或平滑处理,尽管如果更容易实现,也可以这样做.

如果水平线进一步使解决方案复杂化,则也可以省略它们(rhs).

到目前为止,我已经尝试过手动添加hlines和vlines,以覆盖kdeplot等,但是没有理想的结果.有人可以暗示我走向正确的方向吗?

解决方案

您可以使用

Is there a way to automatically add contour (iso-z) lines to a heatmap with concrete x and y values?

Please consider the official seaborn flights dataset:

import seaborn as sns
flights = sns.load_dataset("flights")
flights = flights.pivot("month", "year", "passengers")
sns.heatmap(flights, annot=True, fmt='d')

I imagine the step-like lines to look something like shown below (lhs), indicating thresholds (here 200 and 400). They do not need to be interpolated or smoothed in any way, although that would do as well, if easier to realize.

If the horizontal lines complicate the solution further, they too could be omitted (rhs).

So far, I have tried to add hlines and vlines manually, to overlay a kdeplot etc. without the desired result. Could somebody hint me into the right direction?

解决方案

You can use aLineCollection:

import seaborn as sns
import numpy as np
from matplotlib.collections import LineCollection

flights = sns.load_dataset("flights")
flights = flights.pivot("month", "year", "passengers")
ax = sns.heatmap(flights, annot=True, fmt='d')

def add_iso_line(ax, value, color):
    v = flights.gt(value).diff(axis=1).fillna(False).to_numpy()
    h = flights.gt(value).diff(axis=0).fillna(False).to_numpy()
    
    try:
        l = np.argwhere(v.T)    
        vlines = np.array(list(zip(l, np.stack((l[:,0], l[:,1]+1)).T)))
        
        l = np.argwhere(h.T)    
        hlines = np.array(list(zip(l, np.stack((l[:,0]+1, l[:,1])).T)))
        
        lines = np.vstack((vlines, hlines))
        ax.add_collection(LineCollection(lines, lw=3, colors=color ))
    except:
        pass
    
add_iso_line(ax, 200, 'b')
add_iso_line(ax, 400, 'y')

这篇关于海洋热图中的轮廓线(iso-z)或阈值线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆