I have a little Bokeh plot with data points and associated text labels. What I want is for the text labels to only appear when the user selects points with the box select tool. This gets me close:
from bokeh.plotting import ColumnDataSource,figure,show
source = ColumnDataSource(
data=dict(
x=test[:,0],
y=test[:,1],
label=[unquote_plus(vocab_idx[i]) for i in range(len(test))]))
TOOLS="box_zoom,pan,reset,box_select"
p = figure(plot_width=400, plot_height=400,tools=TOOLS)
p.circle(x='x',y='y', size=10, color="red", alpha=0.25,source=source)
renderer = p.text(x='x',y='y',text='label',source=source)
renderer.nonselection_glyph.text_alpha=0.
show(p)
This is close, in that if I draw a box around some points, those text labels are shown and the rest are hidden, but the problem is that it renders all the text labels to start (which is not what I want). The initial plot should have all labels hidden, and they should only appear upon a box_select.
I thought I could start by rendering everything with alpha=0.0, and then setting a selection_glyph parameter, like this:
...
renderer = p.text(x='x',y='y',text='label',source=source,alpha=0.)
renderer.nonselection_glyph.text_alpha=0.
renderer.selection_glyph.text_alpha=1.
...
But this throws an error:
AttributeError: 'NoneType' object has no attribute 'text_alpha'
When trying to access the text_alpha attribute of selection_glyph.
I know I could use a hover effect here or similar, but need the labels to default to not being visible. An alternative, but not ideal, solution would be to have a toggle button that switches the labels on and off, but I'm not sure how to do that either.
What am I doing wrong here?
As of version 0.11.1, the value of selection_glyph is None by default. This is interpreted by BokehJS as "don't do anything different, just draw the glyph as normal". So you need to actually create a selection_glyph. There are two ways to do this, both demonstrated here:
http://docs.bokeh.org/en/latest/docs/user_guide/styling.html#selected-and-unselected-glyphs
Basically, they are
by hand
Create an actual Circle Bokeh model, something like:
selected_circle = Circle(fill_alpha=1, fill_color="firebrick", line_color=None)
renderer.selection_glyph = selected_circle
OR
using glyph method parameters
Alternatively, as a convenience Figure.circle accepts paramters like selection_fill_alpha or selection_color (basically any line or fill or text property, prefixed with selection_) :
p.circle(..., selection_color="firebrick")
Then a Circle will be created automatically and used for renderer.selection_glyph
I hope this is useful information. If so, it highlights that there are two possible ways that the project could be improved:
updating the docs to be explicit and highlight that renderer.selection_glyph is None by default
changing code so that renderer.selection_glyph is just a copy of renderer.glyph by default (then your original code would work)
Either would be small in scope and ideal for a new contributor. If you would be interested in working up a Pull Request to do either of these tasks, we (and other users) would certainly be grateful for the contribution. In which case, please just make an issue first at
https://github.com/bokeh/bokeh/issues
that references this discussion, and we can provide more details or answer any questions.
Related
Lately I've been following a tutorial and I need to recreate a project. In this instance it's a map made with openstreetmap and folium. On the example map i'm to recreate is a map with small circle markers that are all of a different color.
The first thing I do is open jupyter notebook python session and enter this:
>>> import folium
>>> dir(folium)
from here I see all the things that I can do with folium. One of them is called "Circle.Marker" and seems to be exactly what I need.
>>> help(folium.CircleMarker)
and I'm greeted with this:
"Help on class CircleMarker in module folium.vector_layers:
class CircleMarker(folium.map.Marker)
CircleMarker(location=None, radius=10, popup=None, tooltip=None, **kwargs)"
I see that the parameters that I can pass into CircleMarker are location, radios, popup, tootip, and **kwargs)
unfortunately none of them seem to be what I need. Then I go to the code example and see that they've passed
folium.CircleMarker(location= foo, popup = foo , radius = foo, fill_color = foo)
How was i ever supposed to know that "fill_color" was a parameter that circlemarker would accept? I looked at the "**kwargs" part and that also doesn't seem to be the answer. This must mean that I'm missing some fundamental step in the learning process.
If anyone could point me in the right direction, I'd really appreciate.
I am trying to build a grid plot that updates based on value selected from 'Select' widget using Bokeh.
The graph works but there is no interaction between the widget and the graph. I am not sure how to do this. The goal is to use the 'Select' to update dfPlot then follow the remaining steps.
Here is what i have so far:
output_file('layout.html')
select = Select(title="Option:", options= list(dfExpense['Ident'].unique()), value= "VALUE")
def update_plot(attr, old, new):
dfPlot = dfExpense[dfExpense['Ident'] == select.value]
select.on_change('value', update_plot)
d = []
for x in dfPlot['Account'].unique():
d.append(f's_{x}')
plt = []
for i, x in enumerate(dfPlot['Account'].unique()):
dftemp = dfPlot[dfPlot['Account']==gl]
source1 = ColumnDataSource(dftemp)
d[i] = figure(plot_width = 250, plot_height = 250)
d[i].circle('X', 'Amount', source = source1)
plt.append(d[i])
grid= gridplot([i for i in plt], ncols = 6)
l = row(grid, select)
show(l)
curdoc().add_root(l)
Thanks!
Someone else will probably give you a better answer. I'll just say, I think you might be doing things completely wrong for what you are trying to do (I did the same thing when starting to work with Bokeh).
My understanding after a bit of experience with Bokeh, as it relates to your problem, is as follows:
Using curdoc to make an interactive widget based Bokeh plot means you are using Python to interact with the plot, meaning that you must use a Bokeh server, not just use a .html file. (as a corollary, you won't be using show or output file) https://docs.bokeh.org/en/latest/docs/user_guide/server.html
You can still make a standalone .html file and make it have interactive widgets like sliders, but you will have to write some Javascript. You'll most likely want to do this by utilizing CustomJS within Bokeh, which makes it relatively easy.
https://docs.bokeh.org/en/latest/docs/user_guide/interaction/callbacks.html
I had a similar problem, wanting interactivity without using a Python Bokeh server. CustomJS ended up serving my needs quite well, and even though I'm a novice at Javascript, they make it pretty easy (well, especially if your problem is similar to the examples, it can get tricky otherwise but still not very hard).
I created a map roughly following the texas.py example from Bokeh's documentation. I am trying to add a point on the map that has its own mouseover behavior. I've added the glyph with the following:
bc_glyph = Circle(x=barclays_x, y=barclays_y, size=10, line_color="black", fill_color="silver", line_width=1)
I attempted to create custom HoverTool behavior with this:
bc_ht = HoverTool(renderers=['bc_glyph'], tooltips=['Barclays Stadium'])
Then I called plot.add_glyph(bc_glyph). When running my script, I get the following output:
ValueError: expected an element of either Auto or List(Instance(Renderer)), got ['bc_glyph']
A quick google of the error message leads to Bryan helping another user with a similar issue, so I rewrite as follows:
plot_add = plot.add_glyph(bc_glyph)
bc_ht = HoverTool(renderers=['plot_add'], tooltips=['Barclays Stadium'])
However, that returns the same error:
ValueError: expected an element of either Auto or List(Instance(Renderer)), got ['plot_add']
I understand I have fed the wrong input to renderers, but I'm not sure how to correct this. Any help is appreciated.
You are still passing a string, 'plot_add', as the value. You need to pass the actual variable:
bc_ht = HoverTool(renderers=[plot_add], # no quote around plot_add
tooltips=['Barclays Stadium'])
I am trying to write a python script that uses matplotlib. The idea is that when the user runs the script, an interactive window pops up in which they can toggle certain plots on and off with the CheckButtons that matplotlib provides. I managed to figure out how to change the visibility of the plots themselves, however, I am struggling to do the same for the annotation. For the lines I have the following code:
def plotsetlines(lines,toggle):
""" plot vertical, labeled lines """
x = []
lmin = 4
lmax = 6
for name in lines:
x.append(lines[name])
plt.annotate(s=name, xy=(lines[name], lmax), xytext=(lines[name], lmax+1.1), rotation=90,size='large', visible=toggle)
print x
return plt.vlines(x, lmin, lmax, lw=2,visible=toggle)
Here lines is a dictionary of the form:
lines1 = {"a":115.27, "b":115.0, "c":112.0}
and toggle is a boolean. Once this function has been called, I can change the visibility of the lines as follows:
lns1 = plotsetlines(lines1,True)
lns1.set_visible(not lns1.get_visible())
The problem is, I have no idea how I can do the same thing for my annotations easily. I know that the Annotate object has the get/set_visible methods as well, but the function I wrote doesn't return the annotations in the same way that it returns my lines, so I'm not sure what to call the methods on. Any suggestions and ideas are welcome.
Also, since this is my first question posted here, please let me know if you have suggestions about the layout/wording etc. of the question itself. Thanks!
I have a Python Bokeh plot containing multiple lines, Is there a way I can interactively switch some of these lines on and off?
p1.line(Time,Temp0,size=12,color=getcolor())
p1.line(Time,Temp1,size=12,color=getcolor())
p1.line(Time,Temp2,size=12,color=getcolor())
p1.line(Time,Temp3,size=12,color=getcolor())
....
show(p1)
I just came across this problem myself in a similar scenario. In my case, I also wanted to do other operations on it.
There are 2 possible approaches:
1.) Client-server approach
2.) Client only approach
1.) Client Server Approach ak Bokeh Server
One way how you can achieve this interactivity is by using the bokeh server which you can read more about here. I will describe this way in more detail since at this point, I am a bit more familiar with it.
Going by your example above, if I were to use the bokeh serve, I would first setup a ColumnDataSource like so:
source = ColumnDataSource(data = dict(
time = Time,
temp0 = [],
temp1 = [],
temp2 = [],
temp3 = [],
)
Next I would setup a widget that allows you to toggle what temperatures to show:
multi_select = MultiSelect(title="Option:", value=["Temp1"],
options=["Temp1", "Temp2", "Temp3"])
# Add an event listener on the python side.
multi_select.on_change('value', lambda attr, old, new: update())
Then I would define the update function like below. The purpose of the update function is to update the ColumnDataSource (which was previously empty) with values you want to populate in the graph now.
def update():
"""This function will syncronize the server data object with
your browser data object. """
# Here I retrieve the value of selected elements from multi-select
selection_options = multi_select.options
selections = multi_select.value
for option in selection_options:
if option not in selections:
source.data[option] = []
else:
# I am assuming your temperatures are in a dataframe.
source.data[option] = df[option]
The last thing to do is to redefine how you plot your glyphs. Instead of drawing from lists, or dataframes, we will draw our data from a ColumnDataSource like so:
p1.line("time","temp0", source=source, size=12,color=getcolor())
p1.line("time","temp1", source=source, size=12,color=getcolor())
p1.line("time","temp2", source=source, size=12,color=getcolor())
p1.line(Time,Temp3, source=source, size=12,color=getcolor())
So basically by controlling the content of the ColumnDataSource which is synchronized with the browser object, I can toggle whether data points are shown or not. You may or may not need to define multiple ColumnDataSources. Try it out this way first.
2.) Client only approach ak Callbacks
The approach above uses a client-server architecture. Another possible approach would be to do this all on the front-end. This link shows how some simple interactions can be done completely on the browser side via various forms of callbacks.
Anyway, I hope this is helpful. Cheers!
The question is from some time back but Bokeh now has the interactive legend functionality - you can just specify
your_figure.legend.click_policy = 'hide'
And this makes legend while listing your lines interactive and you can switch each line on/off