littleworth
littleworth

Reputation: 5169

How to expand limited color palette in Python's Bokeh plot

I have the following code:

from bokeh.plotting import figure, show, output_file
from bokeh.sampledata.iris import flowers  
from bokeh.models import LinearColorMapper
from bokeh.models import ColumnDataSource 
from bokeh.models import ColorBar 
from bokeh.palettes import Reds9

p = figure(title = "Iris Morphology")
p.xaxis.axis_label = "Petal Length"
p.yaxis.axis_label = "Petal Width"

source = ColumnDataSource(flowers)


# Reverse the color and map it
Reds9.reverse()
exp_cmap = LinearColorMapper(palette=Reds9, 
                             low = min(flowers["petal_length"]), 
                             high = max(flowers["petal_length"]))

p.circle("petal_length", "petal_width", source=source, line_color=None,
        fill_color={"field":"petal_length", "transform":exp_cmap})



bar = ColorBar(color_mapper=exp_cmap, location=(0,0))
p.add_layout(bar, "left")

show(p)

Which produces the following plot: enter image description here

Notice that I use Brewer's Red palette which is limited to 9 colors.

from bokeh.palettes import Reds9

How can I expand it to 256?

Upvotes: 2

Views: 2924

Answers (1)

Nic
Nic

Reputation: 3507

Bokeh's palettes are simply a list of HTML colors. You can create your own one. For example, picking the list from https://www.w3schools.com/colors/colors_shades.asp:

myReds = [
    '#000000', 
    '#080000', 
    '#100000', 
    '#180000', 
    '#200000', 
    '#280000', 
    '#300000', 
    '#380000', 
    '#400000', 
    '#480000', 
    '#500000', 
    '#580000', 
    '#600000', 
    '#680000', 
    '#700000', 
    '#780000', 
    '#800000', 
    '#880000', 
    '#900000', 
    '#980000', 
    '#A00000', 
    '#A80000', 
    '#B00000', 
    '#B80000', 
    '#C00000', 
    '#C80000', 
    '#D00000', 
    '#D80000', 
    '#E00000', 
    '#E80000', 
    '#F00000', 
    '#F80000', 
    '#FF0000']

Then replace Reds9 by myReds:

[...]
exp_cmap = LinearColorMapper(palette=myReds, 
                         low = min(flowers["petal_length"]), 
                         high = max(flowers["petal_length"]))
[...]

Upvotes: 4

Related Questions