Plotting in Bokeh

Greetings! Some links on this site are affiliate links. That means that, if you choose to make a purchase, The Click Reader may earn a small commission at no extra cost to you. We greatly appreciate your support!

A Bokeh Line plot can be created simply by following these steps:

  • Create a blank figure with necessary arguments: p = figure(…)
  • Call a glyph method such as p.line on the figure
  • Show the figure
#line plot Example with BoxAnnotation usage

#Importing necessary modules
from bokeh.models import BoxAnnotation #for highlighting

#Preparing the plot data
#Taking gulcose data from bokeh sample data
from bokeh.sampledata.glucose import data 
week=data.loc['2010-10-01':'2010-10-08'] #taking one week data
x=week.index
y=week.glucose

#Create a new plot 
p = figure(x_axis_type="datetime", title="Glocose Variation", plot_height=350, plot_width=800) #note to specify x_axis type as datetime to make x axis as datatime
p.xgrid.grid_line_color=None
p.ygrid.grid_line_alpha=0.5
p.xaxis.axis_label = 'Time'
p.yaxis.axis_label = 'GulcoseValue(gm/cc)'
box_left = pd.to_datetime('2010-10-4')
box_right = pd.to_datetime('2010-10-6')

#Configure BoxAnnotation
box = BoxAnnotation(left=box_left, right=box_right,
                    line_width=1, line_color='black', line_dash='dashed',
                    fill_alpha=0.2, fill_color='orange')

#Add box layout to figure
p.add_layout(box)

#Add a line renderer
p.line(x,y,line_width=2)

#Show the results
show(p) 

OUTPUT:

Plotting in Bokeh

Scatter Plot:

Scatter plot can be created easily with the following steps:

  • Create a blank figure with necessary arguments: p = figure(…)
  • Call a glyph method such as p.circle on the figure
  • Show the figure
#Scatter plot Example

#Preparing plot data
from bokeh.sampledata.autompg import autompg 

#See relationships between horse power and acceleration 
x=autompg.hp
y=autompg.accel

# create a new plot with default tools, using figure
p = figure(plot_width=600, plot_height=400,title="Horse Power & Accleration")
p.xaxis.axis_label = 'Horse power'
p.yaxis.axis_label = 'Acceleration'

# add a circle renderer with x and y coordinates, size, color, and alpha
p.circle(x,y, size=15, line_color="navy", fill_color="orange", fill_alpha=0.5) 

# show the results
show(p) 

OUTPUT:

Plotting in Bokeh

Bar Chart:

A bar chart can be created easily with the following steps:

  • Create a blank figure with necessary arguments: p = figure(…)
  • Call a glyph method such as p.vbar on the figure
  • Show the figure
#Bar chart Example

#Importing necessary modules
from bokeh.models import ColumnDataSource
from bokeh.palettes import Spectral6

#Preparing data as pandas dataframe
gapminder_regions=pd.read_csv('https://github.com/PHI-Toolkit/docker-jupyterhub/raw/master/.bokeh/data/gapminder_regions.csv')
print(gapminder_regions.head(3))

#Data processing to find how many countries are there in each group
df = gapminder_regions.groupby('Group')['ID'].nunique() 
regions=gapminder_regions['Group'].unique()
counts=[]
print(regions)
for x in regions:
    counts.append(df[x])
print(counts)


#Set the x_range to the list of categories above
p = figure(x_range=regions, plot_height=250,plot_width=800, title="No.of Countries in Regions")

#Categorical values can also be used as coordinates
p.vbar(x=regions, top=counts, color=Spectral6,width=0.9)

#Set some properties to make the plot look better
p.xgrid.grid_line_color = None
p.y_range.start = 0

show(p)

OUTPUT:

    Country               Group  ID
0    Angola  Sub-Saharan Africa  AO
1     Benin  Sub-Saharan Africa  BJ
2  Botswana  Sub-Saharan Africa  BW
['Sub-Saharan Africa' 'South Asia' 'Middle East & North Africa' 'America'
 'Europe & Central Asia' 'East Asia & Pacific']
[50, 8, 21, 52, 66, 46]
Plotting in Bokeh
#Example of Stacked bar chart
from bokeh.palettes import GnBu3, OrRd3
years = ['2017', '2018', '2019']

fashion_items=['Jeans','Bags','Shoe','Shirt','Belt']

exports = {'fashion_items' : fashion_items,
           '2017'   : [10, 13, 22, 33, 22],
           '2018'   : [53, 36, 45, 25, 45],
           '2019'   : [34, 28, 45, 45, 54]}

imports = {'fashion_items' : fashion_items,
           '2017'   : [-20,-15 , -28, -38, -29],
           '2018'   : [-60, -39, -50, -30, -45],
           '2019'   : [-38, -29, -49, -49, -59]}

p = figure(y_range=fashion_items, plot_height=250,plot_width=800, x_range=(-500, 500), title="Fashion items import/export, by year")

p.hbar_stack(years, y='fashion_items', height=0.9, color=GnBu3, source=ColumnDataSource(exports),
             legend_label=["%s exports" % x for x in years])

p.hbar_stack(years, y='fashion_items', height=0.9, color=OrRd3, source=ColumnDataSource(imports),
             legend_label=["%s imports" % x for x in years])

p.y_range.range_padding = 0.1
p.ygrid.grid_line_color = None
p.legend.location = "center_left"

show(p)

OUTPUT:

Plotting in Bokeh
#Mixed bar chart Example

from bokeh.models import FactorRange

fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']
years = ['2015', '2016', '2017']

data = {'fruits' : fruits,
        '2015'   : [2, 1, 4, 3, 2, 4],
        '2016'   : [5, 3, 3, 2, 4, 6],
        '2017'   : [3, 2, 4, 4, 5, 3]}

# this creates [ ("Apples", "2015"), ("Apples", "2016"), ("Apples", "2017"), ("Pears", "2015), ... ]
x = [ (fruit, year) for fruit in fruits for year in years ]
counts = sum(zip(data['2015'], data['2016'], data['2017']), ()) # like an hstack

source = ColumnDataSource(data=dict(x=x, counts=counts))

p = figure(x_range=FactorRange(*x), plot_height=250, title="Fruit Counts by Year")

p.vbar(x='x', top='counts', width=0.9, source=source)

p.y_range.start = 0
p.x_range.range_padding = 0.1
p.xaxis.major_label_orientation = 1
p.xgrid.grid_line_color = None

show(p)

OUTPUT:

Plotting in Bokeh

Pie Chart:

Pie chart can be created easily with following steps:

  • Create a blank figure with necessary arguments: p = figure(…)
  • Call a glyph method such as p.wedge on the figure
  • Show the figure
#Importing necessary modules
from math import pi
from bokeh.io import output_file, show
from bokeh.palettes import Spectral6
from bokeh.plotting import figure
from bokeh.transform import cumsum

#Data preparation for plot
gapminder_regions=pd.read_csv('https://github.com/PHI-Toolkit/docker-jupyterhub/raw/master/.bokeh/data/gapminder_regions.csv')
df = gapminder_regions.groupby('Group')['ID'].nunique()
data = pd.Series(df).reset_index(name='value').rename(columns={'Group':'Regions'})
print(data)
data['angle'] = data['value']/data['value'].sum() * 2*pi
data['color'] = Spectral6

#Create necessary figure
p = figure(plot_height=350, title="World Regions by Countries", toolbar_location=None,
           tools="hover", tooltips="@Regions: @value", x_range=(-0.5, 1.0))

#Create wedge for defining pie chart
p.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='Regions', source=data)

p.axis.axis_label=None
p.axis.visible=False
p.grid.grid_line_color = None

show(p)

OUTPUT:

                      Regions  value
0                     America     52
1         East Asia & Pacific     46
2       Europe & Central Asia     66
3  Middle East & North Africa     21
4                  South Asia      8
5          Sub-Saharan Africa     50
Plotting in Bokeh

Plotting in BokehPlotting in Bokeh

Do you want to learn Python, Data Science, and Machine Learning while getting certified? Here are some best selling Datacamp courses that we recommend you enroll in:

  1. Introduction to Python (Free Course) - 1,000,000+ students already enrolled!
  2. Introduction to Data Science  in Python- 400,000+ students already enrolled!
  3. Introduction to TensorFlow for Deep Learning with Python - 90,000+ students already enrolled!
  4. Data Science and Machine Learning Bootcamp with R - 70,000+ students already enrolled!

Leave a Comment