2015-10-16 117 views
7

所以我使用seaborn做kdeplotsns.kdeplot(x, y, ax=plt.gca(), cmap="coolwarm")如何標籤seaborn等高線圖

我可以用levels kwarg改變水平,但我想能夠標註輪廓。在matplotlib中,您只需執行plt.clabel(CS, CS.levels, inline=True),但seaborn不會返回輪廓集合CS

我該怎麼做?或者我只需要從頭開始自己做?

編輯:有沒有辦法讓一個包裝也將返回CS?我看不到如何...

+0

是的,你必須自己做,雖然一般的密度值不是特別有意義或有趣。 – mwaskom

+0

我試圖讓水平,所以我可以插入圖例。但是因爲它們沒有特別的意義,所以我使用了一個自定義的KDE函數並且繪製了結果(根據您的建議)。謝謝 – Lucidnonsense

回答

5

不幸的是,seaborn做的一切都是爲了讓用戶保持計數器的祕密。除了從數據中繪製一張plt.contour的圖表,實際上並不太難,您可以讓猴子修補seaborn _bivariate_kdeplot,然後讓它返回以供進一步使用。

這可能如下所示:

import matplotlib.pyplot as plt 
import numpy as np; np.random.seed(10) 
import seaborn as sns 
import seaborn.distributions as sd 
from seaborn.palettes import color_palette, blend_palette 
from six import string_types 


def _bivariate_kdeplot(x, y, filled, fill_lowest, 
         kernel, bw, gridsize, cut, clip, 
         axlabel, cbar, cbar_ax, cbar_kws, ax, **kwargs): 
    """Plot a joint KDE estimate as a bivariate contour plot.""" 
    # Determine the clipping 
    if clip is None: 
     clip = [(-np.inf, np.inf), (-np.inf, np.inf)] 
    elif np.ndim(clip) == 1: 
     clip = [clip, clip] 

    # Calculate the KDE 
    if sd._has_statsmodels: 
     xx, yy, z = sd._statsmodels_bivariate_kde(x, y, bw, gridsize, cut, clip) 
    else: 
     xx, yy, z = sd._scipy_bivariate_kde(x, y, bw, gridsize, cut, clip) 

    # Plot the contours 
    n_levels = kwargs.pop("n_levels", 10) 
    cmap = kwargs.get("cmap", "BuGn" if filled else "BuGn_d") 
    if isinstance(cmap, string_types): 
     if cmap.endswith("_d"): 
      pal = ["#333333"] 
      pal.extend(color_palette(cmap.replace("_d", "_r"), 2)) 
      cmap = blend_palette(pal, as_cmap=True) 
     else: 
      cmap = plt.cm.get_cmap(cmap) 

    kwargs["cmap"] = cmap 
    contour_func = ax.contourf if filled else ax.contour 
    cset = contour_func(xx, yy, z, n_levels, **kwargs) 
    if filled and not fill_lowest: 
     cset.collections[0].set_alpha(0) 
    kwargs["n_levels"] = n_levels 

    if cbar: 
     cbar_kws = {} if cbar_kws is None else cbar_kws 
     ax.figure.colorbar(cset, cbar_ax, ax, **cbar_kws) 

    # Label the axes 
    if hasattr(x, "name") and axlabel: 
     ax.set_xlabel(x.name) 
    if hasattr(y, "name") and axlabel: 
     ax.set_ylabel(y.name) 

    return ax, cset 

# monkey patching 
sd._bivariate_kdeplot = _bivariate_kdeplot 

# some data 
mean, cov = [0, 2], [(1, .5), (.5, 1)] 
x, y = np.random.multivariate_normal(mean, cov, size=50).T 

# plot 
fig, ax = plt.subplots() 
_, cs = sns.kdeplot(x, y, ax=ax, cmap="coolwarm") 
# label the contours 
plt.clabel(cs, cs.levels, inline=True) 
# add a colorbar 
fig.colorbar(cs) 

plt.show() 

enter image description here

+0

對!此修補程序還允許將輪廓填充,線條和標籤的顯示進行輕微更改。 Colorbar在將seaborn更新爲v0.8.1後工作。 – bejota