How to retrieve data from a Bokeh ColumnDataSource ?

Published: January 09, 2024

Tags: Python; Bokeh;

DMCA.com Protection Status

Introduction

Bokeh is an interactive visualization library that allows you to create beautiful and powerful visualizations in Python. It provides various tools and features for creating dynamic and interactive data plots, graphs, and dashboards.

One of the key components of Bokeh is the ColumnDataSource, which represents a tabular or columnar dataset that can be used for visualizations.

In this article, we will learn how to retrieve data from a ColumnDataSource and utilize it for our visualization needs.

Understanding the ColumnDataSource

Before we dive into retrieving data, it's important to understand the structure of a ColumnDataSource. It is essentially a dictionary-like object that maps string names to sequences of values. These values can be lists, arrays, or other data structures that can be accessed using square bracket notation.

Let's create a simple ColumnDataSource to understand this better.

from bokeh.models import ColumnDataSource

data = {'X': [1, 2, 3, 4, 5],
        'Y': [6, 7, 2, 3, 6]}

source = ColumnDataSource(data=data)

In the above example, we have created a ColumnDataSource with two columns - 'X' and 'Y', each having five values. Now, let's see how we can retrieve data from this source.

Retrieving data from a Bokeh ColumnDataSource

If we want to retrieve all the data from our ColumnDataSource, we can simply use source.data which will return a dictionary with all the column names and their corresponding values:

source.data

Executing this code will generate

{'X': [1, 2, 3, 4, 5], 'Y': [6, 7, 2, 3, 6]}

It is important to note that

type(source.data)

is

bokeh.core.property.wrappers.PropertyValueColumnData

To convert it back into a dictionary, simply use the following code:

data_extracted = dict(source.data)

print( data_extracted )

the above code will return

{'X': [1, 2, 3, 4, 5], 'Y': [6, 7, 2, 3, 6]}

Note that now if we check the type

type(data_extracted)

we get

dict

Extract Bokeh ColumnDataSource keys

source.data.keys()

dict_keys(['X', 'Y'])

Extract data from a specific column

We cam also specify the column name within square brackets. For example, to retrieve the data in the 'X' column from our previous example, we can use

source.data['X']

This will return a list of values

[1, 2, 3, 4, 5]

References

Links Site
columndatasource docs.bokeh.org/