8 Tips for Creating Data Visualizations in Python using Bokeh¶

Author: Payal Patel¶

Import Libraries¶

In [1]:
import numpy as np
import pandas as pd
import bokeh
from bokeh.plotting import figure, output_file, show

# Needed for output_notebook / inline notebook data viz 
from bokeh.io import output_notebook, show
from bokeh.resources import INLINE

# Needed for scatterplot markers
from bokeh.transform import factor_cmap, factor_mark
import warnings
warnings.filterwarnings('ignore')

from bokeh.models import BasicTickFormatter, Label, Title, NumeralTickFormatter

# Needed to add a hover tool 
from bokeh.models.tools import HoverTool

# Needed for bar chart legend example 
from bokeh.models import Legend
from bokeh.models import Range1d

# Needed to create tabs
from bokeh.models.widgets import Tabs, Panel
In [2]:
output_notebook(resources=INLINE)
Loading BokehJS ...

California Wildfires Line Graph¶

This section shows how to create a line graph displaying the total acres burned by county in California from 2013 to 2019.

Dataset Used: https://www.kaggle.com/datasets/ananthu017/california-wildfire-incidents-20132020¶

Highlights / Features Implemented:¶

- Formatted Titles & Axes 
- Interactive Legend  
- Gridline Removal 
- Hover Tool  
In [3]:
caliWildfires = pd.read_csv('California_Fire_Incidents.csv')
In [4]:
caliWildfires.head()
Out[4]:
AcresBurned Active AdminUnit AirTankers ArchiveYear CalFireIncident CanonicalUrl ConditionStatement ControlStatement Counties ... SearchKeywords Started Status StructuresDamaged StructuresDestroyed StructuresEvacuated StructuresThreatened UniqueId Updated WaterTenders
0 257314.0 False Stanislaus National Forest/Yosemite National Park NaN 2013 True /incidents/2013/8/17/rim-fire/ NaN NaN Tuolumne ... Rim Fire, Stanislaus National Forest, Yosemite... 2013-08-17T15:25:00Z Finalized NaN NaN NaN NaN 5fb18d4d-213f-4d83-a179-daaf11939e78 2013-09-06T18:30:00Z NaN
1 30274.0 False USFS Angeles National Forest/Los Angeles Count... NaN 2013 True /incidents/2013/5/30/powerhouse-fire/ NaN NaN Los Angeles ... Powerhouse Fire, May 2013, June 2013, Angeles ... 2013-05-30T15:28:00Z Finalized NaN NaN NaN NaN bf37805e-1cc2-4208-9972-753e47874c87 2013-06-08T18:30:00Z NaN
2 27531.0 False CAL FIRE Riverside Unit / San Bernardino Natio... NaN 2013 True /incidents/2013/7/15/mountain-fire/ NaN NaN Riverside ... Mountain Fire, July 2013, Highway 243, Highway... 2013-07-15T13:43:00Z Finalized NaN NaN NaN NaN a3149fec-4d48-427c-8b2c-59e8b79d59db 2013-07-30T18:00:00Z NaN
3 27440.0 False Tahoe National Forest NaN 2013 False /incidents/2013/8/10/american-fire/ NaN NaN Placer ... American Fire, August 2013, Deadwood Ridge, Fo... 2013-08-10T16:30:00Z Finalized NaN NaN NaN NaN 8213f5c7-34fa-403b-a4bc-da2ace6e6625 2013-08-30T08:00:00Z NaN
4 24251.0 False Ventura County Fire/CAL FIRE NaN 2013 True /incidents/2013/5/2/springs-fire/ Acreage has been reduced based upon more accur... NaN Ventura ... Springs Fire, May 2013, Highway 101, Camarillo... 2013-05-02T07:01:00Z Finalized 6.0 10.0 NaN NaN 46731fb8-3350-4920-bdf7-910ac0eb715c 2013-05-11T06:30:00Z 11.0

5 rows × 40 columns

In [5]:
# Subset Dataset
caliWildfires = caliWildfires[['ArchiveYear', 'Counties', 'AcresBurned']]
In [6]:
# Generate Dataframes for Specific Counties
caliWildfiresSanBernardino = caliWildfires[caliWildfires['Counties'] == 'San Bernardino'] 
caliWildfiresSanBernardino_sum = pd.DataFrame(caliWildfiresSanBernardino.groupby('ArchiveYear')['AcresBurned'].sum())
caliWildfiresSanBernardino_sum.rename(columns={'AcresBurned':'San Bernardino'}, inplace=True)

caliWildfiresLA = caliWildfires[caliWildfires['Counties'] == 'Los Angeles'] 
caliWildfiresLA_sum = pd.DataFrame(caliWildfiresLA.groupby('ArchiveYear')['AcresBurned'].sum())
caliWildfiresLA_sum.rename(columns={'AcresBurned':'Los Angeles'}, inplace=True)

caliWildfiresSanDiego = caliWildfires[caliWildfires['Counties'] == 'San Diego'] 
caliWildfiresSanDiego_sum = pd.DataFrame(caliWildfiresSanDiego.groupby('ArchiveYear')['AcresBurned'].sum())
caliWildfiresSanDiego_sum.rename(columns={'AcresBurned':'San Diego'}, inplace=True)

caliWildfiresOrange = caliWildfires[caliWildfires['Counties'] == 'Orange'] 
caliWildfiresOrange_sum = pd.DataFrame(caliWildfiresOrange.groupby('ArchiveYear')['AcresBurned'].sum())
caliWildfiresOrange_sum.rename(columns={'AcresBurned':'Orange'}, inplace=True)

caliWildfiresSB = caliWildfires[caliWildfires['Counties'] == 'Santa Barbara'] 
caliWildfiresSB_sum = pd.DataFrame(caliWildfiresSB.groupby('ArchiveYear')['AcresBurned'].sum())
caliWildfiresSB_sum.rename(columns={'AcresBurned':'Santa Barbara'}, inplace=True)

caliWildfiresSC = caliWildfires[caliWildfires['Counties'] == 'Santa Clara'] 
caliWildfiresSC_sum = pd.DataFrame(caliWildfiresSC.groupby('ArchiveYear')['AcresBurned'].sum())
caliWildfiresSC_sum.rename(columns={'AcresBurned':'Santa Clara'}, inplace=True)
In [7]:
# Combine dataframes
caliWildfires = pd.concat([caliWildfiresLA_sum, caliWildfiresSanDiego_sum, caliWildfiresOrange_sum,
                          caliWildfiresSB_sum, caliWildfiresSC_sum, caliWildfiresSanBernardino_sum], axis=1)

caliWildfires = caliWildfires.reset_index(level=0)
caliWildfires['ArchiveYear'] = caliWildfires['ArchiveYear'].astype(str)
In [8]:
# View combined dataset
caliWildfires
Out[8]:
ArchiveYear Los Angeles San Diego Orange Santa Barbara Santa Clara San Bernardino
0 2013 31503.0 13771.0 40.0 2154.0 90.0 1850.0
1 2014 2416.0 26315.0 968.0 632.0 205.0 2191.0
2 2015 1289.0 2373.0 214.0 284.0 257.0 35883.0
3 2016 11488.0 9115.0 197.0 52813.0 4738.0 44454.0
4 2017 31190.0 10156.0 11879.0 301035.0 639.0 4065.0
5 2018 102232.0 2205.0 23466.0 1804.0 756.0 1820.0
6 2019 14462.0 1459.0 NaN 3846.0 859.0 634.0
In [9]:
# Plot Line Graph

TOOLTIPS = "pan, wheel_zoom, box_zoom, box_select,reset, save" # the tools you want to add to your graph

x = list(caliWildfires['ArchiveYear'])
y = list(caliWildfires['Los Angeles'])
y2 = list(caliWildfires['San Diego'])
y3 = list(caliWildfires['Orange'])
y4 = list(caliWildfires['Santa Barbara'])
y5 = list(caliWildfires['Santa Clara'])
y6 = list(caliWildfires['San Bernardino'])


# Create Figure 
p = figure(x_range = x, title = 'California Wildfires Total Acres Burned by County - 2013 to 2019', 
           x_axis_label='Year', y_axis_label='Total Acres Burned')
l1 = p.line(x,y,legend_label='Los Angeles', color='blue', line_width = 2, muted_color='gray', muted_alpha=0.2)
l2 = p.line(x,y2, legend_label='San Diego', color='green', line_width = 2, muted_color='gray', muted_alpha=0.2)
l3 = p.line(x,y3, legend_label='Orange', color='orange', line_width = 2, muted_color='gray', muted_alpha=0.2)
l4 = p.line(x,y4, legend_label='Santa Barbara', color='midnightblue', line_width = 2, muted_color='gray', muted_alpha=0.2)
l5 = p.line(x,y5, legend_label='Santa Clara', color='gold', line_width = 2, muted_color='gray', muted_alpha=0.2)
l6 = p.line(x,y6, legend_label='San Bernardino', color='sienna', line_width = 2, muted_color='gray', muted_alpha=0.2)



# Adjust Figure Size
p.plot_height=400
p.plot_width=800

# Adjust title and axis fonts
p.title.text_font_size = '18pt'
p.title.align = 'center'


# Modify X & Y Axes 
p.xaxis.axis_label_text_font_size = "12pt"
p.yaxis.axis_label_text_font_size = "12pt"
p.axis.axis_label_text_font_style='bold'
#p.yaxis.formatter = BasicTickFormatter(use_scientific=False)
p.yaxis[0].formatter = NumeralTickFormatter(format="0,0")


# Format Legend 
p.legend.click_policy="mute"
p.legend.title = 'County'
# labelcolor='linecolor'
# p.legend.label_text_color = "blue"

# Hide gridlines
#p.xgrid.grid_line_color = None
#p.ygrid.grid_line_color = None


#p.yaxis.ticker = [1000000, 2000000, 3000000, 4000000, 5000000, 6000000, 7000000]
p.yaxis.major_label_overrides = {50000: '50K', 100000: '100K', 150000: '150K', 
                                200000: '200K', 250000: '250K', 300000: '300K'}

# Add hover text
TOOLTIPS = [('Year', "@x"),
            ('Acres Burned', '@y{0,0}')] 

# p.add_tools(HoverTool(tooltips="Month: @x,  y: @y", renderers=[l1,l2], mode="vline"))
p.add_tools(HoverTool(tooltips=TOOLTIPS, 
                      renderers=[l1,l2,l3,l4,l5, l6]
                      ))

show(p)

Average Chocolate Ratings Bar Graph¶

This section shows how to create a bar graph displaying the average chocolate rating by country.

Dataset Used: https://www.kaggle.com/datasets/andrewmvd/chocolate-ratings¶

Highlights / Features Implemented:¶

- Formatted Titles & Axes 
- Legend outside frame/figure 
- Gridline Removal 
- Hover Tool / Tooltip
In [10]:
# Import Dataset
cacao = pd.read_csv('flavors_of_cacao.csv')
In [11]:
# View dataset
cacao.head()
Out[11]:
Company \n(Maker-if known) Specific Bean Origin\nor Bar Name REF Review\nDate Cocoa\nPercent Company\nLocation Rating Bean\nType Broad Bean\nOrigin
0 A. Morin Agua Grande 1876 2016 63% France 3.75 Sao Tome
1 A. Morin Kpime 1676 2015 70% France 2.75 Togo
2 A. Morin Atsane 1676 2015 70% France 3.00 Togo
3 A. Morin Akata 1680 2015 70% France 3.50 Togo
4 A. Morin Quilla 1704 2015 70% France 3.50 Peru
In [12]:
# Subset dataset where Nationality is England, French, Spanish or German. and include Age column. 
ques1_ds = cacao[['Company\nLocation', 'Rating']]
ques1_ds = ques1_ds.loc[ques1_ds['Company\nLocation'].isin(['Switzerland', 'U.S.A.', 'U.K.', 'Germany', 'Belgium'])]

# groupby nationality 
ques1_ds = pd.DataFrame(ques1_ds.groupby('Company\nLocation')['Rating'].mean().round(decimals=2))

# reset index 
ques1_ds.reset_index(inplace=True)
ques1_ds = ques1_ds.rename(columns = {'index':'Company Location'})
In [13]:
# Plot bar graph
from bokeh.palettes import YlOrBr5

ques1_ds.sort_values('Rating', inplace=True, ascending=False)

types = ques1_ds['Company\nLocation']
values = ques1_ds['Rating']

data=dict(types=types, values=values, color=YlOrBr5)

p = figure(x_range=types,  plot_width = 700, plot_height = 400, 
           title='Average Chocolate Rating by Country', 
           x_axis_label="Country", y_axis_label="Average Rating")

# Modify Legend
p.add_layout(Legend(), 'right')
p.legend.title = "Country"

p.vbar(x='types', top='values', width=0.9, color='color', legend="types", source=data)

# Modify Chart Title 
p.title.align = "center"
p.title.text_color = "black"
p.title.text_font_size = "20px"

# Modify X & Y Axes 
p.axis.axis_label_text_font_style='bold'
p.xaxis.axis_label_text_font_size = '12pt'
p.yaxis.axis_label_text_font_size = '12pt'
p.y_range=Range1d(0, 4)

# Hide gridlines
p.xgrid.grid_line_color = None
p.ygrid.grid_line_color = None


# Add hover text 
p.add_tools(HoverTool(tooltips=[("Country", "@types"), ("Average Rating", "@values")]))


show(p)

Relationship Between Student Math and Reading Scores Scatterplot¶

This section shows how to create a bar graph displaying student math and reading scores by race.

Dataset Used: https://www.kaggle.com/datasets/whenamancodes/students-performance-in-exams¶

Highlights / Features Implemented:¶

- Formatted Titles & Axes 
- Gridline Removal 
- Hover Tool / Tooltip
- Interactive Legend (for scatterplot)
In [14]:
exams = pd.read_csv('exams.csv')
In [15]:
exams = exams.rename(columns={'math score': 'math_score', 'reading score': 'reading_score', 
                              'writing score': 'writing_score','test preparation course':'test_prep_course',
                             'race/ethnicity':'race'})
In [16]:
exams.head()
Out[16]:
gender race parental level of education lunch test_prep_course math_score reading_score writing_score
0 male group A high school standard completed 67 67 63
1 female group D some high school free/reduced none 40 59 55
2 male group E some college free/reduced none 59 60 50
3 male group B high school standard none 77 78 68
4 male group E associate's degree standard completed 78 73 68
In [17]:
exams_GA = exams[exams.race == 'group A']
exams_GB = exams[exams.race == 'group B']
exams_GC = exams[exams.race == 'group C']
exams_GD = exams[exams.race == 'group D']
exams_GE = exams[exams.race == 'group E']
In [18]:
# Create scatterplot 
TOOLS = "pan, wheel_zoom, box_zoom, box_select,reset, save" # the tools you want to add to your graph


# Create a blank figure with necessary arguments
r = figure(plot_width=600, plot_height=500,
           title="Relationship Between Student Math and Reading Scores by Race", 
           tools = TOOLS)



r.circle('math_score','reading_score',source=exams_GA,fill_alpha=0.4, size=7, color = 'royalblue', legend_label='group A',
         muted_color='gray', muted_alpha=0.2)
r.circle('math_score','reading_score',source=exams_GB,fill_alpha=0.4, size=7, color = 'orange', legend_label='group B',
         muted_color='gray', muted_alpha=0.2)
r.circle('math_score','reading_score',source=exams_GC,fill_alpha=0.4, size=7, color = 'hotpink',legend_label='group C',
         muted_color='gray', muted_alpha=0.2)
r.circle('math_score','reading_score',source=exams_GD,fill_alpha=0.4, size=7, color = 'mediumpurple',legend_label='group D',
         muted_color='gray', muted_alpha=0.2)
r.circle('math_score','reading_score',source=exams_GE,fill_alpha=0.4, size=7, color = 'gold',legend_label='group E',
         muted_color='gray', muted_alpha=0.2)

# Examples of other shape alternatives
#r.triangle('math_score','reading_score',source=exams_GE,fill_alpha=0.4, size=7, color = 'gold',legend_label='group E',
#         muted_color='gray', muted_alpha=0.2)
#r.square('math_score','reading_score',source=exams_GE,fill_alpha=0.4, size=7, color = 'gold',legend_label='group E',
#         muted_color='gray', muted_alpha=0.2)

#Adjust title and axis fonts
r.title.text_font_size = '12pt'
r.title.align = 'center'


# Modify X & Y Axes 
r.axis.axis_label_text_font_style='bold'
r.xaxis.axis_label_text_font_size = "12pt"
r.yaxis.axis_label_text_font_size = "12pt"
r.xaxis.axis_label = 'Math Score'
r.yaxis.axis_label = 'Reading Score'

# Add legend 
r.legend.location = "bottom_right"
r.legend.title="Race"
r.legend.label_text_color = "Black"


r.legend.click_policy="mute"

# Hide gridlines
r.xgrid.grid_line_color = None
r.ygrid.grid_line_color = None


# Add Tooltip 
hover = HoverTool()
hover.tooltips=[
    ('Race/Ethnicity', "@race"),
    ('Math Score', "@math_score"),
    ('Reading Score', "@reading_score")
]

r.add_tools(hover)

# Show the figure
show(r) 
In [19]:
# Create scatterplot

x = exams["math_score"]
y = exams["reading_score"]
TOOLS = "pan, wheel_zoom, box_zoom, box_select,reset, save" # the tools you want to add to your graph


# Create a blank figure with necessary arguments
r = figure(plot_width=600, plot_height=500,
           title="Relationship Between Student Math and Reading Scores by Race", 
           tools = TOOLS)


RACE = ['group A', 'group B', 'group C', 'group D', 'group E']
MARKERS = ['triangle', 'circle', 'square', 'plus', 'hex']


# Call a glyph method as needed on the figure
r.scatter("math_score", "reading_score", source=exams, size=5, fill_alpha=0.5, muted_color='gray', muted_alpha=0.2,
         marker=factor_mark('race', MARKERS, RACE),
         color=factor_cmap('race', 'Colorblind5', RACE),
         legend_field="race"
        ) 

#Adjust title and axis fonts
r.title.text_font_size = '12pt'
r.title.align = 'center'


# Modify X & Y Axes 
r.axis.axis_label_text_font_style='bold'
r.xaxis.axis_label_text_font_size = "12pt"
r.yaxis.axis_label_text_font_size = "12pt"
r.xaxis.axis_label = 'Math Score'
r.yaxis.axis_label = 'Reading Score'

# Add legend 
r.legend.title="Race"
r.legend.label_text_color = "Black"
r.legend.location = "bottom_right"

r.legend.click_policy="mute"

# Hide gridlines
r.xgrid.grid_line_color = None
r.ygrid.grid_line_color = None


# Add Tooltip 
hover = HoverTool()
hover.tooltips=[
    ('Race/Ethnicity', "@race"),
    ('Math Score', "@math_score"),
    ('Reading Score', "@reading_score")
]

r.add_tools(hover)


# Show the figure
show(r) 
In [20]:
# Create scatterplot 
TOOLS = "pan, wheel_zoom, box_zoom, box_select,reset, save" # the tools you want to add to your graph

# Create a blank figure with necessary arguments
p = figure(plot_width=600, plot_height=500,
           title="Relationship Between Student Math and Reading Scores by Gender", 
           tools = TOOLS)

GENDER = ['female', 'male']
MARKERS = ['triangle', 'circle']

# Call a glyph method as needed on the figure
p.scatter("math_score", "reading_score", source=exams, size=5, fill_alpha=0.5,
         marker=factor_mark('gender', MARKERS, GENDER),
         color=factor_cmap('gender', 'Colorblind4', GENDER),
         legend_field="gender"
        ) 

#Adjust title and axis fonts
p.title.text_font_size = '12pt'
p.title.align = 'center'


# Modify X & Y Axes 
p.axis.axis_label_text_font_style='bold'
p.xaxis.axis_label_text_font_size = "12pt"
p.yaxis.axis_label_text_font_size = "12pt"
p.xaxis.axis_label = 'Math Score'
p.yaxis.axis_label = 'Reading Score'

# Add legend 
p.legend.title="Gender"
p.legend.label_text_color = "Black"
p.legend.location = "bottom_right"

# Hide gridlines
p.xgrid.grid_line_color = None
p.ygrid.grid_line_color = None


# Add Tooltip 
hover = HoverTool()
hover.tooltips=[
    ('Gender', "@gender"),
    ('Math Score', "@math_score"),
    ('Reading Score', "@reading_score")
]

p.add_tools(hover)

# Show the figure
show(p) 
In [21]:
# Create tab panel for scatterplot visualizations

# Create the two panels 

tab1 = Panel(child = p, title = 'Student Math and Reading Scores by Gender')
tab2 = Panel(child = r, title = 'Student Math and Reading Scores by Race')
#tab3 = Panel(child = (r), title = 'Add Additional Tab') 
#tab4 = Panel(child = (b), title = 'Add Additional Tab')

# Feed the tabs into a Tabs object
tabs_object = Tabs(tabs = [tab1, tab2])

# Output the plot
# output_file('tab_layout.html')

show(tabs_object)

Average Salary by Experience Level Bar Graph¶

This section shows how to create a bar graph displaying the average salary by experience level for various data science professionals.

Dataset Used: https://www.kaggle.com/datasets/saurabhshahane/data-science-jobs-salaries¶

Highlights / Features Implemented:¶

- Formatted Titles & Axes 
- Gridline Removal 
- Hover Tool / Tooltip
In [22]:
salaries = pd.read_csv('Data Science Jobs Salaries.csv')
In [23]:
salaries.head()
Out[23]:
work_year experience_level employment_type job_title salary salary_currency salary_in_usd employee_residence remote_ratio company_location company_size
0 2021e EN FT Data Science Consultant 54000 EUR 64369 DE 50 DE L
1 2020 SE FT Data Scientist 60000 EUR 68428 GR 100 US L
2 2021e EX FT Head of Data Science 85000 USD 85000 RU 0 RU M
3 2021e EX FT Head of Data 230000 USD 230000 RU 50 RU L
4 2021e EN FT Machine Learning Engineer 125000 USD 125000 US 100 US S
In [24]:
# Rename values in Experience-Level column
salaries['experience_level'] = salaries['experience_level'].replace('EN','Entry-level')
salaries['experience_level'] = salaries['experience_level'].replace('SE','Senior-level')
salaries['experience_level'] = salaries['experience_level'].replace('EX','Executive-level')
salaries['experience_level'] = salaries['experience_level'].replace('MI','Mid-level')
In [25]:
# Subset dataset where Nationality is England, French, Spanish or German. and include Age column. 
salaries = salaries[['experience_level', 'salary_in_usd']]
#ques1_ds = ques1_ds.loc[ques1_ds['Company\nLocation'].isin(['Switzerland', 'U.S.A.', 'U.K.', 'Germany', 'Belgium'])]

# groupby nationality 
salaries = pd.DataFrame(salaries.groupby('experience_level')['salary_in_usd'].mean().round(decimals=2))

# reset index 
salaries.reset_index(inplace=True)
salaries = salaries.rename(columns = {'index':'Experience Level'})
In [26]:
# View dataset
salaries
Out[26]:
experience_level salary_in_usd
0 Entry-level 59753.46
1 Executive-level 226288.00
2 Mid-level 85738.14
3 Senior-level 128841.30
In [27]:
# Create bar graph
from bokeh.palettes import Pastel1_5

salaries.sort_values('salary_in_usd', inplace=True, ascending=False)

types = salaries['experience_level']
values = salaries['salary_in_usd']

data=dict(types=types, values=values, color=Pastel1_5)

p = figure(x_range=types,  plot_width = 700, plot_height = 400, 
           title='Average Salary by Experience Level', 
           x_axis_label="Experience Level", y_axis_label="Average Salary (in USD)")

# Format legend
p.add_layout(Legend(), 'right')
p.legend.title = "Experience Level"

p.vbar(x='types', top='values', width=0.9, color='color', legend="types", source=data)

# Modify Chart Title 
p.title.align = "center"
p.title.text_color = "black"
p.title.text_font_size = "20px"

# Modify X & Y Axes 
p.axis.axis_label_text_font_style='bold'
p.xaxis.axis_label_text_font_size = '12pt'
p.yaxis.axis_label_text_font_size = '12pt'
p.y_range=Range1d(0, 250000)

# Hide gridlines
p.xgrid.grid_line_color = None
p.ygrid.grid_line_color = None


# Add hover text 
p.add_tools(HoverTool(tooltips=[("Experience Level", "@types"), 
                                ("Average Salary (USD)", "$@values{0,0}")]))

# Remove scientific notation
p.yaxis[0].formatter = NumeralTickFormatter(format="0,0")

# Format Y Axis Labels 
p.yaxis.ticker = [0, 50000, 100000, 150000, 200000, 250000]
p.yaxis.major_label_overrides = {0: '0K', 50000: '50K', 100000: '100K', 150000: '150K', 
                                200000: '200K', 250000: '250K'}


# Show figure 
show(p)

Color Palettes¶

Highlights:¶

- View available color palettes
- Print colors in color palette
In [28]:
# View names of color palettes available  
bokeh.palettes.all_palettes.keys()
Out[28]:
dict_keys(['YlGn', 'YlGnBu', 'GnBu', 'BuGn', 'PuBuGn', 'PuBu', 'BuPu', 'RdPu', 'PuRd', 'OrRd', 'YlOrRd', 'YlOrBr', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds', 'Greys', 'PuOr', 'BrBG', 'PRGn', 'PiYG', 'RdBu', 'RdGy', 'RdYlBu', 'Spectral', 'RdYlGn', 'Accent', 'Dark2', 'Paired', 'Pastel1', 'Pastel2', 'Set1', 'Set2', 'Set3', 'Category10', 'Category20', 'Category20b', 'Category20c', 'Colorblind', 'Magma', 'Inferno', 'Plasma', 'Viridis', 'Cividis', 'Turbo', 'Bokeh'])
In [29]:
# View all color palettes available
# bokeh.palettes.all_palettes
In [30]:
# View available sizes for a specific color palette 
bokeh.palettes.all_palettes['Set3']
Out[30]:
{3: ('#8dd3c7', '#ffffb3', '#bebada'),
 4: ('#8dd3c7', '#ffffb3', '#bebada', '#fb8072'),
 5: ('#8dd3c7', '#ffffb3', '#bebada', '#fb8072', '#80b1d3'),
 6: ('#8dd3c7', '#ffffb3', '#bebada', '#fb8072', '#80b1d3', '#fdb462'),
 7: ('#8dd3c7',
  '#ffffb3',
  '#bebada',
  '#fb8072',
  '#80b1d3',
  '#fdb462',
  '#b3de69'),
 8: ('#8dd3c7',
  '#ffffb3',
  '#bebada',
  '#fb8072',
  '#80b1d3',
  '#fdb462',
  '#b3de69',
  '#fccde5'),
 9: ('#8dd3c7',
  '#ffffb3',
  '#bebada',
  '#fb8072',
  '#80b1d3',
  '#fdb462',
  '#b3de69',
  '#fccde5',
  '#d9d9d9'),
 10: ('#8dd3c7',
  '#ffffb3',
  '#bebada',
  '#fb8072',
  '#80b1d3',
  '#fdb462',
  '#b3de69',
  '#fccde5',
  '#d9d9d9',
  '#bc80bd'),
 11: ('#8dd3c7',
  '#ffffb3',
  '#bebada',
  '#fb8072',
  '#80b1d3',
  '#fdb462',
  '#b3de69',
  '#fccde5',
  '#d9d9d9',
  '#bc80bd',
  '#ccebc5'),
 12: ('#8dd3c7',
  '#ffffb3',
  '#bebada',
  '#fb8072',
  '#80b1d3',
  '#fdb462',
  '#b3de69',
  '#fccde5',
  '#d9d9d9',
  '#bc80bd',
  '#ccebc5',
  '#ffed6f')}
In [31]:
# Import Specific Color Palette - Specific Size 
from bokeh.palettes import Set3_3
from bokeh.palettes import Spectral6

# Import Color Palette - All Sizes 
from bokeh.palettes import cividis
In [32]:
# View HEX colors in a color palette - ex for cividis palette, size 6
cividis(6)

# View HEX colors in a color palette - ex for cividis palette, size 3
cividis(3)
Out[32]:
('#00204C', '#7B7B78', '#FFE945')
In [33]:
# Import Markdown & display - needed to create function to print color palette 
from IPython.display import Markdown, display
In [34]:
# Create function to print colors in palette 
# Option 1 - Print HEX Color & Color Block 
def printColorPalette(color_palette):
    display(Markdown('<br>'.join(
        f'<span style="color: {color}; font-family: courier;"><span>{color}: </span>&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;</span>'
        for color in color_palette
    )))
In [35]:
printColorPalette(cividis(6))

#00204C: ███████</span>
#31446B: ███████</span>
#666870: ███████</span>
#958F78: ███████</span>
#CAB969: ███████</span>
#FFE945: ███████</span>

In [36]:
printColorPalette(Set3_3)

#8dd3c7: ███████</span>
#ffffb3: ███████</span>
#bebada: ███████</span>

In [37]:
printColorPalette(Spectral6)

#3288bd: ███████</span>
#99d594: ███████</span>
#e6f598: ███████</span>
#fee08b: ███████</span>
#fc8d59: ███████</span>
#d53e4f: ███████</span>

In [38]:
# Create function to print colors in palette 

# Option 2 - Print Color Blocks Only 
def printColorPalette2(color_palette):
    display(Markdown(''.join(
        f'<span style="color: {color}">&#9608;&#9608;&#9608;</span>'
        for color in color_palette
    )))
In [39]:
printColorPalette2(cividis(6))

██████████████████