I would like to work in Jupyter Notebook though the project with one plot. Update it with a new data or new layout, maybe add/delete additional plot nearby it and so on… In Bokeh I could use smth similar to:
target = show(layout, notebook_handle=True)
push_notebook(handle=target)
In Holoviews I found how to feed new data to the existing plot:
pipe = Pipe(data=[])
Image = hv.DynamicMap(hv.Image, streams=[pipe1])
pipe.send(np.random.rand(3,2)) #data change
But is there any solution to manage live layout update in Holoviews? Is it possible to update existed plot by .opts() construction? In this example I will get a new plot:
pipe = Pipe(data=[])
Image = hv.DynamicMap(hv.Image, streams=[pipe])
Image.opts(width=1000,height=1000)
#######new cell in jupyter notebook############
Image.opts(width=100,height=100)
Here is a brilliant answer I have got on my question:
import param
import panel as pn
import numpy as np
import holoviews as hv
from holoviews.streams import Pipe
pn.extension()
pipe = Pipe(data=[])
class Layout(param.Parameterized):
colormap = param.ObjectSelector(default='viridis', objects=['viridis', 'fire'])
width = param.Integer(default=500)
update_data = param.Action(lambda x: x.param.trigger('update_data'), label='Update data!')
#param.depends("update_data", watch=True)
def _update_data(self):
pipe.send(np.random.rand(3,2))
layout = Layout()
Image = hv.DynamicMap(hv.Image, streams=[pipe]).apply.opts(cmap=layout.param.colormap, width=layout.width)
pdmap = pn.panel(Image)
playout = pn.panel(layout)
def update_width(*events):
for event in events:
if event.what == "value":
pdmap.width = event.new
layout.param.watch(update_width, parameter_names=['width'], onlychanged=False)
pn.Row(playout, pdmap)
https://discourse.holoviz.org/t/how-to-update-holoviews-plots-width-height/1947
Related
My app has become fairly complex, about 1500 lines across several files. There is a button that creates tabs and adds them to an existing panel. Here is a minimal working example of how the button works:
def create_new_tab():
paragraph = Paragraph(text="Hello!")
tab = Panel(child=paragraph, title="tab")
tab.closable = True
return tab
def append_new_tab():
new_tab = create_new_tab()
curdoc().select_one({'name': 'tabs'}).tabs.append(new_tab)
button = Button(label='append new tab')
button.on_click(append_new_tab)
tab1 = Panel(child=button, title='button tab')
tabs = Tabs(tabs = [tab1], name='tabs')
curdoc().add_root(tabs)
In my actual program there is a bug somewhere, because when I click the button I get the message that some set changed during iteration:
error handling message Message 'EVENT' (revision 1) content: '{"event_name":"button_click","event_values":{"model_id":"1002"}}': RuntimeError('Set changed size during iteration',)
I have spent some time trying to debug, without success. I have tried to create a minimal not working example, but all my minimal examples work. I keep staring at the error message and wonder what else can I do to find out what is going wrong?
Remark: I am already using bokeh serve myapp/ --dev
You can debug your app using this code (Bokehh v1.1.0):
from bokeh.models import Panel, Tabs, Button, Paragraph
from tornado.ioloop import IOLoop
from bokeh.server.server import Server
from bokeh.application import Application
from bokeh.application.handlers.function import FunctionHandler
def modify_doc(doc):
def create_new_tab():
paragraph = Paragraph(text="Hello!")
tab = Panel(child=paragraph, title="tab")
tab.closable = True
return tab
def append_new_tab():
new_tab = create_new_tab()
doc.select_one({'name': 'tabs'}).tabs.append(new_tab)
button = Button(label='append new tab')
button.on_click(append_new_tab)
tab1 = Panel(child=button, title='button tab')
tabs = Tabs(tabs = [tab1], name='tabs')
doc.add_root(tabs)
io_loop = IOLoop.current()
server = Server(applications = {'/app': Application(FunctionHandler(modify_doc))}, io_loop = io_loop, port = 5001)
server.start()
server.show('/app')
io_loop.start()
I'd like to have a custom formatter for one my dataTable cells.
Say, for example I'd like to have the title column font style in bold.
from bokeh.plotting import show
from bokeh.models.sources import ColumnDataSource
from bokeh.models.widgets import DataTable, TableColumn
if __name__ == '__main__':
source = ColumnDataSource(data = dict(hello = ["one", "two", "three"]))
c0 = TableColumn(field="hello",
title= "TITLE IN BOLD?")
ds = DataTable(source=source,
columns = [c0])
show(ds)
Is there a simple way to do this in BokehJS?
Thanks
Using the HTMLTemplateFormatter can get the job done. This allows all cells in the column to be formatted as code so you can add in bold tags or what ever else you want in any of the cells.
Note: if you are using bokeh version 0.12.5 Unfortunately they have removed underscore js so to get around it (first block of ugly code), you can use the work around from this github issue: https://github.com/bokeh/bokeh/issues/6207. Or alternatively include underscorejs/lodash in the output html file, i.e. <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/0.10.0/lodash.min.js"></script>
from bokeh.models.widgets import HTMLTemplateFormatter
from bokeh.plotting import show
from bokeh.models.sources import ColumnDataSource
from bokeh.models.widgets import DataTable, TableColumn
class MyHTMLFormatter(HTMLTemplateFormatter):
__javascript__ = ["https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"]
__implementation__ = """
import {HTMLTemplateFormatter} from "models/widgets/cell_formatters"
export class MyHTMLFormatter extends HTMLTemplateFormatter
type: 'MyHTMLFormatter'
"""
if __name__ == '__main__':
source = ColumnDataSource(data = dict(hello = ["<b>one</b>", "two", "three"]))
formatter = HTMLTemplateFormatter(template='<code><%= value %></code>')
c0 = TableColumn(field="hello",
title= "<b>TITLE IN BOLD?</b>", formatter=formatter)
ds = DataTable(source=source,
columns = [c0])
show(ds)
I'm making a scatter plot of some data using Bokeh from a pandas dataframe (df). The dataframe is university data, and has columns "faculty_salary", "tuition", "sector" and "institution_name". The plot is faculty_salary vs tuition, and I'm using the sector to color the data, as shown below.
I currently have the tap tool which greys-out all other data points except for the one you clicked, as shown below.
What I want to do is use the AutocompleteInput widget to select an institution_name from the autocomplete and have it highlight that data point by graying out all the others, just like the tap tool. The AutocompleteInput widget is working fine, it's just the code to make it highlight that data point that I'm struggling to figure out. Here's where I'm at:
source = ColumnDataSource(df)
autocomp = AutocompleteInput(completions=df['name'].tolist())
callback = CustomJS(args=dict(source=source), code="""
what do I put here?? It doesn't seem to have a cb_obj
""")
autocomp.js_on_change('value',callback)
Please let me know how I can achieve the functionality I described: use the selected value in the AutocompleteInput to highlight the datapoint it corresponds to. I should note that for my application I would prefer a CustomJS solution, and not a Bokeh server solution.
Edit: It turns out that my browser (Chrome in Linux) doesn't recognize that an autocompletion value has been selected, but Firefox for Linux does. I think this must be because Jquery UI says:
This widget manipulates its element's value programmatically, therefore a native change event may not be fired when the element's value changes.
Suggestions for how to get around this in Bokeh are welcome.
Here is the Bokeh server solution :
from bokeh.layouts import layout
from bokeh.io import curdoc
from bokeh.models.widgets import AutocompleteInput
from bokeh.models.widgets import (Panel, Tabs, DataTable, TableColumn,
Paragraph, Slider, Div, Button, Select)
from bokeh.plotting import figure, ColumnDataSource
from bokeh.models import HoverTool,TapTool
def update_selected(wttr,old,new):
a_val = autocomp.value
names = source.data['names']
ind = [i for i,x in enumerate(names) if x == a_val]
source.selected={'0d': {'glyph': None, 'indices': []}, '1d': {'indices': ind}, '2d': {}}
data_dict = {'names':['test2','test3','hello','goodbye'],
'x':[0,1,2,3], 'y':[10,20,30,40]}
source = ColumnDataSource(data_dict)
autocomp = AutocompleteInput(completions=['test2','test3','hello','goodbye'])
autocomp.on_change('value',update_selected )
fig = figure(plot_width=400,
plot_height=400,
x_axis_label='x',
y_axis_label='y',
tools=["pan","hover","box_zoom","reset,save"])
fig.scatter('x','y',source=source)
layout = layout([[fig, autocomp]])
curdoc().add_root(layout)
EDIT : here is the solution using customJS
from bokeh.layouts import layout
from bokeh.io import curdoc
from bokeh.models.widgets import AutocompleteInput
from bokeh.plotting import figure, ColumnDataSource
from bokeh.models.callbacks import CustomJS
data_dict = {'names':['test2','test3','hello','test3'],
'x':[0,1,2,3], 'y':[10,20,30,40]}
source = ColumnDataSource(data_dict)
fig = figure(plot_width=400,
plot_height=400,
x_axis_label='x',
y_axis_label='y',
tools=["pan","hover","box_zoom","reset,save"])
fig.scatter('x','y',source=source)
autocomp = AutocompleteInput(completions=['test2','test3','hello','goodbye'])
code = """
var autocomplete = cb_obj.value
var names = source.data.names
function getAllIndexes(arr, val) {
var indexes = [], i;
for(i = 0; i < arr.length; i++)
if (arr[i] === val)
indexes.push(i);
return indexes;
}
var index = getAllIndexes(names,autocomplete)
source.selected = {'0d':{indices: [0]}, '1d':{indices: index},'2d':{indices: [0]}}
"""
callback = CustomJS(args={'source':source}, code=code)
autocomp.callback = callback
layout = layout([[fig, autocomp]])
curdoc().add_root(layout)
Plotly allows you to display text fields when hovering over a point on a scatterplot. Is it possible to instead display an image associated with each point when the user hovers over or clicks on it? I am mostly just using the web interface, but I could instead push my ggplot from R.
Unfortunately, there is no easy way to display images on hover on plotly graphs at the moment.
If you are willing to learn some javascript, plotly's embed API allows you to customize hover (as well as click) interactivity.
Here is an example of a custom hover interaction showing images on top of a plotly graph. The javascript source code can be found here.
Images on hover is now available by Plotly lib. Here is a sample:
from dash import Dash, dcc, html, Input, Output, no_update
import plotly.graph_objects as go
import pandas as pd
# Small molcule drugbank dataset
# Source: https://raw.githubusercontent.com/plotly/dash-sample-apps/main/apps/dash-drug-discovery/data/small_molecule_drugbank.csv'
data_path = 'datasets/small_molecule_drugbank.csv'
df = pd.read_csv(data_path, header=0, index_col=0)
fig = go.Figure(data=[
go.Scatter(
x=df["LOGP"],
y=df["PKA"],
mode="markers",
marker=dict(
colorscale='viridis',
color=df["MW"],
size=df["MW"],
colorbar={"title": "Molecular<br>Weight"},
line={"color": "#444"},
reversescale=True,
sizeref=45,
sizemode="diameter",
opacity=0.8,
)
)
])
# turn off native plotly.js hover effects - make sure to use
# hoverinfo="none" rather than "skip" which also halts events.
fig.update_traces(hoverinfo="none", hovertemplate=None)
fig.update_layout(
xaxis=dict(title='Log P'),
yaxis=dict(title='pkA'),
plot_bgcolor='rgba(255,255,255,0.1)'
)
app = Dash(__name__)
app.layout = html.Div([
dcc.Graph(id="graph-basic-2", figure=fig, clear_on_unhover=True),
dcc.Tooltip(id="graph-tooltip"),
])
#app.callback(
Output("graph-tooltip", "show"),
Output("graph-tooltip", "bbox"),
Output("graph-tooltip", "children"),
Input("graph-basic-2", "hoverData"),
)
def display_hover(hoverData):
if hoverData is None:
return False, no_update, no_update
# demo only shows the first point, but other points may also be available
pt = hoverData["points"][0]
bbox = pt["bbox"]
num = pt["pointNumber"]
df_row = df.iloc[num]
img_src = df_row['IMG_URL']
name = df_row['NAME']
form = df_row['FORM']
desc = df_row['DESC']
if len(desc) > 300:
desc = desc[:100] + '...'
children = [
html.Div([
html.Img(src=img_src, style={"width": "100%"}),
html.H2(f"{name}", style={"color": "darkblue"}),
html.P(f"{form}"),
html.P(f"{desc}"),
], style={'width': '200px', 'white-space': 'normal'})
]
return True, bbox, children
if __name__ == "__main__":
app.run_server(debug=True)
More info: https://dash.plotly.com/dash-core-components/tooltip
I'm newbie in PyQtGraph and Qt. I need to write a function (preferably in separate file) for visualization my data. The short version of my snippet is below. The function and the main code in the same file here:
import numpy as np
from pyqtgraph.Qt import QtGui
import pyqtgraph as pg
def visualizator(image):
app = QtGui.QApplication([])
win = QtGui.QMainWindow()
w = QtGui.QWidget()
win.setCentralWidget(w)
layout = QtGui.QGridLayout()
w.setLayout(layout)
imgView = pg.ImageView()
layout.addWidget(imgView)
imgView.setImage(image)
win.show()
app.exec_()
return
my_image = np.ones((256,256),np.float)
visualizator(my_image)
When I run my code I get Qt crash. What am I doing wrong? What should I return from my function?
You have to be careful with your QApplications. You don't want to start another one in a function. Try removing the app-stuff.