2016-11-08 78 views
0

我想要在Seaborn网格中获取hexbin图。我有以下代码,PairGrid中的Hexbin图与Seaborn

# 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地块以这样一种方式,他们覆盖图的整个表面,而不是只是所示绘图区域的一个子集?

+0

而是反对投票的请解释我如何能提高问题的质量。我很乐意这样做。 – Stereo

+0

这可能是因为你没有一个最小的工作例子。 – GWW

+0

更新了代码,谢谢! – Stereo

回答

2

您在这里要做的事情有(至少)三个问题。

  1. stripplot适用于至少有一个轴是分类的数据。这种情况并非如此。 Seaborn猜测x轴是将子图的x轴弄乱的分类。从docs for stripplot

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

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

  2. 借鉴海誓山盟的前两名hexbin-地块将只显示后者。我在hexbin参数中添加了一些alpha=0.5,但结果并不美观。

  3. 在你的代码的程度的参数调整hexbin阴谋x和每个性别之一y同时。但是这两个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

+0

感谢您的解释,我忘了提及我是一名蟒蛇和海豹菜鸟。我绝对会想到更多RTFM。感谢您的美丽解决方案。 – Stereo