出生在海尔格的海滨

2024-10-02 06:27:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我在试着在一个海生的网格里得到一个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)

但是,这给了我下面的图像, seaborn output

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


Tags: importtruemapmatplotlibaspltminmax
1条回答
网友
1楼 · 发布于 2024-10-02 06:27:33

你想做的事情(至少)有三个问题。在

  1. stripplot用于至少有一个轴是分类的数据。在这种情况下,情况并非如此。Seaborn猜测x轴是绝对轴,它会扰乱子批次的x轴。从docs for stripplot

    ^{bq}$

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

  2. 在每一个上面画两个hexbin图只会显示后一个。我在hexbin参数中添加了一些alpha=0.5,但结果并不理想。

  3. 代码中的extent参数将hexbin图调整为x和{},一次一个。但是两个hexbin图的大小必须相等,所以它们应该使用一个完整系列的最小值/最大值,而不是两个性别。为了实现这一点,我将所有系列的最小值和最大值传递给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 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)

结果如下: enter image description here

相关问题 更多 >

    热门问题