2016-11-08 42 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