将图与热图(可能是对数)配对?

2024-06-19

How to create a pair plot in Python like the following: enter image description here but with heat maps instead of points (or instead of a "hex bin" plot)? Having the possibility of instead displaying logarithmic heat map counts would be an added bonus. (Histograms on the diagonal would be perfectly fine.)

我所说的“热图”是指计数的二维直方图,显示如下西伯恩的 http://seaborn.pydata.org/generated/seaborn.heatmap.html or 维基百科的 https://en.wikipedia.org/wiki/Heat_map热图:

使用 Pandas、seaborn 或 matplotlib 会很棒(也许是plot.ly)。

我尝试了以下简单的变体,但无济于事:

pairplot = sns.PairGrid(data)  # sns = seaborn
pairplot.map_offdiag(sns.kdeplot)  # Off-diagnoal heat map wanted instead!
pairplot.map_diag(plt.hist)  # plt = matplotlib.pyplot

(上面使用了内核密度估计器,我不想要它;也可以使用 Pandas 获得十六进制网格,但我正在寻找“方形”2D 直方图和 Matplotlib 的hist2d()没用)。


答案的关键是 matplotlib 函数plt.hist2d,它使用色标(“热图”)绘制矩形箱内的计数。它的API几乎兼容PairGrid,但不完全是,因为它不知道如何处理color=夸格。通过编写一个薄包装函数可以轻松解决这个问题。另外,如果您希望颜色图以对数方式映射计数,则可以使用 matplotlib 轻松完成LogNorm:

import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
sns.set_style("white")
iris = sns.load_dataset("iris")    

g = sns.PairGrid(iris)
g.map_diag(plt.hist, bins=20)

def pairgrid_heatmap(x, y, **kws):
    cmap = sns.light_palette(kws.pop("color"), as_cmap=True)
    plt.hist2d(x, y, cmap=cmap, cmin=1, **kws)

g.map_offdiag(pairgrid_heatmap, bins=20, norm=LogNorm())
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将图与热图(可能是对数)配对? 的相关文章

随机推荐