Search code examples
pythongraphseaborncatplot

Is there a way to add a line plot on top of all plots within a Catplot grid in Seaborn/Python?


Hello I am very new to using python, I am starting to use it for creating graphs at work (for papers and reports etc). I was just wondering if someone could help with the problem which I have detailed below? I am guessing there is a very simple solution but I can't figure it out and it is driving me insane!

Basically, I am plotting the results from an experiment where by on the Y-axis I have the results which in this case is a numerical number (Result), against the x-axis which is categorical and is labeled Location. The data is then split across four graphs based on which machine the experiment is carried out on (Machine)(Also categorical).

This first part is easy the code used is this:

'sns.catplot(x='Location', y='Result', data=df3, hue='Machine', col='Machine', col_wrap = 2, linewidth=2, kind='swarm')'

this provides me with the following graph: Catplot without line

I now want to add another layer to the plot where by it is a red line which represents the Upper spec limit for the data.

So I add the following line off code to the above:

'sns.lineplot(x='Location',y=1.8, data=df3, linestyle='--', color='r',linewidth=2)'

This then gives the following graph:

Catplot with line

As you can see the red line which I want is only on one of the graphs, all I want to do is add the same red line across all four graphs in the exact same position etc.

Can anyone help me???


Solution

  • You could use .map to draw a horizontal lines on each of the subplots. You need to catch the generated FacetGrid object into a variable.

    Here is an example:

    import matplotlib.pyplot as plt
    import seaborn as sns
    
    titanic = sns.load_dataset('titanic').dropna()
    
    g = sns.catplot(x='class', y='age', data=titanic,
                    hue='embark_town', col='embark_town', col_wrap=2, linewidth=2, kind='swarm')
    g.map(plt.axhline, y=50, ls='--', color='r', linewidth=2)
    plt.tight_layout()
    plt.show()
    

    catplot with horizontal line