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.
Pie charts are used to summarise nominal datasets into a circular graph to provide information at a glance. Different colors represent each sector to create an evident visual difference, and a key is provided against each color to identify the category.
Pie charts are commonly used in research work and project tracking to get the status and result ratios at a glance.
from math import piimport pandas as pdfrom bokeh.io import output_file, savefrom bokeh.palettes import Colorblindfrom bokeh.plotting import figure, showfrom bokeh.transform import cumsum
math:
To access the pi
for 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 output_file
and save
methods.
bokeh.palettes:
To assign a color palette to the chart to improve its visual appearance. There are various available themes we use Colorblind
to improve interface accessibility.
bokeh.plotting:
To create and customize plots without working directly with the lower-level Bokeh models. We specifically import figure
and show
methods from it.
bokeh.transform:
To transform the data by adding visual properties such as colors, sizes, and positions. We specifically import cumsum
to calculate the cumulative sum of the data field.
In this example, we present different movie genres corresponding to their daily audience in a pie chart illustration to show which genre is most liked.
from math import pi, degrees import pandas as pd from bokeh.palettes import Colorblind from bokeh.plotting import figure, show from bokeh.transform import cumsum from bokeh.io import output_file, save #sample dataset genre = { 'Horror': 106, 'SciFi': 126, 'Comedy': 84, 'Action': 130, 'Fantasy': 74, 'Romance': 96, 'History': 40, } #creating data data = pd.Series(genre).reset_index(name='value').rename(columns={'index': 'movie'}) data['angle'] = data['value']/data['value'].sum() * 2*pi data['color'] = Colorblind[len(genre)] #creating chart myChart = figure(height=400, width=650, title="Movie genre - liking based on the audience per day", toolbar_location=None, tools="hover", tooltips="@movie: @value, Angle: @angle{0.0}", x_range=(-0.5, 1.0)) #creating sectors myChart.wedge(x=0, y=1, radius=0.4, start_angle=cumsum('angle', include_zero=True), end_angle=cumsum('angle'), line_color="white", fill_color='color', legend_field='movie', 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)
Lines 1–6: Import all the necessary libraries and modules.
Lines 9–16: Create a dictionary named genre
with the movie genres as a key and their audience per day as the value.
Line 20: Create a series data
using pandas
and assign each genre key as an index
and the corresponding audience count as value to it. We rename()
the data columns to movie
and value
.
Line 21: Calculate the angles for each genre
key using the formula.
Note: The formula divides each genre's audience count by the sum of total audience count 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 genre
dictionary as a parameter. Assign it to color
in data
.
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 genre , its count and its angle.
Lines 34–41: Create the pie slices using wedge()
, define the properties, and set the source.
x
and y
are the center coordinates of the chart.
radius
sets the radius of the chart.
start-angle
and end-angle
are specified using cumsum
to calculate when each slice starts and ends.
line_color
specifies the border color of the pie chart.
fill_color
specifies the color assigned to each category from the color column.
legend_field
specifies the column we use for each slice label in the legend.
Lines 44–46: Clear the interface by setting the axis gridlines to none and its visibility to false.
Lines 46–47: Set the output to output.html
to specify the endpoint where the plot will appear and use show()
to display the created plot.
The pie chart is displayed at the output.html endpoint with the Colorblind
color palette to represent each wedge of the dataset.
Click here to view the donut chart variation using the same coding pattern.
The angle values in the above code are in radians. How can I convert them to degree format?
Free Resources