I use a LinearColorMapper in Bokeh 2.3.0 to map values to certain colors in my plot. Nothing fancy, as shown in the minimal working example:
import pandas as pd
from bokeh.plotting import figure, curdoc
from bokeh.models import ColumnDataSource, LinearColorMapper
from bokeh.layouts import layout
plot1 = figure(plot_width=1000, plot_height=250)
df = pd.DataFrame({"ID":[0, 1, 2, 3, 4, 5, 6, 7],
"Value1":[0, 100, 200, 300, 400, 500, 600, 700],
"Color": [0, 1, 0, 1, 2, 2, 3, 3] # Those somehow correspond to the categories, but will change during runtime
})
source = ColumnDataSource(df)
possible_categories = ["A", "B", "C", "D"]
cmap = LinearColorMapper(palette="Turbo256", low = 0, high = len(possible_categories))
circle = plot1.circle(x='ID', y='Value1', source=source,
fill_color={"field":'Color', "transform":cmap},
line_color={"field":'Color', "transform":cmap})
layout_ = layout([[plot1]])
curdoc().add_root(layout_)
But I wonder if there is a possibility to 'manually' access the colors directly from the cmap that I created? I would like to pass a value to the cmap and get the color or Hex-Color-Code or something similar back. Somehow like this (which of course does not work, but illustrates the idea):
for categ, num in enumerate(possible_categories):
color = cmap.get_colorcode_to_the_following_value(num)
print(f"Color of Category {possible_categories[categ]}: {color}")
with the output:
Color of Category A: ColorCodeXXX
Color of Category B: ColorCodeXXX
Color of Category C: ColorCodeXXX
Color of Category D: ColorCodeXXX
I´m sure this somehow works, but I extensively looked up the reference of Bokeh and did not find anything like this.
The color mapping done by LinearColorMapper is actually performed on the JavaScript side, in the browser. The information is never computed or available in Python. If you require this information, you would need to map and set the colors on the glyph manually, without using Bokeh's LinearColorMapper.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With