The Wayback Machine - https://web.archive.org/web/20240917142813/https://www.geeksforgeeks.org/interactive-data-visualization-with-python-and-bokeh/
Open In App

Interactive Data Visualization with Python and Bokeh

Last Updated : 24 Jan, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we’ll learn how to do Interactive Data Visualization with Bokeh. Bokeh is a Python library that is used for creating interactive visualizations for modern web browsers. It handles custom or specialized use cases very simply.  It provides high-performance interactive charts and plots. Bokeh output can be obtained in various mediums like a notebook, HTML, and server. It is possible to embed bokeh plots in Django and Flask apps. Here we will be exploring all the key features and code for it. So let’s get started.

To install the bokeh library run the following command in the terminal : 

pip install bokeh
import bokeh
bokeh.sampledata.download()

Where to use Bokeh charts?

There are various Python libraries that can be used to plot graphs and charts. If your focus is on website interactivity, then Bokeh is the better choice than other libraries. We can use the bokeh library to embed the charts on the web page, make live dashboards, etc.  Bokeh provides highly interactive graphs and plots that target modern web browsers for presentations.

Example 1: Builtin Themes

Here, we have first imported the required libraries and then set X and Y values. Next, we’ve named the output file “output.html” A for loop is used to output all the themes available in Bokeh. Run the following code to use the built-in themes.

Python3




from bokeh.io import curdoc
from bokeh.plotting import figure, output_file, show
 
x = [1, 2, 3, 4, 5]
y = [6, 7, 6, 4, 5]
 
output_file("output.html")
themes = ['contrast', 'night_sky', 'light_minimal',
          'caliber', 'dark_minimal']
for i in themes:
    curdoc().theme = i
    p = figure(title=i, width=300, height=300)
    p.circle(x, y)
 
    show(p)


Outputs:

 

Example 2: Zoom and Drag

There are mainly 6 classifications: 

  • Pan/Drag Tool: The pan tool moves the graph within the plot.
  • Box Zoom Tool: The box zoom tool (magnifying glass symbol) is used to zoom into an area of the plot.
  • Zoom in and out Tool: In order to zoom in and out with a mouse wheel, the wheel zoom tool is used.
  • Save Tool: To save the current plot as a PNG file, the save tool is used.
  • Reset Tool: To reset the plot as it was before, the reset tool is used.
  • Help Tool: To learn more about the tools available in Bokeh, the help tool is used.

Python3




# Importing Bokeh Library
from bokeh.plotting import figure, output_file, show
 
# Importing numpy for calculating sin values
import numpy as np
 
x = [1, 2, 3, 4, 5]
y = [6, 7, 2, 4, 5]
 
fig = figure()
fig.step(x, y, line_width=2)
 
# Image Showing
show(fig)


Output:

 

Example 3: Configuring the Toolbar Location

By default, the position of the toolbar is above the plot. The positioning can be changed by passing  the toolbar_location parameter to the figure() function as shown below:

Syntax: Figure(*args, **kwargs)

Parameters: 

  • title: the title of your line chart (optional)
  • width: Width of figure
  • height: Height of figure.
  • x_axis_label: a text label to put on the chart’s x-axis (optional)
  • y_axis_label: a text label to put on the chart’s y-axis (optional)
  • toolbar_location: used to set the location of the toolbar. These are “above”, “below”, “left” and “right”. 

In this example, we have simply added the toolbar_location parameter and set its value to “below” to set the toolbar_location below. As you can see, the toolbar is now relocated below. Similarly, you can experiment with passing other values as mentioned above.

Python3




from bokeh.io import curdoc
from bokeh.plotting import figure, output_file, show
 
x = [1, 2, 3, 4, 5]
y = [6, 7, 6, 4, 5]
 
output_file("demo.html")
 
 
p = figure(title='demo', width=300, height=300,
           toolbar_location="below")
p.circle(x, y)
 
show(p)


 Output:

 

Example 4: Adding Hover Actions

The hover tool is a passive inspector tool. It is always active by default. The hover tool, by default,  generates a “tabular” tooltip where each row contains a label and its associated value. The labels and values are supplied as a list of (label, value) tuples.

TOOLTIPS = [ (“index”, “$index”),  (“(x,y)”, “($x, $y)”), (“desc”, “@desc”) ]

Note: The tooltips list consists of tuples specifying name and the field name to display.

We have defined TOOLTIPS in the above code. It is what will get displayed when we’ll hover over a data point. The labels and values are supplied as a list of (label, value) tuples. We notice that the field names begin with  $ and @. The ones beginning with $ are “special fields” and the field names beginning with @ are associated with columns in a ColumnDataSource.

Python3




from bokeh.plotting import ColumnDataSource, figure, output_file, show
 
output_file("demo.html")
 
source = ColumnDataSource(data=dict(
    x=[1, 2, 3, 4, 5],
    y=[2, 5, 8, 2, 7],
    desc=['A', 'b', 'C', 'd', 'E'],
))
 
TOOLTIPS = [
    ("index", "$index"),
    ("(x,y)", "($x, $y)"),
    ("desc", "@desc"),
]
 
p = figure(width=400, height=400, tooltips=TOOLTIPS,
           title="Mouse over the dots")
 
p.circle('x', 'y', size=20, source=source)
 
show(p)


Output:

 

Example 5: Highlighting Data using the Legend

We have plotted a line graph with ‘Date’ as the x-axis and ‘Close’ as the y-axis. Further, we have set p.legend.click_policy to “hide” in order to hide the desirable glyph. We can hide the desirable glyph by simply clicking on an entry in a legend. Bokeh provides a feature to do so by setting the legend click_policy property to “hide” as given below:

Python3




import pandas as pd
 
from bokeh.palettes import Spectral4
from bokeh.plotting import figure, output_file, show
from bokeh.sampledata.stocks import AAPL, GOOG, IBM, MSFT
 
p = figure(width=800, height=250, x_axis_type="datetime")
p.title.text = 'Click on legend entries \
            to hide the corresponding lines'
 
for data, name, color in zip([AAPL, IBM, MSFT,
                              GOOG], ["AAPL", "IBM",
                                      "MSFT", "GOOG"],
                             Spectral4):
    df = pd.DataFrame(data)
    df['date'] = pd.to_datetime(df['date'])
    p.line(df['date'], df['close'], line_width=2,
           color=color, alpha=0.8,
                           legend_label=name)
 
p.legend.location = "top_left"
p.legend.click_policy = "hide"
 
output_file("interactive_legend.html",
            title="interactive_legend.py example")
 
show(p)


Output:

 

Example 6: Linking axes and selections

Linking is required when we need plots to add connected interactivity between plots. There are two types of linking:

  1. Linked panning
  2. Linked brushing

Linked panning

It is used when it is required to link pan or zooming actions across more than one plot.

Python3




from bokeh.io import output_file, show
from bokeh.layouts import gridplot
from bokeh.plotting import figure
 
output_file("panning.html")
 
x = list(range(11))
y0 = x
y1 = [10-xx for xx in x]
y2 = [abs(xx-5) for xx in x]
 
# create a new plot
s1 = figure(width=250, height=250, title=None)
s1.circle(x, y0, size=10, color="navy", alpha=0.5)
 
# create a new plot and share both ranges
s2 = figure(width=250, height=250, x_range=s1.x_range,
            y_range=s1.y_range, title=None)
s2.triangle(x, y1, size=10, color="firebrick", alpha=0.5)
 
# create a new plot and share only one range
s3 = figure(width=250, height=250, x_range=s1.x_range, title=None)
s3.square(x, y2, size=10, color="olive", alpha=0.5)
 
p = gridplot([[s1, s2, s3]], toolbar_location=None)
 
# show the results
show(p)


Output:

 

Linked Brushing

 Linked brushing is achieved by sharing data sources between glyph renderers.

Python3




from bokeh.io import output_file, show
from bokeh.layouts import gridplot
from bokeh.models import ColumnDataSource
from bokeh.plotting import figure
 
output_file("brushing.html")
 
x = list(range(-20, 21))
y0 = [abs(xx) for xx in x]
y1 = [xx**2 for xx in x]
 
# create a column data source for the plots to share
source = ColumnDataSource(data=dict(x=x, y0=y0, y1=y1))
 
TOOLS = "box_select,lasso_select,help"
 
# create a new plot and add a renderer
left = figure(tools=TOOLS, width=300, height=300, title=None)
left.circle('x', 'y0', source=source)
 
# create another new plot and add a renderer
right = figure(tools=TOOLS, width=300, height=300, title=None)
right.circle('x', 'y1', source=source)
 
p = gridplot([[left, right]])
 
show(p)


Output:

 

Difference between Bokeh vs Matplotlib vs Plotly

Bokeh

Matplotlib

Plotly

Bokeh is a data visualization library that is used by many data science professionals. Plots made with Bokeh are flexible, interactive, and shareable. It is one of the most simple ways to plot data in Python. It is also integrated with Pandas.  It is capable of handling geographical, scientific, statistical, and financial data. Used to create interactive web-based visualizations and even web applications.  It is built on javascript
It has many interactive components like zoom, pan, search a coordinate, etc. The functionalities can be extended by using third-party packages. No third-party packages are required.
It has various output options for the plotted graphs. Each additional plot feature requires an additional required code line of code. Plotting using Plotly requires only a few lines of code.
Styling graphs with bokeh is a tedious process. It is difficult to modify/export your plot. Makes it easier to modify and export your plot.
Bokeh is the ideal tool to build dashboards and charts quickly with interactivity.  Matplotlib is a quick and straightforward tool for creating visualizations within Python. Plotly creates more beautiful plots.
Only Python programming language can be used. It is great for beginners but only Python can be used. It is compatible with many programming languages.
 The dashboard is served using the Bokeh server. It also uses a dash. The dashboard is served using the dash.
Handling of data is faster. It is compatible with IPython shells, Python scripts, and Jupyter notebooks. Handling data takes time.
There are no 3D graphing features available. It provides 3D graphing features. Also provides 3D graphing features.


Similar Reads

Interactive visualization of data using Bokeh
Bokeh is a Python library for creating interactive data visualizations in a web browser. It offers human-readable and fast presentation of data in an visually pleasing manner. If you’ve worked with visualization in Python before, it’s likely that you have used matplotlib. But Bokeh differs from matplotlib. To install Bokeh type the below command in
4 min read
Python Bokeh - Making Interactive Legends
Bokeh is a Python interactive data visualization. It renders its plots using HTML and JavaScript. It targets modern web browsers for presentation providing elegant, concise construction of novel graphics with high-performance interactivity. How to make Interactive legends? The legend of a graph reflects the data displayed in the graph's Y-axis. In
2 min read
Python - Data visualization using Bokeh
Bokeh is a data visualization library in Python that provides high-performance interactive charts and plots. Bokeh output can be obtained in various mediums like notebook, html and server. It is possible to embed bokeh plots in Django and flask apps. Bokeh provides two visualization interfaces to users: bokeh.models : A low level interface that pro
3 min read
Add Interactive Slider to Bokeh Plots
Bokeh is an interactive Data visualization library of Python. It can be used to create interactive plots, dashboards, and data applications. Widgets are nothing but additional visual elements that you can add to your plots to interactively control your Bokeh document. There are various types of widgets such as button, div, spinner, slider, etc. In
2 min read
Interactive maps with Bokeh
Interactive maps are used to visualize the data based on the geo-location category. any large dataset which contains a lot of geo-location data like cities, states, countries, etc can be plotted easily. bokeh is an open-source package, which uses the Bokeh visualization tool. It gives a flexible declarative interface for dynamic web-based visualiza
4 min read
What is Interactive Data Visualization?
Organizations are always looking for innovative methods to effectively share insights and get value from their data in today's data-rich environment. With dynamic and engaging images, users may explore and comprehend data thanks to the potent interactive data visualization technology. The article aims to discuss the importance, benefits, and techni
9 min read
Interactive Data Visualization with Plotly Express in R
Data Visualization in R is the process of representing data so that it is easy to understand and interpret. Various packages are present in the R Programming Language for data visualization. Plotly's R graphing library makes interactive, publication-quality graphs. Plotly can be used to make various interactive graphs such as scatter, line, bar, hi
9 min read
Handling Categorical Data with Bokeh - Python
As a data scientist, you will often come across datasets with categorical data. Categorical data is a type of data that can be divided into distinct categories or groups. For example, a dataset might have a column with the categories "red", "green", and "blue". Handling categorical data can be challenging because it cannot be processed in the same
5 min read
Python Bokeh – Visualizing Stock Data
Bokeh is a Python interactive data visualization. It renders its plots using HTML and JavaScript. It targets modern web browsers for presentation providing elegant, concise construction of novel graphics with high-performance interactivity. Bokeh can be used to visualize stock market data. Visualization is be done using the plotting module. Here we
3 min read
Difference Between Data Mining and Data Visualization
Data mining: Data mining is the method of analyzing expansive sums of data in an exertion to discover relationships, designs, and insights. These designs, concurring to Witten and Eibemust be "meaningful in that they lead to a few advantages, more often than not a financial advantage." Data in data mining is additionally ordinarily quantitative par
2 min read
Difference Between Data Visualization and Data Analytics
Data Visualization: Data visualization is the graphical representation of information and data in a pictorial or graphical format(Example: charts, graphs, and maps). Data visualization tools provide an accessible way to see and understand trends, patterns in data and outliers. Data visualization tools and technologies are essential to analyze massi
3 min read
Difference Between Data Science and Data Visualization
Data Science: Data science is study of data. It involves developing methods of recording, storing, and analyzing data to extract useful information. The goal of data science is to gain knowledge from any type of data both structured and unstructured. Data science is a term for set of fields that are focused on mining big data sets and discovering t
2 min read
Stock Data Analysis and Data Visualization with Quantmod in R
Analysis of historical stock price and volume data is done in order to obtain knowledge, make wise decisions, and create trading or investment strategies. The following elements are frequently included in the examination of stock data in the R Programming Language. Historical Price Data: Historical price data contains information about a stock's op
8 min read
How to create interactive data visualizations with ggvis
Creating interactive data visualizations is a powerful way to explore and present data. The ggvis package in R provides a flexible framework for building these visualizations by combining the capabilities of dplyr data manipulation and Shiny interactivity. This article will guide you through the process of creating interactive data visualizations u
7 min read
10 Examples of Interactive Map Data Visualizations
In today's data-driven world, interactive map data visualizations have become a powerful tool for communicating complex information visually and intuitively. By the term 'map' we can say it's related to geographic area. Thus the topic describes the visualization or analysis of geographic insight and its associated data in terms of a map. In this ar
7 min read
Why Data Visualization Matters in Data Analytics?
What if you wanted to know the number of movies produced in the world per year in different countries? You could always read this data in the form of a black and white text written on multiple pages. Or you could have a colorful bar chart that would immediately tell you which countries are producing more movies and if the total movies per year are
7 min read
Conditional Data Visualization Using Google Data Studio
In this article, we will learn how to do Conditional Data Visualization using Google Data studio. Before moving forward, let's understand the title itself. Data visualization Data visualization is all about getting useful insights from the data through graphical media or visuals. When data is presented in a visual format. It becomes easy and quick
3 min read
Why is Data Visualization so Important in Data Science
Would you prefer to view large data tables and then make sense of that data or view a data visualization that represents that data in an easy-to-understand visual format? Well, most of you would prefer data visualization! That is because data visualization is extremely useful in understanding the data and obtaining useful insights. It can allow you
8 min read
Visualization and Prediction of Crop Production data using Python
Prerequisite: Data Visualization in Python Visualization is seeing the data along various dimensions. In python, we can visualize the data using various plots available in different modules. In this article, we are going to visualize and predict the crop production data for different years using various illustrations and python libraries. Dataset T
4 min read
Data analysis and Visualization with Python
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages, and makes importing and analyzing data much easier. In this article, I have used Pandas to analyze data on Country Data.csv file from UN public Data Sets of a popular 'statweb.stanford.ed
4 min read
Data Visualization using Plotnine and ggplot2 in Python
Data Visualization is the technique of presenting data in the form of graphs, charts, or plots. Visualizing data makes it easier for the data analysts to analyze the trends or patterns that may be present in the data as it summarizes the huge amount of data in a simple and easy-to-understand format.  In this article, we will discuss how to visualiz
10 min read
bokeh.plotting.figure.diamond_cross() function in Python
Bokeh is a data visualization library in Python that provides high-performance interactive charts and plots and the output can be obtained in various mediums like a notebook, HTML and server. Figure Class create a new Figure for plotting. It is a subclass of Plot that simplifies plot creation with default axes, grids, tools, etc. bokeh.plotting.fig
2 min read
bokeh.plotting.figure.step() function in Python
Bokeh is a data visualization library in Python that provides high-performance interactive charts and plots and the output can be obtained in various mediums like notebook, html and server. The Figure Class create a new Figure for plotting. It is a subclass of Plot that simplifies plot creation with default axes, grids, tools, etc. bokeh.plotting.f
4 min read
bokeh.plotting.figure.circle_cross() function in Python
Bokeh is a data visualization library in Python that provides high-performance interactive charts and plots and the output can be obtained in various mediums like notebook, html and server. The Figure Class create a new Figure for plotting. It is a subclass of Plot that simplifies plot creation with default axes, grids, tools, etc. bokeh.plotting.f
4 min read
bokeh.plotting.figure.annular_wedge() function in Python
Bokeh is a data visualization library in Python that provides high-performance interactive charts and plots and the output can be obtained in various mediums like notebook, html and server. The Figure Class create a new Figure for plotting. It is a subclass of Plot that simplifies plot creation with default axes, grids, tools, etc. bokeh.plotting.f
4 min read
bokeh.plotting.figure.arc() function in Python
Bokeh is a data visualization library in Python that provides high-performance interactive charts and plots and the output can be obtained in various mediums like notebook, html and server. The Figure Class create a new Figure for plotting. It is a subclass of Plot that simplifies plot creation with default axes, grids, tools, etc. bokeh.plotting.f
4 min read
bokeh.plotting.figure.asterisk() function in Python
Bokeh is a data visualization library in Python that provides high-performance interactive charts and plots and the output can be obtained in various mediums like notebook, html and server. The Figure Class create a new Figure for plotting. It is a subclass of Plot that simplifies plot creation with default axes, grids, tools, etc. bokeh.plotting.f
4 min read
bokeh.plotting.figure.bezier() function in Python
Bokeh is a data visualization library in Python that provides high-performance interactive charts and plots and the output can be obtained in various mediums like notebook, html and server. The Figure Class create a new Figure for plotting. It is a subclass of Plot that simplifies plot creation with default axes, grids, tools, etc. bokeh.plotting.f
4 min read
bokeh.plotting.figure.circle() function in Python
Bokeh is a data visualization library in Python that provides high-performance interactive charts and plots and the output can be obtained in various mediums like notebook, html and server. The Figure Class create a new Figure for plotting. It is a subclass of Plot that simplifies plot creation with default axes, grids, tools, etc. bokeh.plotting.f
4 min read
bokeh.plotting.figure.circle_x() function in Python
Bokeh is a data visualization library in Python that provides high-performance interactive charts and plots and the output can be obtained in various mediums like notebook, html and server. The Figure Class create a new Figure for plotting. It is a subclass of Plot that simplifies plot creation with default axes, grids, tools, etc. bokeh.plotting.f
4 min read