How to perform an onclick action on button click in python bokeh?
I'm new to bokeh and I have aquery regarding button onclick event, the code is provided below:
x = widgetbox(button) show(x) fruits = ['Answered', 'Unanswered','Total'] top1=[1,2,3] def callback(): p = figure(x_range=fruits, plot_height=250, title="sophia bot") p.vbar(x=fruits, top=top1, width=0.9) p.xgrid.grid_line_color = None p.y_range.start = 0 output_file("abc.html") show(p) button_one = Button(label="Start", disabled=True, callback=callback) show(button_one)
but this isnt performing the action, the following code when used alone, does plot the graph, i want the graph to be shown alongisde when i clicke the button.
fruits = ['Answered', 'Unanswered','Total'] top1=[1,2,3] p = figure(x_range=fruits, plot_height=250, title="sophia bot") p.vbar(x=fruits, top=top1, width=0.9) p.xgrid.grid_line_color = None p.y_range.start = 0 output_file("abc.html") show(p)
You must assign the callback to the button like this:
from bokeh.models import Button from bokeh.io import curdoc bt = Button(label='Click me') def change_click(): print('I was clicked') bt.on_click(change_click) curdoc().add_root(bt)
Launch this with
bokeh serve --show example.py.
Note: Also take a look at my question where I talk about dynamic layout
See also questions close to this topic
conversion of lists into a numpy array in pandas dataframe
We have a dataframe where the elements of one column are lists (the discussion is not about if this should be done or not). A simple example is the following:
df = pd.DataFrame([[12,[123,234,234]], [14,[124,25,235]], [16,[1267,267,2345]]], columns = ['A', 'B'])
the goal here to to convert the column B into a numpy array, like the following one:
If I ask to pandas convert the column into an array:
it returns an array of list, which is not the same as the one above:
array([list([123, 234, 234]), list([124, 25, 235]), list([1267, 267, 2345])], dtype=object)
How can we solve the problem?
How to convert hex to dec manually in python?
This is my first time using this QnA site... I had this task in my class which asks me to convert numbers from any basis into decimal using method... I'm very confused about converting alphabets contained in a hex number. Here is the program which I type:
def base_n_to_dec(num_string, base): dec = 0 index = len(num_string) - 1 for digit in num_string: dec += int(digit) * (base ** index) index -= 1 return dec
Could anyone please help me to modify this program so it could recognize the alphabets contained in hex numbers, so it could convert the characters to decimal basis? Please don't use built-in functions, because it's not allowed. (I already submitted the task, so I don't mean asking someone to finish my assignment) sorry for the bad english...
Can't get "WebDriver" element data if not "eye-visible" in browser [Selenium + Python]
I'm doing a scraping with Selenium in Python. My problem is that after I found all the WebElements, I'm unable to get their info (id, text, etc) if the element is not really VISIBLE in the browser opened with Selenium.
What i mean is:
As you can see from the first and second images, I have the first 4 "tables" that are "visible" for me and for the code. There are however, other 2 tables (5 & 6 Gettho lucky dip & Sue Specs) that are not "visible" until I drag down the right bar.
Here's what I get when I try to get the element info, without "seeing it" in the page: Third image
Manually dragging the page to the bottom and therefore making it "visible" to the human eye (and also to the code ???) is the only way I can the data from the WebDriver element I need: Fourth image
What am I missing ? Why Selenium can't do it in background ? Is there a manner to solve this problem without going up and down the page ?
ps.: the page could be any kind of dog race page in http://greyhoundbet.racingpost.com/ Just click City - Time - and then FORM.
Here's part of my code:
# I call this function with the URL and it returns the driver object def open_main_page(url): chrome_path = r"c:\chromedriver.exe" driver = webdriver.Chrome(chrome_path) driver.get(url) # Wait for page to load loading(driver, "//*[@id='showLandingLADB']/h4/p", 0) element = driver.find_element_by_xpath("//*[@id='showLandingLADB']/h4/p") element.click() # Wait for second element to load, after click loading(driver, "//*[@id='landingLADBStart']", 0) element = driver.find_element_by_xpath("//*[@id='landingLADBStart']") element.click() # Wait for main page to load. loading(driver, "//*[@id='whRadio']", 0) return driver
Now I have the browser "driver" which I can use to find the elements I want
url = "http://greyhoundbet.racingpost.com/#card/race_id=1640848&r_date=2018- 09-21&tab=form" browser = open_main_page(url) # Find dog names names =  text: str tags = browser.find_elements_by_xpath("//strong")
Now "TAGS" is a list of WebDriver elements as in the figures.
Thanks, guys. I'm pretty new to this area. I tried to be as clear as possible. Any help is welcome.
Based on the visualised plots, which features data matrix is better for PCA, "X_scaled" or "X", Why?
The first graph is a plot by transfer a 25 features feature matrix and the second graph is transformed from the same feature matrix but be scaled by StandardScaler(). I am very confused about this question, I understand that the PCA is used to visualize the high dimensional data. But I don't understand what is meant by a 'good' PCA plot. Both graphs look like they have a lot of points coincide with each other, but I think this can be overcome by zoom in or changed the scale, so I think the number of coinciding points in a plot should not be the criterion to judge if it is better.
I have another idea which is that the scaled plot(which is the second one) have a more clear cluster(most red points are on the second principal component--y-axis and blue points are in first component---x-axis), so from this respect, I think the scaled one is better. Could anyone explain this to me?
How to color each pixel of a 3D MRI brain structure to visualise in slicer without actually changing pixel values?
I couldnot find anything in nilearn python library to color the pixels.
ROS RVIZ: How to visualize a point cloud that doesn't have a fixed frame transform
I was following the ROS official documentation on how to publish a point cloud and I was able to successfully run the code. Now I'm trying to visualize the point cloud using ROS RVIZ but I'm getting an error.
Transform [sender=unknown_publisher] For frame [single_frame]: Fixed Frame [map] does not exist
How can I overcome this error? It says the frame does not exist. Is there a workaround or a configuration setting in RVIZ to bypass the error? Or how can I update my c++ code to update the frame object? Can you please provide me with some example code?
Bokeh Columnsourcedata finding min and max
I am trying to find the max and min value for each category within source = columndatasource where my stock data is organized into columns by (Open, High, Low, Close, AdjClose, Volume, etc....)
I tried using,
however, the problem with max(source.data['Open'] is that the values do not update when I update my data when using the slider and select widgets.
Is there a way in which that I can find the min and max of each column that will update each time when I update my data ?
from math import pi import pandas as pd import numpy as np import datetime import time from datetime import date from bokeh.layouts import row, widgetbox, column from bokeh.models import DataRange1d, LinearAxis, Range1d, ColumnDataSource, PrintfTickFormatter, CDSView, BooleanFilter, NumeralTickFormatter from bokeh.models.widgets import PreText, Select, DateRangeSlider, Button, DataTable, TableColumn, NumberFormatter from bokeh.io import curdoc, show, reset_output from bokeh.plotting import figure, output_file DEFAULT_TICKERS = ['AAPL','GOOG','NFLX', 'TSLA'] ticker1 = Select(value='AAPL', options = DEFAULT_TICKERS) range_slider1 = DateRangeSlider(start=date(2014,1,1) , end=date(2017,1,1), value=(date(2014,2,1),date(2016,3,1)), step=1) def load_ticker(ticker): fname = ( '%s.csv' % ticker.lower()) data = pd.read_csv( fname, header = None, parse_dates = ['Date'], names =['Date','Open','High','Low','Close','AdjClose','Volume']) return data def get_data(t1): data = load_ticker(t1) return data def ticker1_change(attrname, old, new): update() def range_slider_change(attrname, old, new): update() def update(selected=None): t1 = ticker1.value if isinstance(range_slider1.value, (int, float)): # pandas expects nanoseconds since epoch start_date = pd.Timestamp(float(range_slider1.value)*1e6) end_date = pd.Timestamp(float(range_slider1.value)*1e6) else: start_date = pd.Timestamp(range_slider1.value) end_date = pd.Timestamp(range_slider1.value) datarange = get_data(t1) datarange['Date'] = pd.to_datetime(datarange['Date']) mask = (datarange['Date'] > start_date) & (datarange['Date'] <= end_date) data = datarange.loc[mask] source.data = source.from_df(data) p.title.text = t1 data = get_data(ticker1.value) source = ColumnDataSource(data) p = figure(plot_width=900, plot_height=400, x_axis_type='datetime') p.grid.grid_line_alpha = 0.3 p.line('Date', 'Close', source=source) ticker1.on_change('value', ticker1_change) range_slider1.on_change('value', range_slider_change) update() layout = column(ticker1,range_slider1, p) curdoc().add_root(layout) curdoc().title = "Stock"
python bokeh: get image from webcam and show it in dashboard
I want to display a an image - e.g. capture with the webcam - in bokeh. I tried image_url and image_rgba, but both are not working. Image_url is showing nothing, image_rgb shows somethin, but there seems to be some index shif.
# -*- coding: utf-8 -*- from bokeh.plotting import figure, show import scipy.misc import cv2 import matplotlib.pyplot as plt import os # capture video frame from webcam #vc = cv2.VideoCapture(1) vc = cv2.VideoCapture(-0) rval, frame = vc.read() vc.release() # show captured image fig = plt.figure() ax = plt.Axes(fig,[0,0,1,1]) ax.set_axis_off() fig.add_axes(ax) ax.imshow(frame) plt.show() # save captured image scipy.misc.imsave('outfile.jpg', frame) mypath = os.path.join(os.getcwd(),'outfile.jpg') # 1. try using image_url ... not working p = figure() p.image_url(url=[mypath],x=,y=,w=,h=) show(p) # 2. try using image_rgba ... also not working p = figure(x_range=(0,10), y_range=(0,10)) p.image_rgba(image=[frame], x=0, y=0, dw=10, dh=10) show(p) # 3. solution provided by @bigreddot ... flipped but also not working img = misc.imread(mypath)[::-1] # flip y-direction for Bokeh p = figure(x_range=(0,10), y_range=(0,10)) p.image_rgba(image=[img], x=0, y=0, dw=10, dh=10) show(p)
Bokeh: Dynamically update the location of a vertical line.
I have added a vertical line to an existing bokeh figure using the following lines, following the example bokeh docs:
from bokeh.models import Span important_time = Span(location=shift_no, dimension='height', line_color='red', line_dash='dashed', line_width=3) my_figure.add_layout(important_time)
I update the source data of the figure dynamically based on selections made in some widgets. And the vertical line should change for each new data. The problems that the above code keeps adding new vertical lines to existing ones, which is no surprise.
Anybody knows a method to remove previous vertical lines or just update its location? I run it on bokeh server in case that makes any difference in the solution.