Donut charts with Bokeh
Bokeh is a Python library used for creating interactive visualizations in a web browser. It provides powerful tools that offer flexibility, interactivity, and scalability for exploring various data insights.
What is a donut chart?
Donut charts are a variation of pie charts used to illustrate the proportions of categorical data where the size of the segment represents the category's proportion. Different colors represent each sector to create an evident visual difference, and a key is provided against each color to identify the category.
Real-life applications
Donut charts are commonly used to compile results visually and use the segment size to monitor the value of each category.
Required imports
from math import piimport pandas as pdfrom bokeh.io import output_file, savefrom bokeh.palettes import Category10from bokeh.plotting import figure, showfrom bokeh.transform import cumsum
math:To accesspifor creating the chart.pandas:To manipulate data and create a series to hold data.bokeh.io:To control the output and display of the plots. We specifically import theoutput_fileandsavemethods.bokeh.palettes:To assign a color palette to the chart to improve its visual appearance. There are various available themes we useCategory10to improve interface accessibility.bokeh.plotting:To create and customize plots without working directly with the lower-level Bokeh models. We specifically import thefigureandshowmethods from it.bokeh.transform:To transform the data by adding visual properties such as colors, sizes, and positions. We specifically importcumsumto calculate the cumulative sum of the data field.
Example code
In this example, we present different teams corresponding to the number of votes they got in a donut chart illustration to show which team is winning.
from math import pi
import pandas as pd
from bokeh.io import output_file, save
from bokeh.palettes import Category10
from bokeh.plotting import figure, show
from bokeh.transform import cumsum
#sample dataset
elecResults = {
'Tiger team': 106,
'Lion team': 126,
'Falcon team': 84,
'Dolphin team': 130,
'Iris team': 74,
'Orchid team': 40,
'Rio team': 96,
}
#creating data
data = pd.Series(elecResults).reset_index(name='value').rename(columns={'index':'teams'})
data['angle'] = data['value']/data['value'].sum() * 2*pi
data['color'] = Category10[len(elecResults)]
#creating chart
myChart = figure(height=400,
width=650,
title="Election results - based on team votes",
toolbar_location=None,
tools="hover",
tooltips="@teams: @value, Angle: @angle{0.0}",
x_range=(-0.5, 0.5))
#creating sectors
myChart.annular_wedge(x=0, y=1,
inner_radius=0.12,
outer_radius=0.25,
direction="anticlock",
start_angle=cumsum('angle', include_zero=True),
end_angle=cumsum('angle'),
line_color="white",
fill_color='color',
legend_field='teams',
source=data)
#clearing interface
myChart.axis.axis_label=None
myChart.axis.visible=False
myChart.grid.grid_line_color = None
#displaying output
output_file("output.html")
show(myChart)Code explanation
Lines 1–6: Import all the necessary libraries and modules.
Lines 9–16: Create a dictionary named
elecResultswith the team names as a key, and their votes count as the value.Line 20: Create a series
datausingpandasand assign each election result's key as anindexand the corresponding vote count as value to it. Werename()the data columns toteamsandvalue.Line 21: Calculate the angles for each
elecResultskey using the formula.
Note: The formula divides each team's vote count by the sum of total vote counts and then multiply it with the double of pi to normalise the data values.
Line 22: Set a color palette to the chart and pass the length of the
electResultsdictionary as a parameter. Assign it tocolorindata.Lines 25–31: Create a chart figure using
figure()and define its dimensions, title, tools and tooltip properties, and range.
Note: Hover over the slices to see the team names, their votes , and angles.
Lines 34–43: Create the pie slices using
annular_wedge(), define the properties, and set the source.xandyare the center coordinates of the chart.inner_radiusandouter_radiussets both the radius of the donut chart.directionspecifies from which point to start creating the chart.start-angleandend-angleare specified usingcumsumto calculate when each slice starts and ends.line_colorspecifies the border color of the pie chart.fill_colorspecifies the color assigned to each category from the color column.legend_fieldspecifies the column we use for each slice label in the legend.
Lines 46–48: Clear the interface by setting the axis gridlines to none and its visibility to false.
Lines 51–52: Set the output to
output.htmlto specify the endpoint where the plot will appear and useshow()to display the created plot.
Code output
The donut chart is displayed at the output.html endpoint with the Category10 color palette to represent each wedge of the dataset.
Common query
How can we add the percentages of each category to tooltips?
Free Resources