【问题标题】:Hexbin plot in PairGrid with Seaborn使用 Seaborn 的 PairGrid 中的 Hexbin 绘图
【发布时间】:2016-11-24 21:37:44
【问题描述】:

我正在尝试在 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 http://stackoverflow.com/a/31385996/4099925
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)

但是,这给了我以下图像,

如何修复十六进制图,使其覆盖图形的整个表面,而不仅仅是显示的绘图区域的子集?

【问题讨论】:

  • 请解释我如何提高问题的质量,而不是投反对票。我很乐意这样做。
  • 这可能是因为你没有一个最小的工作示例。
  • 更新了代码,谢谢!

标签: python matplotlib seaborn


【解决方案1】:

您在这里尝试做的事情(至少)存在三个问题。

  1. stripplot 适用于至少一个轴是分类的数据。在这种情况下,情况并非如此。 Seaborn 猜测 x 轴是一个分类轴,它会弄乱子图的 x 轴。来自docs for stripplot

    绘制一个散点图,其中一个变量是分类变量。

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

  2. 在彼此之上绘制两个 hexbin 图将只显示后一个。我在 hexbin 参数中添加了一些 alpha=0.5,但结果并不漂亮。

  3. 代码中的 extent 参数将十六进制图调整为每个性别一次一个xy。但是两个 hexbin 图的大小需要相等,因此它们应该使用整个系列的最小值/最大值,而不是 both 性别。为了实现这一点,我将所有系列的最小值和最大值传递给 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 http://stackoverflow.com/a/31385996/4099925
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菜鸟。我绝对会更多地考虑 RTFM。谢谢你漂亮的解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-29
  • 2023-01-09
  • 1970-01-01
  • 2021-07-22
  • 2015-09-05
相关资源
最近更新 更多