Search code examples
bokeh

Aligning a Bokeh plot. (Python)


I am actually a beginner to Python's Bokeh library.

I am plotting a simple scatter plot as follows:

from bokeh.io import show
from bokeh.plotting import figure
plot = figure()
plot.circle(x=[1,2,3,4,5],y=[10,7,2,5,9],size=10)
show(plot)

The code above opens a html page, with that plot aligned to the left of the screen.

Is there a way to align the plot to the center ?

I actually saw an attibute align of the method figure.

I set it to 'center', but nothing happened.

Can anyone help ?


Solution

  • Well, I have faced this problem and i found a solution that works: You need to create a template that will overwrite the margin property of the plot's parent div>

    template = """
    {% block postamble %}
    <style>
    .bk-root .bk {
        margin: 0 auto !important;
    }
    </style>
    {% endblock %}
    """
    

    .bk-root .bk defines the parent div of your plot. .bk-root is specified too because this will prevent ignoring of this property by specific styles(related to style importance evaluation order). !important; is needed because margin property for that div is defined inline. Inline property can be overwritten only with this !important tag.

    After this you will need two imports and two function calls:

    from bokeh.io import save
    from bokeh.util.browser import view
    save(your_plot, template=template)
    view("digits.html")
    

    The save function will apply template to your html document. The view function will open a new tab in browser with your centered plot.

    In case this solution does not work, you should inspect the html code from your browser and find out for which div class you should modify margin property, but general concept will remain the same.