Search code examples
pythonpandasbokeh

How to incorporate subplots option when plotting a data frame using Pandas-Bokeh?


I have a dataframe corresponding to a multivariate time series which I'd like to plot. Each channel would appear on its own set of axes, with all plots arranged vertically. I'd also like to add the interactive options available with Bokeh, including the ability to remove one channel from view by clicking on its label.

Without Bokeh, I can use subplots to get the separate "static" plots stacked vertically as follows:

import numpy as np
import pandas as pd
from matplotlib import pyplot as plt

A=np.random.rand(800,10)
df=pd.DataFrame(data=A,columns=['a','b','c','d','e','f','g','h','i','j'])

df.plot(subplots=True)
plt.show()

I can plot the 10 channels on one set of axes using Bokeh using this:

import numpy as np
import pandas as pd
pd.set_option('plotting.backend', 'pandas_bokeh')

A=np.random.rand(800,10)
df=pd.DataFrame(data=A,columns=['a','b','c','d','e','f','g','h','i','j'])
df.plot_bokeh(kind="line")

The resulting graph allows for zooming, panning, channel de-selection, etc. However all plots signals are plotted on the same set of axes, which I would rather not do.


Solution

  • I use this code snippet to plot my figures in a grid.

    import pandas as pd
    import pandas_bokeh
    from bokeh.palettes import Dark2_5 as palette
    
    
    def plot_grid(df: pd.DataFrame):
        figs = []
        color = itertools.cycle(palette)
        for c in df.columns:
            figs.append(df[c].plot_bokeh(show_figure=False, color=next(color)))
        pandas_bokeh.plot_grid(figs, ncols=1, plot_width=1500)
    

    The ncols parameter allows you to specify how many columns you want per row. Hope this helps!