How to overlay a Seaborn jointplot with a “marginal” (distribution histogram) from a different dataset

后端 未结 3 1073
死守一世寂寞
死守一世寂寞 2021-02-06 07:22

I have plotted a Seaborn JointPlot from a set of \"observed counts vs concentration\" which are stored in a pandas DataFrame. I would like to overlay (

3条回答
  •  轮回少年
    2021-02-06 07:32

    Whenever I try to modify a JointPlot more than for what it was intended for, I turn to a JointGrid instead. It allows you to change the parameters of the plots in the marginals.

    Below is an example of a working JointGrid where I add another histogram for each marginal. These histograms represent the expected value that you wanted to add. Keep in mind that I generated random data so it probably doesn't look like yours.

    Take a look at the code, where I altered the range of each second histogram to match the range from the observed data.

    import pandas as pd
    import numpy as np
    import seaborn as sns
    import matplotlib.pyplot as plt
    
    df = pd.DataFrame(np.random.randn(100,4), columns = ['x', 'y', 'z', 'w'])
    
    plt.ion()
    plt.show()
    plt.pause(0.001)
    
    p = sns.JointGrid(
        x = df['x'],
        y = df['y']
        )
    
    p = p.plot_joint(
        plt.scatter
        )
    
    p.ax_marg_x.hist(
        df['x'],
        alpha = 0.5
        )
    
    p.ax_marg_y.hist(
        df['y'],
        orientation = 'horizontal',
        alpha = 0.5
        )
    
    p.ax_marg_x.hist(
        df['z'],
        alpha = 0.5,
        range = (np.min(df['x']), np.max(df['x']))
        )
    
    p.ax_marg_y.hist(
        df['w'],
        orientation = 'horizontal',
        alpha = 0.5,
        range = (np.min(df['y']), np.max(df['y'])),
        )
    

    The part where I call plt.ion plt.show plt.pause is what I use to display the figure. Otherwise, no figure appears on my computer. You might not need this part.

    Welcome to Stack Overflow!

提交回复
热议问题