How to use bokeh.server

share link

by vsasikalabe dot icon Updated: Aug 29, 2023

technology logo
technology logo

Solution Kit Solution Kit  

The Bokeh server is an element of Bokeh. This is for making interactive web applications. Python code running on a server connects to it. The system mentions no-host values by default. 

 

Then, the Bokeh server will accept requests from the local host. The server is listening to (by default: 5006). Bokeh is a Python library. People use it to create interactive graphs and visualizations. You can do this in Bokeh using HTML and JavaScript. This is a powerful tool for custom charts and web design-based applications. The ColumnDataSource (CDS) is the core of Bokeh plots. It gives the data for the glyphs of the plot. When using lists or arrays to a Bokeh renderer, Bokeh creates a ColumnDataSource.   

   

The purpose of the Bokeh server is to create interactive Web applications. It can connect front-end UI events to real, running Python code. During the visualization, the Bokeh server gives convenient deploying HoloViews plots. This flexible and decoupled design gives some advantages. It is easy to work with other languages. Such as R or Scala, drive Bokeh plots and visualizations in the browser.   

  

The browser provides powerful capabilities:   

  • Respond to UI and tool events in the browser using the full power of Python.   
  • Push server-side updates to the UI elements (widgets or plots in the browser)   
  • use periodic, timeout, and asynchronous callbacks (streaming updates)   

   

Photographers use Bokeh. Their striking light effects highlight an element and blur the rest of the image. Bokeh, also called “Boke,” is one of the most popular advantages of photography. Bokeh makes photographs visually appealing. This focuses on a particular area of the image. The word comes from the Japanese language. It translates as “blur”.   

Preview of the output that you will get on running this code from your IDE.

Code

In this solution, we used Bokeh library.

from bokeh.layouts import column
from bokeh.models import ColumnDataSource, Slider
from bokeh.plotting import figure
from bokeh.server.server import Server
from bokeh.themes import Theme

from bokeh.sampledata.sea_surface_temperature import sea_surface_temperature

def modify_doc(doc):
    df = sea_surface_temperature.copy()
    source = ColumnDataSource(data=df)

    plot = figure(x_axis_type='datetime', y_range=(0, 25), y_axis_label='Temperature (Celsius)',
                  title="Sea Surface Temperature at 43.18, -70.43")
    plot.line('time', 'temperature', source=source)

    def callback(attr, old, new):
        if new == 0:
            data = df
        else:
            data = df.rolling('{0}D'.format(new)).mean()
        source.data = ColumnDataSource(data=data).data

    slider = Slider(start=0, end=30, value=0, step=1, title="Smoothing by N Days")
    slider.on_change('value', callback)

    doc.add_root(column(slider, plot))

    doc.theme = Theme(filename="theme.yaml")

# Setting num_procs here means we can't touch the IOLoop before now, we must
# let Server handle that. If you need to explicitly handle IOLoops then you
# will need to use the lower level BaseServer class.
server = Server({'/': modify_doc}, num_procs=4)
server.start()

if __name__ == '__main__':
    print('Opening Bokeh application on http://localhost:5006/')

    server.io_loop.add_callback(server.show, "/")
    server.io_loop.start()

from bokeh.models import  ColumnDataSource, Legend, CustomJS, Select
from bokeh.plotting import figure
from bokeh.palettes import Category10
from bokeh.layouts import row
import pandas as pd
from bokeh.server.server import Server

from bokeh.sampledata.sea_surface_temperature import sea_surface_temperature

def test(doc):
    df0 = pd.DataFrame({'x': [1, 2, 3], 'Ay' : [1, 5, 3], 'A': [0.2, 0.1, 0.2], 'By' : [2, 4, 3], 'B':[0.1, 0.3, 0.2]})

    columns = ['A', 'B']

    tools_to_show = 'box_zoom,save,hover,reset'
    p = figure(plot_height =300, plot_width = 1200, 
               toolbar_location='above',
               tools=tools_to_show)

    legend_it = []
    color = Category10[10]
    columns = ['A', 'B']
    source = ColumnDataSource(df0)
    c = []
    for i, col in enumerate(columns):
        c.append(p.line('x', col, source=source, name=col, color=color[i]))
        legend_it.append((col, [c[i]]))


    legend = Legend(items=legend_it, location=(5,114))#(0, -60))

    p.add_layout(legend, 'right')

    select = Select(title="color", value=color[0],
                    options = color)
    callbacks = CustomJS(args=dict(renderer=c[0], select=select), code ="""
        renderer.glyph.line_color = select.value;
        renderer.trigger('change')
    """)

    select.callback = callbacks

    layout = row(select, p)

    doc.add_root(layout)


server = Server({'/': test}, num_procs=1)
server.start()

if __name__ == '__main__':
    print('Opening Bokeh application on http://localhost:5006/')

    server.io_loop.add_callback(server.show, "/")
    server.io_loop.start()

Instructions

Follow the steps carefully to get the output easily.

  1. Download and Install the PyCharm Community Edition on your computer.
  2. Open the terminal and install the required libraries with the following commands.
  3. Install Bokeh - pip install Bokeh.
  4. Create a new python file on your IDE.
  5. Copy the snippet using the 'copy' button and paste (2nd part of code) into your python file.
  6. Run the current file to generate the output.


I hope you found this useful. I have added the link to dependent libraries, and version information in the following sections.


I found this code snippet by searching for ' How to embed a bokeh server in a standalone ' in kandi. You can try any such use case!

Environment Tested

I tested this solution in the following versions. Be mindful of changes when working with other versions.

  1. The solution is created in PyCharm 2022.3.
  2. The solution is tested on Python 3.11.1
  3. Bokeh version- 3.1.1


Using this solution, we are able to use bokeh.server with simple steps. This process also facilities an easy way to use, hassle-free method to create a hands-on working version of code which would help us to use bokeh.server.

Dependent Libraries

bokehby bokeh

Python doticonstar image 17667 doticonVersion:Currentdoticon
License: Permissive (BSD-3-Clause)

Interactive Data Visualization in the browser, from Python

Support
    Quality
      Security
        License
          Reuse

            bokehby bokeh

            Python doticon star image 17667 doticonVersion:Currentdoticon License: Permissive (BSD-3-Clause)

            Interactive Data Visualization in the browser, from Python
            Support
              Quality
                Security
                  License
                    Reuse

                      If you do not have the Bokeh library that is required to run this code, you can install them by clicking on the above link.

                      You can search for any dependent library on kandi like Bokeh.

                      Support

                      1. For any support on kandi solution kits, please use the chat
                      2. For further learning resources, visit the Open Weaver Community learning page.

                      FAQ:   

                      1. What is the Python library to create interactive visualizations with the Bokeh Server?   

                      Bokeh is a Python library. It is for creating interactive visualizations for modern web browsers. People use it to make pretty pictures, from simple drawings to fancy designs. We can create JavaScript-powered visualizations without writing any JavaScript yourself with Bokeh.   

                         

                      2. How does one go about running Bokeh Server?   

                      To run a Bokeh server instance, use commands like the following:   

                      serve myapp.py --port 5100   

                      serve myapp.py --port 5101   

                      To update the value of proxy_pass, find the location stanza in the Bokeh server. Then, update it in the upstream stanza. The code uses proxy_pass http://localhost:5006/  

                         

                      3. What basic visual building blocks should one know when using Bokeh Server?   

                      Glyphs are the simple visual building blocks of Bokeh plots. The simplest way is to create a simple chart using the various glyph methods. In Bokeh, glyphs are geometrical shapes (lines, circles, rectangles)   

                         

                      4. Are there security risks associated with data visualization using a bokeh server?   

                      The Bokeh server will only start WebSocket connections from the origins. To reduce the risk of cross-site misuse, people use it. That is explicitly allowed.   

                         

                      5. How can I build a bar plot or scatter plot with Bokeh Server?   

                      To create a basic bar chart, we can use the hbar() (horizontal bars) or vbar() (vertical bars) glyph methods. Pass this list as the x_range argument to figure() to assign these categories to the x-axis.  

                      See similar Kits and Libraries