How to better fit seaborn violinplots?

后端 未结 1 483
梦如初夏
梦如初夏 2020-12-16 14:52

The following code gives me a very nice violinplot (and boxplot within).

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

foo = np.         


        
相关标签:
1条回答
  • As the comments note, this is a consequence (I'm not sure I'd call it an "artifact") of the assumptions underlying gaussian KDE. As has been mentioned, this is somewhat unavoidable, and if your data don't meet those assumptions, you might be better off just using a boxplot, which shows only points that exist in the actual data.

    However, in your response you ask about whether it could be fit "tighter", which could mean a few things.

    One answer might be to change the bandwidth of the smoothing kernel. You do that with the bw argument, which is actually a scale factor; the bandwidth that will be used is bw * data.std():

    data = np.random.rand(100)
    sns.violinplot(y=data, bw=.1)
    

    enter image description here

    Another answer might be to truncate the violin at the extremes of the datapoints. The KDE will still be fit with densities that extend past the bounds of your data, but the tails will not be shown. You do that with the cut parameter, which specifies how many units of bandwidth past the extreme values the density should be drawn. To truncate, set it to 0:

    sns.violinplot(y=data, cut=0)
    

    enter image description here

    By the way, the API for violinplot is going to change in 0.6, and I'm using the development version here, but both the bw and cut arguments exist in the current released version and behave more or less the same way.

    0 讨论(0)
提交回复
热议问题