How to restrict range with Panel Pyviz datepicker? - pyviz

I have a chart plotting datetime data between a Start and End date the user selects from 2 Panel datepickers. At the moment the user can select an End date than comes before the Start date, or a Start date that falls after the selected End date. There is no warning to the user that the dates they've selected are invalid.I'm looking for a way to generate a warning, or restrict the dates available for selection on one datepicker depending on what was selected in the other.
I've worked with #pn.depends before in dropdown selectors (How do i automatically update a dropdown selection widget when another selection widget is changed? (Python panel pyviz)). I'm struggling to figure out how to achieve dependency between 2 date pickers... Any ideas?
Here is a list of attributes of the datepicker class. Those in bold sound promising?
'add_periodic_callback', 'align', 'app', 'aspect_ratio', 'background', 'clone', 'css_classes', 'debug', 'defaults', 'disabled', 'embed', 'end', 'force_new_dynamic_value', 'get_param_values', 'get_root', 'get_value_generator', 'height', 'height_policy', 'initialized', 'inspect_value', 'jslink', 'link', 'margin', 'max_height', 'max_width', 'message', 'min_height', 'min_width', 'name', 'param', 'params', 'pprint', 'print_param_defaults', 'print_param_values', 'save', 'script_repr', 'select', 'servable', 'server_doc', 'set_default', 'set_dynamic_time_fn', 'set_param', 'show', 'sizing_mode', 'start', 'state_pop', 'state_push', 'value', 'verbose', 'warning', 'width', 'width_policy'
import panel as pn
from panel.interact import interact
from bokeh.plotting import figure
[...]
date_picker = pn.widgets.DatePicker(name='Select date range Start', value=datetime(2020, 1, 1, tzinfo=timezone.utc))
date_picker_2 = pn.widgets.DatePicker(name='Select date range End', value=datetime(2020, 8, 31, tzinfo=timezone.utc))
interact_obj = interact(
make_plot,
Start=date_picker,
End=date_picker_2
)
return pn.Column(interact_obj).servable()

Related

How to embed a dropdown ipywidget in an ipysheet spreadsheet?

I tried following the code to merge a dropdown menu ipywidget into the ipysheet. it seems like my code works the way I imagined. However, I am unable to select items from the menus listed in the dropdown widget.
import ipysheet
import ipywidgets as widgets
Solvent = widgets.Dropdown(
options=['DMC', '2-Butanol', 'Chloroform', 'Ethanol'],
value='DMC',)
sheet2 = ipysheet.sheet()
ipysheet.column(0, [Solvent])
ipysheet.column(1, [1,2,3,4, 5])
widgets.VBox([sheet2, Solvent ])
After some review, I believe that this is a genuine bug/shortcoming with ipysheet. Though there are alternative approaches, this inability to use a particular widget within ipysheet cells is not an expected result of this API... Someone please correct me if I'm missing something.
There is a "hack" that is working for me through Jupyter Notebook in the browser, which is to right-click the dropdown before left-clicking it to change the context of the dropdown menu, allowing you to select it via mouseover.
The other alternative is passing in your options as the "choice" argument to the cell you wish to contain the dropdown.
from ipywidgets import link
import ipysheet
import ipywidgets as widgets
Solvent = widgets.Dropdown(
options=['DMC', '2-Butanol', 'Chloroform', 'Ethanol'],
value='DMC',)
sheet2 = ipysheet.sheet()
# dropdown_cell = ipysheet.cell(0,0,choice = Solvent.options,value='WORLD')
interactive_cell = ipysheet.cell(1,3, value='HELLO')
dropdown_cell = ipysheet.cell(0,0,choice = Solvent.options,value='WORLD')
# link((interactive_cell,'value'),(dropdown_cell,'value'))
link((dropdown_cell,'value'),(interactive_cell,'value'))
widgets.VBox([sheet2, Solvent ])
From my current understanding (and attempts), only cells are interactive in ipysheets. (The alternative method of using the ipysheet "calculation" decorator also depends on the items being Cells, not Columns.)

Plotly - clicking on legend items - how to make an initial setting?

When someone clicks on a legend item, it becomes grey, and the data disappears, for instance, here. It is possible to set that an item from a legend will be grey after opening the .HTML output and will appear after clicking of that? Thank you
You can do that using the visible property on the trace, just set visible='legendonly'.
visible
Type: enumerated , one of ( True | False | "legendonly" )
Default: True
Determines whether or not this trace is visible. If "legendonly", the
trace is not drawn, but can appear as a legend item (provided that the
legend itself is visible).
A common use case is when one has a lot of traces and wants to show only a few of them initially, eg. with plotly.express :
import plotly.express as px
df = px.data.gapminder().query("continent == 'Europe'")
# Nb. This creates one trace per country (color='country'), with each trace `name`
# inheriting the value of its respective country.
fig = px.line(df, x='year', y='gdpPercap', color='country', symbol="country")
# Arbitrary selection
sel = ['Norway', 'Ireland', 'France', 'Switzerland']
# Disable the traces that are not in the selection
fig.update_traces(selector=lambda t: t.name not in sel, visible='legendonly')
fig.show()

PySimpleGui: How to enter text in the text box?

I am learning PySimpleGui by referring the tutorials at
Link-1 and Link-2
I need to add buttons to my layout to enter a value, then display the value in adjoining textbox
So far, i have been able to create the buttons and the textboxes.
Following is my code:-
import PySimpleGUI as sg
layout = [[sg.Text('Enter Value:')],
[sg.Input(do_not_clear=False), sg.Text('Value selected is:'), sg.Text(sg.InputText(""), key='_USERNAME_')],
[sg.Button('Enter'), sg.Exit()],
[sg.Text('List Of Values:')],
[sg.Listbox(values=('value1', 'value2', 'value3'), size=(30, 2), key='_LISTBOX_')]]
window = sg.Window('My Application', layout)
while True:
event, values = window.Read()
print(event, values)
if event is None or event == 'Exit':
break
if event == 'Enter':
window.Element('_LISTBOX_').Update(values=[event, values, 'new value 3'])
#window.Element('_USERNAME_').Update(values=[values]) #need to update the text box with value entered
window.Close()
However, i am not able to display the entered value in the text box.
I have added a comment in the code (which gives an error for now) where i need to update the text box with entered value.
Please help!
Edit: I was able to display the value in a popup, but i need to display in the text box
You can update elements directly by referencing them using their key on the window object:
eg as per your updates
window['_LISTBOX_'].Update(values=[event, values, 'new value 3'])
window['_USERNAME_'].Update(values[0])
I figured it out,
Following code serves my purpose:-
import PySimpleGUI as sg
layout = [[sg.Text('Enter Value:')],
[sg.Input(do_not_clear=False), sg.T('Not Selected ', size=(52,1), justification='left',text_color='red', background_color='white', key='_USERNAME_')],
[sg.Button('Enter'), sg.Exit()],
[sg.Text('List Of Values:')],
[sg.Listbox(values=('value1', 'value2', 'value3'), size=(30, 2), key='_LISTBOX_')]]
window = sg.Window('My Application', layout)
while True:
event, values = window.Read()
print(event, values)
if event is None or event == 'Exit':
break
if event == 'Enter':
window.Element('_LISTBOX_').Update(values=[event, values, 'new value 3'])
window.FindElement('_USERNAME_').Update(values[0])
window.Close()

How can I get the values of my widget items to display in a TextArea and convert the values to dictionary

I am creating a post form that will send my input as dictionary to a server. I planned to display the user entered input in a TextArea with my first display button click. This display button sets the next button (Send) to be visible. The Send button then convert or saves the values to a dictionary (key/value pair).
In my code, i followed the example in the ipywidget documentation (https://ipywidgets.readthedocs.io/en/latest/examples/Widget%20Styling.html [cell 12]) by adding all my widgets in a list. I am have difficulty in calling the values of the widget items to display in the Text area
I have tried to access the values using children[0].values but get error each time. AttributeError: 'Button' object has no attribute 'values'. I will appreciate anyone's help to do this form. If i can get my inputs as a dictionary, that will be very helpful
from ipywidgets import Layout, Button, Box, FloatText, Textarea, Dropdown, Label, IntSlider, Text
#Form item layout
form_item_layout = Layout(
display='flex',
flex_flow='row',
justify_content='space-between'
)
#form container
form_items = [
Box([
Label(value='Name'),
Text(value='John')
], layout=form_item_layout),
Box([
Label(value='Collection UUID'),
Dropdown(options=['theme', 'play', 'character'])
], layout=form_item_layout),
Box([Label(value='Result'),
Textarea(rows = 20)], layout=form_item_layout),
Button(description="display"),
Button(description="Send", button_style='success')
]
#box layout that holds the forms
box_lyt = Layout(
display='flex',
flex_flow='column',
border='solid 2px',
align_items='stretch',
width='50%'
)
form = Box(children=form_items, layout=box_lyt)
display(form)
form.children[4].layout.visibility = 'hidden'
def show(b):
form.children[4].layout.visibility = 'visible'
form.children[2] = c.children[0] + c.children[1] + c.children[2]
#Convert textarea values to dictionary
def list_children(c):
return c.children[2].to_dict()
form.children[3].on_click(show)
form.children[4].on_click(list_children )
I expect a widget displaying: Name, ID, result and display button. Clicking the display should show the values in the result TextArea and make the button (send) visible. Clicking the Send button should accept these values from result and save as dictionary. The widget displays but is not responsiveenter image description here

Matlab GUI: Selecting a number from a popup menu

I have a variable d of size 50 x 1 and class double which contains numbers. I am trying to include this in a popup menu in a Matlab GUI. I am currently doing this:
d = cellfun(#num2str, num2cell(handles.zRaw(:)), 'uniformoutput', false);
S.T2pm5 = uicontrol('Style', 'popupmenu', 'BackgroundColor', 'w', 'Parent',...
T2vbox6, 'String', {'Choose a Number', d{:}}, 'value', 1);
However, any selection from the above popup menu using str2double(get(S.T2pm5, 'value')); outputs all the numbers into a single string variable. How can I output only a single number selected by the user through the popup menu than all the values present there?
You can do that by adding a callback that uses both the value and string properties of the popup menu. Here's a working example:
Create a popup menu with a callback
T2vbox6 = figure();
handles.zRaw = [10,20,30,40,50];
d = cellfun(#num2str, num2cell(handles.zRaw(:)), 'uniformoutput', false);
S.T2pm5 = uicontrol('Style', 'popupmenu', 'BackgroundColor', 'w', 'Parent',...
T2vbox6, 'String', {'Choose a Number', d{:}}, 'value', 1,...
'callback', #someMenuCallBack);
str2double(get(S.T2pm5, 'value'))
Then define the call back:
function someMenuCallBack(hObj,event)
d = str2double(get(hObj, 'String'));
val = get(hObj,'Value');
disp(d(val))
This will display the value selected by the user at the command line.

Resources