如何将权重参数传递给seaborn的jointplot()或底层kdeplot?

时间:2015-05-20 08:44:03

标签: python seaborn

我尝试使用以下代码创建一个seaborn的联合图:

import seaborn as sns 
import pandas as pd
import numpy as np
import matplotlib.pylab as plt

testdata = pd.DataFrame(np.array([[100, 1, 3], [5, 2, 6], [25, 3, -4]]), index=['A', 'B', 'C'], columns=['counts', 'X', 'Y'])
counts = testdata['counts'].values
sns.jointplot('X', 'Y', data=testdata, kind='kde', joint_kws={'weights':counts})
plt.savefig('test.png')

现在joint_kws没有引发错误,但是在图中可以看到权重肯定不会被考虑在内:

我还尝试使用JointGrid,将权重传递给边际分布:

g = sns.JointGrid('X', 'Y', data=testdata)
x = testdata['X'].values
y = testdata['Y'].values
g.ax_marg_x.hist(x, bins=np.arange(-10,10), weights=counts)
g.ax_marg_y.hist(y, bins=np.arange(-10,10), weights=counts, orientation='horizontal')
g.plot_marginals(sns.distplot)
g.plot_join(sns.kdeplot, joint_kws={'weights':counts})
plt.savefig('test.png')

但这仅适用于边际分布,而联合图仍未加权:

有谁知道如何做到这一点?

3 个答案:

答案 0 :(得分:0)

不幸的是,这似乎是不可能的。

2015年12月提交的a feature request已被提交,但已被关闭,因为无法修复。

此StackOverflow问题中也对此进行了讨论:weights option for seaborn distplot?

答案 1 :(得分:0)

我知道这是很久以前的事了,但我已经能够在联合图中使用权重:

p = sns.jointplot(data=v, x="x", y="y",  kind="hist", weights=v.weights, bins=50)

v 是一个包含 [x,y,weights]

列的数据框

答案 2 :(得分:-1)

你真的很亲密。

要保留的是连接图执行以下操作(重复释义):

def jointplot(x, y, data=None, ..., joint_kws):
    g = sns.JointGrid(...)
    g.plot_joint(..., **joint_kws)

所以,当你自己打电话给g.plot_joint时,只需喂它正常的kwargs:

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

testdata = pd.DataFrame(
    np.array([[100, 1, 3], [5, 2, 6], [25, 3, -4]]), 
    index=['A', 'B', 'C'], 
    columns=['counts', 'X', 'Y']
)
counts = testdata['counts'].values

g = sns.JointGrid('X', 'Y', data=testdata)
g.plot_marginals(sns.distplot)
g.plot_joint(sns.kdeplot, weights=counts)

enter image description here

现在我不确定这看起来是否正确,但它没有barf,所以这是值得的。