Center plot in notebook cell

Trying to center a bokeh plot in a notebook cell like holoviews does.
Using the align keyword when creating the figure didn’t work.
Here is an example from the docs:

from bokeh.io import show
from bokeh.plotting import figure

fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']
counts = [5, 3, 4, 2, 4, 6]

p = figure(x_range=fruits, plot_height=250, title="Fruit counts",
           toolbar_location=None, tools="", align="center")

p.vbar(x=fruits, top=counts, width=0.9)

p.xgrid.grid_line_color = None
p.y_range.start = 0

show(p)

I would appreciate any suggestions or guidance on how to do this.

I don’t actually know what Holoviews does to accomplish this. I am not sure there will be any simple or easy solution out of the box.

cc @Philipp_Rudiger @James_A_Bednar1

Thanks for the amazingly quick response! Also, thanks for the awesome project and community support.

I’ve been browsing through the source for holoviews to figure it out, but haven’t found it yet. I was hoping it was something simple and obvious I was overlooking. :slight_smile:

I found a couple of work arounds shared below. I do still wonder if the align=center attribute is not being properly respected/handled.

One approach is to output to HTML and wrap in a <center> tag.

from bokeh.resources import CDN
from bokeh.embed import file_html
from IPython.display import display, HTML

html = file_html(p, CDN, theme="dark_minimal")
HTML("<center>{}</center>".format(html))

Another approach is to use panel:

import panel as pn
pn.extension()

pn.Row(pn.layout.HSpacer(), p, pn.layout.HSpacer())

I suspect there are other, possibly better, ways to accomplish this, so I would appreciate any other ideas or suggestions.

I only just noticed your passing that to figure. I would not expect that to work. As the docs state it centers within the parent container, which in this case I am fairly sure has tight bounds. So, basically a no-op. That property has very narrow applicability, perhaps it should have been private, or had a less friendly name.

I would expect any solution to involve CSS as above, or spacers. AFAIK you could try that solution with Bokeh’s row and Spacer without Holoviews.

Edit: align=center might work if you do that with the plot as single child inside a row that has a responsive sizing mode specified.