Search code examples
pythonpandasmatplotlibplotseaborn

How do i add a subplot to an existing FacetGrid?


i have 10 times measured data i want to plot in a specific way. The easy part was this:

facetgrid = sns.lmplot(data=file_to_plot, col="count", col_wrap=3, x='measured_data', y='y_data')
plt.savefig(dir + f'{name}.png')
plt.close()

This creates a png with 10 plots in 4 rows and 3 colums with only one diagram in the last row.

FacetGrid with 10 plots from one function call

First, I want the axis labels all in one row

Secondly I want a plot that kind of aggregates all the other ones and concludes at the "12th" place of the plot, lower right corner. I would do that with:

sns.regplot(data=file_to_plot, x='measured_data', y='y_data', scatter_kws={"alpha": 0})

FacetGrid mockup with 11 plots

I cannot grasp how to add an axes object or similiar to the existing facetgrid lmplot() created. Or should I manipulate my Dataframe?


Solution

  • The code below uses "month" as the variable for each subplot.

    • Create a copy of the dataset, replacing "month" with a string "all".
    • Concatenate the original dataset and the "all" dataset to create a facet grid.
    • Use col_order= with two extra columns: a dummy column and an "all" column.
    • Afterward, the "dummy" subplot can be cleaned up.
    import matplotlib.pyplot as plt
    import seaborn as sns
    import pandas as pd
    
    # create a test dataset reducing the flights dataset to 10 months
    flights = sns.load_dataset('flights')
    months = list(flights['month'].unique())[:10]  # get first 10 months
    flights = flights[flights['month'].isin(months)]
    
    # make a copy to represent all months
    flights_all = flights.copy()
    flights_all['month'] = 'all'
    
    # create the facet grid, adding a "dummy" month and an "all" month
    fg = sns.lmplot(pd.concat([flights, flights_all]), x='year', y='passengers',
                    col='month', col_wrap=3, col_order=months + ['dummy', 'all'],
                    height=3, aspect=2)
    
    # remove the title of the dummy subplot
    fg.axes_dict['dummy'].set_title('')  # remove title of dummy subplot
    
    # optionally remove y-axis and ticks of the dummy subplot
    fg.axes_dict['dummy'].spines['left'].set_visible(False)
    fg.axes_dict['dummy'].tick_params(axis='y', length=0)
    
    # optionally change the line color in the all subplot
    fg.axes_dict['all'].lines[0].set_color('crimson')
    
    plt.show()
    

    seaborn facetgrid with extra subplots