问题
I need to change the color map of polygons based on a variable that the user can select. I can update the colors, but if I select one polygon with TapTool then the initial color map appears:
from bokeh.plotting import figure, curdoc
from bokeh.layouts import column, layout
from bokeh.models import ColumnDataSource, LinearColorMapper, ColorBar, BasicTicker, Select
from bokeh.palettes import Viridis256 as palette
palette.reverse()
TOOLS = "tap"
p = figure(title="Coloring Humidity", tools=TOOLS)
source = ColumnDataSource(dict(x=[[1, 3, 2], [3, 4, 6, 6]],
y=[[2, 1, 4], [4, 7, 8, 5]],
name=['A', 'B'],
humidity=[0, 1.0],
temperature=[10.0, 0.0]
)
)
color_mapper = LinearColorMapper(palette=palette, low=0, high=1)
pglyph = p.patches('x', 'y', source=source, fill_color={'field': 'humidity', 'transform': color_mapper},
alpha=1, line_width=2)
color_bar = ColorBar(color_mapper=color_mapper, label_standoff=12, border_line_color=None, location=(0, 0),
ticker=BasicTicker())
p.add_layout(color_bar, 'left')
def color_change(attr, old, new):
cm = p.select_one(LinearColorMapper)
if new == 'humidity':
cm.update(low=0, high=1.0)
elif new == 'temperature':
cm.update(low=0, high=10)
else:
raise ValueError('unknown color')
pglyph.glyph.fill_color['field'] = new
p.title.text = 'Coloring {}'.format(new.title())
select = Select(value='humidity', options=['humidity', 'temperature'])
select.on_change('value', color_change)
l = layout([
[select],
[p]
])
curdoc().add_root(l)
In this script, if I select 'temperature' in the select widget, the colors remap without problem, but if I then select one of the polygons with taptool, the color of the selected and unselected polygons go back to the color mapping of humidity. I guess i'm missing something but i can't tell what.
回答1:
I think you just have to remove the line:
pglyph.glyph.fill_color['field'] = new
Changing the low/high properties of the ColorMapper in your callback should cause the data to re-color mapped, so you shouldn't have to set the colors manually.
来源:https://stackoverflow.com/questions/43212721/updating-color-mapper-in-a-bokeh-plot-with-taptool