1
votes

Is there a way how to add multiple seaborn boxplots to one figure sequentially?

Taking example from Time-series boxplot in pandas:

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

n = 480
ts = pd.Series(np.random.randn(n), index=pd.date_range(start="2014-02-01", periods=n, freq="H"))


fig, ax = plt.subplots(figsize=(12,5))
seaborn.boxplot(ts.index.dayofyear, ts, ax=ax)

This gives me one series of box-plots?

enter image description here

Now, is there any way to plot two time-series like this one the same plot side-by-side? I want to plot it in the function that would have make_new_plot boolean parameter for separating the boxplots that are plotted from the for-loop.

If I try to just call it on the same axis, it gives me the overlapping plots:

enter image description here

I know that it is possible to concatenate the dataframes and make box plots of the concatenated dataframe together, but I would not want to have this plotting function returning any dataframes.

Is there some other way to make it? Maybe it is possible to somehow manipulate the width&position of boxes to achieve this? The fact tact that I need a time-series of boxplots & matplotlib "positions" parameter is on purpose not supported by seaborn makes it a bit tricky for me to figure out how to do it.

Note that it is NOT the same as eg. Plotting multiple boxplots in seaborn?, because I want to plot it sequentially without returning any dataframes from the plotting function.

1
where should the second set of boxes be? Each new box alongside the other (like hue-nesting), or as a whole group on the right, at positions 52...71?Diziet Asahi
@DizietAsahi boxes alongside each other for each time-step. I sorta managed to do a workaround in pure matplotlib but still wondering if there is a smarted way to do it.Valeria

1 Answers

0
votes

You could do something like the following if you want to have hue nesting of different time-series in your boxplots.

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

n = 480
ts0 = pd.Series(np.random.randn(n), index=pd.date_range(start="2014-02-01", periods=n, freq="H"))
ts1 = pd.Series(np.random.randn(n), index=pd.date_range(start="2014-02-01", periods=n, freq="H"))
ts2 = pd.Series(np.random.randn(n), index=pd.date_range(start="2014-02-01", periods=n, freq="H"))

def ts_boxplot(ax, list_of_ts):
    new_list_of_ts = []
    for i, ts in enumerate(list_of_ts):
        ts = ts.to_frame(name='ts_variable')
        ts['ts_number'] = i
        ts['doy']=ts.index.dayofyear
        new_list_of_ts.append(ts)
    plot_data = pd.concat(new_list_of_ts)
    sns.boxplot(data=plot_data, x='doy', y='ts_variable', hue='ts_number', ax=ax)
    return ax

fig, ax = plt.subplots(figsize=(12,5))
ax = ts_boxplot(ax, [ts0, ts1, ts2])