5 Best Ways to Use Bokeh Library for Horizontal Bar Plots in Python

Rate this post

πŸ’‘ Problem Formulation: When working with data visualization in Python, you may need to represent comparative data across categories using horizontal bar plots. Bokeh is an interactive visualization library that can make this task easier. Suppose you have structured data consisting of various categories and their corresponding values, and you want to visually display this relationship in a horizontal format for better readability and comparison. This article illustrates how to harness Bokeh’s functionalities to create horizontal bar plots effectively.

Method 1: Basic Horizontal Bar Plot

This method covers creating a basic horizontal bar plot using Bokeh’s hbar() glyph function. It allows you to produce a simple, but scalable, horizontal bar chart by specifying bar heights, coordinates, and lengths. This method is best for quick and straightforward representations of data.

Here’s an example:

from bokeh.plotting import figure, show, output_file

# Sample data
categories = ['Category A', 'Category B', 'Category C']
values = [10, 20, 30]

# Create a figure
p = figure(y_range=categories, plot_height=250)

# Add horizontal bars
p.hbar(y=categories, right=values, height=0.4)

# Show the results
output_file("horizontal_bar.html")
show(p)

Output: This code generates a horizontal bar plot with categories on the y-axis and their corresponding values represented by the length of the bars.

This example initializes the Bokeh figure with a specified y-axis range to accommodate our categories. Then, the hbar() method is used to create horizontal bars by setting the y for categories and right for corresponding values, along with the height for bar thickness. Finally, output_file() and show() functions are called to display the plot in a browser.

Method 2: Stacked Horizontal Bar Plot

Stacked Horizontal Bar Plots are useful when you need to show segmented data within each category. Bokeh’s vbar_stack() function is utilized to stack multiple datasets horizontally, allowing detailed comparison within categories.

Here’s an example:

from bokeh.models import ColumnDataSource
from bokeh.plotting import figure, show, output_file

# Sample data
data = {'categories': ['Category A', 'Category B', 'Category C'],
        'value1': [10, 20, 30],
        'value2': [15, 25, 35]}

# Creating a ColumnDataSource
source = ColumnDataSource(data=data)

# Create a figure
p = figure(y_range=data['categories'], plot_height=250)

# Add stacked horizontal bars
p.hbar_stack(stackers=['value1', 'value2'], y='categories', height=0.4, color=("grey", "lightgrey"), source=source)

# Show the results
output_file("stacked_horizontal_bar.html")
show(p)

Output: A horizontal bar plot with bars for each category, segmented into different data portions colored in grey and light grey.

In this code snippet, we create a ColumnDataSource object to hold our data, which makes it easier to reference within Bokeh. Using figure(), we define our plot and then add stacked horizontal bars by calling the hbar_stack() function, passing our different data segments and a color scheme. The plot is then rendered with output_file() and displayed using show().

Method 3: Customized Horizontal Bar Chart with Interactive Tools

This method involves adding interactive elements to a horizontal bar plot to enhance data visualization. Customizations can include tools for zooming, panning, and hover tooltips using Bokeh’s built-in features.

Here’s an example:

from bokeh.models import HoverTool
from bokeh.plotting import figure, show, output_file

# Sample data
categories = ['Category A', 'Category B', 'Category C']
values = [10, 20, 30]

# Create a figure with interactive tools
p = figure(y_range=categories, plot_height=250, tools="pan,box_zoom,reset")

# Add horizontal bars
p.hbar(y=categories, right=values, height=0.4)

# Add hover tool
hover = HoverTool()
hover.tooltips = [("Category", "@y"), ("Value", "@right")]
p.add_tools(hover)

# Show the results
output_file("interactive_horizontal_bar.html")
show(p)

Output: This code creates an interactive horizontal bar plot that displays a hover tooltip with category and value information on mouseover, alongside tools for panning and zooming.

By specifying the tools parameter in the figure() function, we enable the pan and zoom capabilities. We then create a HoverTool object with customized tooltips that display the value and category of each bar when hovered over. The final plot is interactive, providing a more informative and engaging user experience.

Method 4: Horizontal Bar Plot with Categorical Data Sorting

Sorting data in a horizontal bar plot can provide clearer insights, particularly when comparing the magnitude of values across categories. Bokeh allows sorting within the figure() function by adjusting the y_range to sort categories based on the data values.

Here’s an example:

from bokeh.models import FactorRange
from bokeh.plotting import figure, show, output_file

# Sample data sorted
categories = ['Category C', 'Category B', 'Category A']
values = [30, 20, 10]

# Sort the categories based on values
sorted_categories = sorted(zip(values, categories), reverse=True)
sorted_categories = [category for _, category in sorted_categories]

# Create a figure with sorted categories
p = figure(y_range=FactorRange(*sorted_categories), plot_height=250)

# Add horizontal bars
p.hbar(y=sorted_categories, right=values, height=0.4)

# Show the results
output_file("sorted_horizontal_bar.html")
show(p)

Output: A horizontal bar plot where categories are sorted in descending order based on their associated values, from top to bottom.

We initiate the process by sorting our categorical data with their values and then passing the sorted categories to the FactorRange within the figure() function call. The horizontal bars are added accordingly, and the resulting plot is displayed with sorted categories, making it easy to compare the magnitude of the corresponding values at a glance.

Bonus One-Liner Method 5: Horizontal Bar Plot with Inverted Axis

Sometimes inverting the axes in a horizontal bar plot can offer a fresh perspective or better fit the layout of a presentation. With Bokeh, you can quickly invert the axes using the invert_axis() method.

Here’s an example:

from bokeh.plotting import figure, show, output_file

# Sample data
categories = ['Category A', 'Category B', 'Category C']
values = [10, 20, 30]

# Create a figure and invert the axis
p = figure(y_range=categories, plot_height=250)
p.hbar(y=categories, right=values, height=0.4)
p.y_range.flipped = True

# Show the results
output_file("inverted_axis_horizontal_bar.html")
show(p)

Output: A horizontal bar plot with an inverted y-axis, presenting the categories in reverse order.

This code snippet is a quick way to flip the y-axis by setting p.y_range.flipped to True. The method maintains all the functionality of a standard horizontal bar plot while presenting data in an inverted fashion, which may be useful for certain datasets or visual preferences. The plot generated will be presented with the categories in reverse order as defined by the axis inversion.

Summary/Discussion

  • Method 1: Basic Horizontal Bar Plot. Effective for simple and clear visualizations. Does not handle complex data representations and lacks interactivity.
  • Method 2: Stacked Horizontal Bar Plot. Ideal for showcasing segmented data within categories. May become cluttered with too many segments or categories.
  • Method 3: Customized Interactive Bar Chart. Enhances user engagement with added interactivity. Requires additional setup for tools and can be overkill for straightforward data.
  • Method 4: Horizontal Bar Plot with Sorted Data. Eases comparison across categories. Relies on pre-sorting data and is less dynamic in visual representation.
  • Method 5: Horizontal Bar Plot with Inverted Axis. Offers an alternative perspective. Might confuse users expecting the standard orientation.