Python Bokeh - making a pie chart
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 pie chart?
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.
Real-life application
Pie charts are commonly used in research work and project tracking to get the status and result ratios at a glance.
Required imports
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 thepifor 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 importoutput_fileandsavemethods.bokeh.palettes:To assign a color palette to the chart to improve its visual appearance. There are various available themes we useColorblindto improve interface accessibility.bokeh.plotting:To create and customize plots without working directly with the lower-level Bokeh models. We specifically importfigureandshowmethods 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 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)Code explanation
Lines 1–6: Import all the necessary libraries and modules.
Lines 9–16: Create a dictionary named
genrewith the movie genres as a key and their audience per day as the value.Line 20: Create a series
datausingpandasand assign each genre key as anindexand the corresponding audience count as value to it. Werename()the data columns tomovieandvalue.Line 21: Calculate the angles for each
genrekey 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
genredictionary 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 genre , its count and its angle.
Lines 34–41: Create the pie slices using
wedge(), define the properties, and set the source.xandyare the center coordinates of the chart.radiussets the radius of 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 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.htmlto specify the endpoint where the plot will appear and useshow()to display the created plot.
Code output
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.
Common query
The angle values in the above code are in radians. How can I convert them to degree format?
Free Resources