使用Seaborn在PairGrid中绘制Hexbin图

4

我正在尝试在Seaborn Grid中获取一个hexbin图。我有以下代码:

# Works in Jupyter with Python 2 Kernel.
%matplotlib inline

import seaborn as sns
import matplotlib as mpl
import matplotlib.pyplot as plt

tips = sns.load_dataset("tips")

# Borrowed from https://dev59.com/p4zda4cB1Zd3GeqPtPXx#31385996
def hexbin(x, y, color, **kwargs):
    cmap = sns.light_palette(color, as_cmap=True)
    plt.hexbin(x, y, gridsize=15, cmap=cmap, extent=[min(x), max(x), min(y), max(y)], **kwargs)

g = sns.PairGrid(tips, hue='sex')
g.map_diag(plt.hist)
g.map_lower(sns.stripplot, jitter=True, alpha=0.5)
g.map_upper(hexbin)

然而,这给我带来了以下的图像, seaborn output

我该如何修复hexbin图表,使其覆盖整个图表表面而不仅是所显示的图表区域的子集?


请不要直接点踩,可以给我一些指导意见,帮助我改进提问质量,谢谢! - Stereo
可能是因为您没有提供一个最小可行示例。 - GWW
代码已更新,谢谢! - Stereo
1个回答

4
你在这里尝试做的事情至少存在三个问题。
  1. stripplot 用于至少有一个轴为分类数据的情况。但这种情况并不成立。Seaborn 猜测 x 轴是分类变量,这会破坏子图的 x 轴。从 stripplot 文档 中可以看到:

    绘制其中一个变量为分类变量的散点图。

    在我下面提供的代码中,我将其更改为简单的散点图。

  2. 在两个 hexbin 图上重叠绘制只会显示后面的那个。我在 hexbin 参数中添加了一些 alpha=0.5,但结果远非完美。

  3. 你代码中的 extent 参数只调整了 hexbin 图到每个性别的 xy。但两个 hexbin 图需要相等大小,因此它们应该使用整个系列(包括两个性别)的最小值和最大值。为了实现这一点,我向 hexbin 函数传递了所有系列的最小值和最大值,然后函数可以选择并使用相关的值。

以下是我的建议代码:
# Works in Jupyter with Python 2 Kernel.
%matplotlib inline

import seaborn as sns
import matplotlib as mpl
import matplotlib.pyplot as plt

tips = sns.load_dataset("tips")

# Borrowed from https://dev59.com/p4zda4cB1Zd3GeqPtPXx#31385996
def hexbin(x, y, color, max_series=None, min_series=None, **kwargs):
    cmap = sns.light_palette(color, as_cmap=True)
    ax = plt.gca()
    xmin, xmax = min_series[x.name], max_series[x.name]
    ymin, ymax = min_series[y.name], max_series[y.name]
    plt.hexbin(x, y, gridsize=15, cmap=cmap, extent=[xmin, xmax, ymin, ymax], **kwargs)

g = sns.PairGrid(tips, hue='sex')
g.map_diag(plt.hist)
g.map_lower(plt.scatter, alpha=0.5)
g.map_upper(hexbin, min_series=tips.min(), max_series=tips.max(), alpha=0.5)

以下是结果: 在此输入图片描述


感谢您的解释,我忘了提到我是一个 Python 和 Seaborn 的新手。我一定会记住多阅读文档。感谢您提供的优美解决方案。 - Stereo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接