Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit the range of x in seaborn distplot KDE estimation

Suppose we have an array with numbers between 0 and 1:

arr=np.array([ 0.        ,  0.        ,  0.        ,  0.        ,  0.6934264 ,
               0.        ,  0.        ,  0.        ,  0.        ,  0.        ,
               0.        ,  0.        ,  0.6934264 ,  0.        ,  0.6934264 ,
               0.        ,  0.        ,  0.        ,  0.        ,  0.251463  ,
               0.        ,  0.        ,  0.        ,  0.87104906,  0.251463  ,
               0.        ,  0.        ,  0.        ,  0.        ,  0.        ,
               0.        ,  0.        ,  0.        ,  0.        ,  0.48419626,
               0.        ,  0.        ,  0.        ,  0.        ,  0.        ,
               0.87104906,  0.        ,  0.        ,  0.251463  ,  0.48419626,
               0.        ,  0.251463  ,  0.        ,  0.        ,  0.        ,
               0.        ,  0.        ,  0.        ,  0.        ,  0.        ,
               0.        ,  0.251463  ,  0.        ,  0.35524532,  0.        ,
               0.        ,  0.        ,  0.        ,  0.        ,  0.251463  ,
               0.251463  ,  0.        ,  0.74209813,  0.        ,  0.        ])

Using seaborn, I want to plot a distribution plot:

sns.distplot(arr, hist=False)

Which will give us the following figure: enter image description here

As you can see, the kde estimation ranges from somewhere near -0.20 to 1.10. Is it possible to force the estimation to be between 0 and 1? I have tried the followings with no luck:

sns.distplot(arr, hist=False, hist_kws={'range': (0.0, 1.0)})
sns.distplot(arr, hist=False, kde_kws={'range': (0.0, 1.0)})

The second line raises an exception -- range not a valid keyword for kde_kws.

like image 210
Ashkan Avatar asked Aug 28 '17 04:08

Ashkan


2 Answers

The correct way of doing this, is by using the clip keyword instead of range:

sns.distplot(arr, hist=False, kde_kws={'clip': (0.0, 1.0)})

which will produce: enter image description here

Indeed, if you only care about the kde and not the histogram, you can use the kdeplot function, which will produce the same result:

sns.kdeplot(arr, clip=(0.0, 1.0))
like image 138
Ashkan Avatar answered Sep 27 '22 17:09

Ashkan


Settins plt.xlim(0, 1) beforehand should help :

plt.xlim(0, 1)
sns.distplot(arr, hist=False)
like image 34
R. Cox Avatar answered Sep 27 '22 19:09

R. Cox