Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 带加权数据的分布类型图(直方图/kde)_Python_Pandas_Matplotlib_Bokeh_Seaborn - Fatal编程技术网

Python 带加权数据的分布类型图(直方图/kde)

Python 带加权数据的分布类型图(直方图/kde),python,pandas,matplotlib,bokeh,seaborn,Python,Pandas,Matplotlib,Bokeh,Seaborn,简而言之,当我的数据被加权时,我对分布类型图(直方图或kde)的最佳选择是什么 df = pd.DataFrame({ 'x':[1,2,3,4], 'wt':[7,5,3,1] }) df.x.plot(kind='hist',weights=df.wt.values) 这很好,但seaborn不会接受重量限制,即 sns.distplot( df.x, bins=4, # doesn't work like this weights=

简而言之,当我的数据被加权时,我对分布类型图(直方图或kde)的最佳选择是什么

df = pd.DataFrame({ 'x':[1,2,3,4], 'wt':[7,5,3,1] })

df.x.plot(kind='hist',weights=df.wt.values)
这很好,但seaborn不会接受重量限制,即

sns.distplot( df.x, bins=4,              # doesn't work like this
              weights=df.wt.values )     # or with kde=False added
如果kde能接受重量,那也不错,但熊猫和seaborn似乎都不允许

顺便说一句,我意识到数据可能会被扩展以伪造权重,这在这里很容易,但对于权重为数百或数千的真实数据没有多大用处,所以我不想寻找这样的解决方法


总之,就这些。我只是想找出除了基本直方图之外,我还能用加权数据做什么(如果有的话)。我还没有玩弄bokeh,但是bokeh的建议也很受欢迎。

您必须了解seaborn使用的matplotlib绘图功能也正是pandas使用的功能

如前所述,
sns.distplot
不接受
weights
参数,但它接受
hist_kws
参数,该参数将被发送到对
plt.hist
的底层调用。因此,这应该满足您的要求:

sns.distplot(df.x, bins=4, hist_kws={'weights':df.wt.values}) 

我通过根据数据点的权重重新采样来解决这个问题

您可以这样做:

from random import random
from bisect import bisect

def weighted_choice(choices):
    values, weights = zip(*choices)
    total = 0
    cum_weights = []
    for w in weights:
        total += w
        cum_weights.append(total)
    x = random() * total
    i = bisect(cum_weights, x)
    return values[i]

samples = [([5, 0.5], 0.1), ([0, 10], 0.3), ([0, -4], 0.3)]
choices = np.array([weighted_choice(samples) for c in range(1000)])
sns.distributions.kdeplot(choices[:, 0], choices[:, 1], shade=True)

是的,谢谢,这很有帮助。我不知道如何把kwarg传递给matplotlib。我现在将进行升级投票,但将其保留一段时间,以防有人对kde或类似的东西有想法。Seaborns kde plots使用python包statmodels进行计算。相关函数采用了权重论证,但似乎seaborn并未提出这一点。相关源文件:好的,谢谢。看起来权重可能还没有实现(我不能从快速浏览中确定)。不管怎样,我现在就结束这个话题,也许以后再问一个关于kde的问题。好的。顺便说一句:mwaskom也是如此,考虑到这个问题带有seaborn标签,他可能会看看这个问题。那么我们就可以确定了。这里的问题和答案都一样: