gpt4 book ai didi

python - 如何用来自不同数据集的 "marginal"(分布直方图)覆盖 Seaborn 联合图

转载 作者:太空狗 更新时间:2023-10-30 01:57:49 26 4
gpt4 key购买 nike

我根据一组存储在 pandas DataFrame 中的“观察到的计数与浓度”绘制了一个 Seaborn JointPlot。我想(在同一组轴上)在现有边际之上覆盖每个浓度的“预期计数”的边际(即:单变量分布),以便可以轻松比较差异。

这张图与我想要的非常相似,尽管它有不同的轴并且只有两个数据集:

这是我的数据布局和关联方式的示例:

df_observed

x axis--> log2(concentration): 1,1,1,2,3,3,3 (zero-counts have been omitted)

y axis--> log2(count): 4.5, 5.7, 5.0, 9.3, 16.0, 16.5, 15.4 (zero-counts have been omitted)

df_expected

x axis--> log2(concentration): 1,1,1,2,2,2,3,3,3

因此,将 df_expected 的分布叠加在 df_observed 的分布之上将指示每个浓度的计数丢失的位置。

我目前拥有的

Jointplot with the observed counts at each concentration Separate jointplot of the expected counts at each concentration. I want the marginal from this plot to be overlaid on top of the marginal from the above jointplot

PS:我是 Stack Overflow 的新手,所以任何关于如何更好地提问的建议都将不胜感激。另外,我已经广泛搜索了我的问题的答案,但无济于事。此外,Plotly 解决方案同样有用。谢谢

最佳答案

写了一个函数来绘制它,非常松散地基于@blue_chip 的想法。您可能仍需要根据您的特定需求对其进行一些调整。

这是一个用法示例:

enter image description here

示例数据:

import seaborn as sns, numpy as np, matplotlib.pyplot as plt, pandas as pd
n=1000
m1=-3
m2=3

df1 = pd.DataFrame((np.random.randn(n)+m1).reshape(-1,2), columns=['x','y'])
df2 = pd.DataFrame((np.random.randn(n)+m2).reshape(-1,2), columns=['x','y'])
df3 = pd.DataFrame(df1.values+df2.values, columns=['x','y'])
df1['kind'] = 'dist1'
df2['kind'] = 'dist2'
df3['kind'] = 'dist1+dist2'
df=pd.concat([df1,df2,df3])

函数定义:

def multivariateGrid(col_x, col_y, col_k, df, k_is_color=False, scatter_alpha=.5):
def colored_scatter(x, y, c=None):
def scatter(*args, **kwargs):
args = (x, y)
if c is not None:
kwargs['c'] = c
kwargs['alpha'] = scatter_alpha
plt.scatter(*args, **kwargs)

return scatter

g = sns.JointGrid(
x=col_x,
y=col_y,
data=df
)
color = None
legends=[]
for name, df_group in df.groupby(col_k):
legends.append(name)
if k_is_color:
color=name
g.plot_joint(
colored_scatter(df_group[col_x],df_group[col_y],color),
)
sns.distplot(
df_group[col_x].values,
ax=g.ax_marg_x,
color=color,
)
sns.distplot(
df_group[col_y].values,
ax=g.ax_marg_y,
color=color,
vertical=True
)
# Do also global Hist:
sns.distplot(
df[col_x].values,
ax=g.ax_marg_x,
color='grey'
)
sns.distplot(
df[col_y].values.ravel(),
ax=g.ax_marg_y,
color='grey',
vertical=True
)
plt.legend(legends)

用法:

multivariateGrid('x', 'y', 'kind', df=df)

关于python - 如何用来自不同数据集的 "marginal"(分布直方图)覆盖 Seaborn 联合图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35920885/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com