I am using ipywidgets to take user inputs in Jupyter Notebook. Below, I put the code for most two frequent types I am using:
import ipywidgets as widgets
widgets.BoundedIntText(
min=0,
max=90,
step=1,
description='Surface Tilt (in °)',
disabled=False
)
widgets.RadioButtons(
options=['South', 'East-West'],
description='Orientation',
disabled=False
)
However, I can't figure out from the documentation, how can I save the user input to a variable so I can use it next cells.
Any help or alternative solutions/packages to facilitate will be appreciated.
Best,
Debayan
First you need to assign a name to each widget, as #ac24 mentioned. Then by using the value property you can get the value for each widget.
By running the code below you can print the values for both of your widgets:
import ipywidgets as widgets
BoundedIntText_widget = widgets.BoundedIntText(
min=0,
max=90,
step=1,
description='Surface Tilt (in °)',
disabled=False
)
RadioButtons_widget = widgets.RadioButtons(
options=['South', 'East-West'],
description='Orientation',
disabled=False
)
print(BoundedIntText_widget.value , RadioButtons_widget.value)
Related
Sorry, I don't know if the question is clear enough: In Shiny, every time the slider is sliding, it will only calculate and update the value at the end of the sliding. If I link its value to the chart, it doesn't look very smooth when sliding (the chart will only change when the mouse is released or after seconds, rather than keep changing with the sliding).
Use the slide bar to change the y, and the red point's position in the chart will be changed.
Input and Chart
Part of my code is as follows:
In ui.R:
sliderInput("slider_mean",
HTML("Try to change the value of ŷ:"),
min = 1, max = 200, value = 100,width="30%"),
plotlyOutput('meanplot'),
In server.R:(This code may not be complete, just to give an example)
output$meanplot <- renderPlotly({
meantb <- data.frame(y_hat = 1:200) %>%
mutate(col2 =(y_mean1()-y_hat)^2+(y_mean2()-y_hat)^2+(y_mean3()-y_hat)^2+(y_mean4()-y_hat)^2+(y_mean5()-y_hat)^2+(y_mean6()-y_hat)^2)
#Here is to input the slider value
highlight_adjust <- meantb %>%
filter(y_hat %in% input$slider_mean)
p=ggplot(meantb,
aes(x = y_hat, y = col2)) +
geom_point(size =0.7,color="black") +
geom_point(data=highlight_adjust,
aes(x = y_hat, y = col2),
color='red')+
geom_line(size = 0.2,color="black") +
ggplotly(p)
})
The example from Shiny:
https://shiny.rstudio.com/gallery/slider-bar-and-slider-range.html
If we move the slider bar quickly, the output value will have a delay.
After reading some of the source code of sliderInput I found out that the default debounce behavior (cf. to the getRatePolicy section of this article) of the slider is only adhered to in absence of a data-immediate attribute in the HTML code.
That is, we just need to add this attribute to the HTML and the slider reacts instantly.
Note. If you look into the source code referenced before, you will see that receiveMessage will reset immediate to false. receiveMessage is called whenever we use updateSliderInput. Thus, after calling updateSliderInput we have to re-assign the immediate data attribute in order to still see the behaviour.
In the example below you see that the values of the hacked slider are updated instantaneously, while the second slider shows default behavior. A click on update will turn of this behavior as sort of collateral damage and in case you want to use updateSliderInput, you should make sure that the data-immediate attribute is added again (the code for the reset button shows one possible way to do so).
Be, however, aware that there is most likely a reason why the shiny team did not expose this functionality to the end user, so this solution should be regarded as a hack and used with care. (Judging from the source code, they use the immediate attribute to overrule the default rate policy when using updateSliderInput(and thus receiveMessage).
library(shiny)
library(shinyjs)
my_sld <- function(...) {
sld <- sliderInput(...)
sld$children[[2]]$attribs$`data-immediate` <- "true"
sld
}
shinyApp(
fluidPage(
useShinyjs(),
my_sld("sld1", "Immediate:", 1, 10, 1),
verbatimTextOutput("dbg1"),
sliderInput("sld2", "Debounced:", 1, 10, 1),
verbatimTextOutput("dbg2"),
actionButton("update", "Update kills Immediateness"),
actionButton("reset", "Re-add immediate attribute")
),
function(input, output, session) {
output$dbg1 <- renderPrint(input$sld1)
output$dbg2 <- renderPrint(input$sld2)
observeEvent(input$update, {
updateSliderInput(session, "sld1", value = 8)
})
observeEvent(input$reset, {
runjs("$('#sld1').data('immediate', true);")
})
})
I am relatively new to shiny app and is trying to make a simple app : while i am able to run ui.R correctly, i am having problem with server.R......what i want is to take a value of slider bar "post" (this number will be used as arg. of function "wbpg"),select the type of plot from dropdown menu and plot the corresponding variable when action button "RUN" is pushed.....all the results and plots are saved when a function named "wbpg(x)" (where "x" is the value of slider bar)...when wbpg(x) is run it returns plots(this contains list of all the plots in drop down menu)
#UI.R
shinyUI( fluidPage(
titlePanel(title=h4("Text Mining on thread",align="centre")),
sidebarLayout(
sidebarPanel(
sliderInput("post","1. Choose no. of posts you want to run the model",value = 1, min = 1, max = 30000),
br(),
selectInput("plotvar","2. Select the variable you want to plot",choices=c("raw_dat"=1,"content"=2,"barplot"=3,"genderplot"=4,"girlplot"=5,"rawplot"=6,"adjplot"=7,
"drinkplot"=8,"damageplot"=9,"songplot"=10,"sentimentplot"=11)),
br(),
actionButton(inputId="act",label = "RUN!")
),
mainPanel(
textOutput("out"),
#tableOutput("tab"),
plotOutput("hist1")
)
)
))
this is server file, where the problem exists:
#server.R
shinyServer(function(input, output) {
#observeEvent(input$action,wbpage(as.numeric(input$post)))
#output$data<-renderPrint({str(get(content))})
observeEvent(input$act,{wbpg(np)})
output$out<-renderText(paste("No. of posts mined: ",input$post))
#defaul<-reactiveValues(data=wbpage(3000))
np<-wbpage(as.numeric(input$post))
output$hist1 <- renderPlot({barplot})
})
#output$hist1 <-
#renderPlot({
#plots$barplot
#output$tab<-
# renderTable({
# head(data())
#})
#output$hist2 <- renderPlot({
#hist(rnorm(input$num))
#raunchyplot
#})
#})
Without having access to your function (wbpg), let me try to help you with the values returned from the 'observeEvent' call. I think your problem is the placement of the '})' on the line with 'observeEvent'. Everything you want to happen upon clicking the 'Run' button needs to be within the '})'. If this isn't what you need, please restate the question.
In place of your 'observeEvent' command, use the following code to see the data returned every time you click on the 'Run' button. It shows the value of the slider bar and the number from the drop down menu.
observeEvent(input$act,{
print (paste(input$post,input$plotvar,sep=' '))
})
I have a google map that shows markers whenever I click on the map. This map is located at one tab in my shiny dashboard. I also have there a table that shows the tabulated info of the markers.
So far, so good.
The problem appears when I switch to a any different tab and then I get back to the google map tab. The maps is not reacting, the markers are not updating despite the information on the table is. So, the problem is on the map itself.
Is there a way to keep, I don't know, active the map even if I'm in different tab, or the map refresh when I get back to the tab?
This is my sidebar
sidebar<-dashboardSidebar(
fluidRow(column(width = 12,
fluidRow(column(width = 12,
sidebarMenu(
id = "sidebar",
menuItem("Inicio", tabName="BVND"),
menuItem("Localizador", tabName="LOC"),
menuItem("Homologación", tabName="HOM")
)))
)
Inside the "Localizador" is where I call the map: google_mapOutput(outputId = "map",height = 600).
and in the output I have
google_map(key = map_key
,location = c(avia[2], avia[1],"red")
,data=distancia2
,zoom = 18
,height = 1500
) %>%
add_markers(lat="latitud"
,lon="longitud"
,title ="title"
,info_window="info_window"
,close_info_window=TRUE
,marker_icon = "icon"
)
I tried the updatetabitems, google_map_update, as reactives/observe in my output or the server itself
I solved the issue by "fragmenting" the observe.
The action is that the map updates whenever I click on it, and it wasn't doing it if I went to a different section of the app.
I rewrote the "click on map" action by using an observe containing google_map_update.
google_map_update( "map"
,session = shiny::getDefaultReactiveDomain()
) %>%
clear_markers( ) %>%
clear_polygons()
google_map_update( "map"
,session = shiny::getDefaultReactiveDomain()
) %>%
add_markers(data = data
,lat="latitud"
,lon="longitud"
,title ="title"
,info_window="info_window"
,close_info_window=TRUE
,marker_icon = "icon"
)
you have to be careful. For some reason in another action, the add_markers cause problems inside an observeEvent. So you might want to avoid or test the add_markers in an map update.
(Sorry I didn't wrote the example of the problem, it's kind of a big project and didn't have time to make a slim version of it. I hope at least it helps to another fellow with same or similar issues)
I would like to friendly ask that if anybody know how to make a certain variable name invisible in the selective area when using 'rpivotTable()' package in R?
For example, I build a pivot table using "UCBAdmission" data set:
# use rpivotTable to illustrate the effect
rp <- rpivotTable(UCBAdmissions, height=200)
The is the output of rp:
However, if user accidentally drag "Freq" to "col" or "row" area, the table will be very big but this is not what I want.
So I would like to find a way to make "Freq" invisible from the selective area. I used the code here but this can only customize the whole table but not the individual variable.
style_widget <- function(hw=NULL, style="", addl_selector="") {
stopifnot(!is.null(hw), inherits(hw, "htmlwidget"))
# use current id of htmlwidget if already specified
elementId <- hw$elementId
if(is.null(elementId)) {
# borrow htmlwidgets unique id creator
elementId <- sprintf(
'htmlwidget-%s',
htmlwidgets:::createWidgetId()
)
hw$elementId <- elementId
}
htmlwidgets::prependContent(
hw,
htmltools::tags$style(
sprintf(
"#%s %s {%s}",
elementId,
addl_selector,
style
)
)
)
}
library(htmltools)
library(htmlwidgets)
library(rpivotTable)
# use rpivotTable to illustrate the effect
rp <- rpivotTable(UCBAdmissions, height=200)
browsable(
tagList(
rp,
style_widget(hw=rp, "font-family:monospace;"),
style_widget(hw=rp, "visibility:none;", "table td")
)
)
I don't know how to control the customize for individual variables. Does anyone know it or have any ideas about it?
I appreciate for any replies.
Thank you!
Best regards
This is my first question on stackoverflow, and I've been using R for 3 months. I have a lot to learn! Any help is much appreciated. Thank you in advance for your time.
What I WANT to happen:
The user selects a category (Animals or Foods) from a drop-down box and clicks Next once. The appropriate ui component will render and display. Then the Next button should be disabled (grayed-out) whenever the right box of the Chooser Input component is empty. Only when the user has at least one selection in the right box, should Next button be enabled and the user may click it.
The PROBLEM: After the Chooser Input component is rendered, the right box is empty, but Next is NOT disabled. Here is the error:
Warning in run(timeoutMs) :
Unhandled error in observer: argument is of length zero
observeEvent(input$widget2)
Below are a demo ui.R and sever.R to recreate my problem. (However, I will be implementing the solution into a larger, more complex GUI.) The code uses shinyBS, so you will first need to install the package and load the library. The code also uses chooserInput, which requires two files: chooser.R and www/chooser-binding.js. See the following link for more information:
http://shiny.rstudio.com/gallery/custom-input-control.html
ui
### The following libraries need to be loaded BEFORE runApp()
### library(shiny)
### library(shinyBS)
source("chooser.R") # Used for Custom Input Control UI component (chooserInput)
# chooser.R is saved in the same location as the ui.R and server.R files
# chooserInput also requires chooser-binding JScript script file, which should be located within "www" folder
shinyUI(navbarPage("navbarPage Title",
tabPanel("tabPanel Title", titlePanel("titlePanel Title"),
fluidPage(
#### NEW ROW #####################################################################################################
fluidRow(wellPanel(
# Instructions for initial screen
conditionalPanel(condition = "input.ButtonNext == 0", tags$b("Step 1: Choose category and click 'Next'")),
# Instructions for 'Foods'
conditionalPanel(condition = "input.ButtonNext == 1 && input.widget1 == 'Foods'", tags$b("Step 2: Move Food(s) of interest to the right box and click 'Next'")),
# Instructions for 'Animals'
conditionalPanel(condition = "input.ButtonNext == 1 && input.widget1 == 'Animals'", tags$b("Step 2: Move Animals(s) of interest to the right box and click 'Next'"))
)),
#### NEW ROW #####################################################################################################
fluidRow(
# Drop down box for first selection
conditionalPanel(
condition = "input.ButtonNext == 0",
selectInput("widget1", label = "",
choices = c("Foods",
"Animals"))),
# This outputs the dynamic UI components based on first selection
uiOutput("ui1")
),
#### NEW ROW #####################################################################################################
fluidRow(tags$hr()), # Horizontal line separating input UI from "Next" button
#### NEW ROW #####################################################################################################
fluidRow(
column(1, offset=10,
# UI component for 'Next' button
conditionalPanel(condition = "input.ButtonNext < 2", bsButton("ButtonNext", "Next"))
),
column(1,
HTML("<a class='btn' href='/'>Restart</a>")
)
)
) # End of fluidPage
) # End of tabPanel
)) # End of navbarPage and ShinyUI
server
shinyServer(function(input, output, session) {
# Widget to display when number of clicks of "Next" button (ButtonNext) = 1
output$ui1 <- renderUI({
if(input$ButtonNext[1]==1) {
print("I am in renderUI") # Used to help debug
# Depending on the initial selection, generate a different UI component
switch(input$widget1,
"Foods" = chooserInput("widget2", "Available frobs", "Selected frobs", leftChoices=c("Apple", "Cheese", "Carrot"), rightChoices=c(), size = 5, multiple = TRUE),
"Animals" = chooserInput("widget2", "Available frobs", "Selected frobs", leftChoices=c("Lion", "Tiger", "Bear", "Wolverine"), rightChoices=c(), size = 5, multiple = TRUE)
)
}
}) # End of renderUI
# Disable "Next" button when right side of multi select input is empty
observeEvent(input$widget2, ({
widget2_right <- input$widget2[[2]]
print(widget2_right) # Used to help debug
if(widget2_right == character(0)) {
updateButton(session, "ButtonNext", disabled = TRUE)
} else {
updateButton(session, "ButtonNext", disabled = FALSE)
}
})) # End of observeEvent
}) # End of shinyServer
A similar question (link below) mentioned using Priorities and Resume/Suspend but no example was provided. If that is a valid solution to my problem, please provide some code.
R shiny Observe running Before loading of UI and this causes Null parameters
EXTRA NOTE: The code provided is a small demo recreated from a much larger GUI that I developed for the user to make a series of selections, clicking 'Next' between each selection. Depending on the selections they make each step, new choices are generated from a csv file. Therefore, the ui component that is rendered and displayed is dependent on how many times the user has clicked 'Next' and which selections they've previously made. In the end, the selections are used to sort a large data set so the user can plot only the data they are interested in. The dual conditions are why I used conditionalPanel and the VALUE of the actionButton to render and display the current ui component that the user needs. My code works (except for the problem above - HA!). However, I have read that it is poor coding practice to use the VALUE of an actionButton. If there are any suggestions for another method to handle the dual conditions, please let me know.
In server.R, I replaced
if(widget2_right == character(0))
with
if(length(widget2_right)==0)
and now the program works as I wanted it to.
When the right-box is empty, widget2_right = character(0). I learned that comparing vectors to character(0) results in logical(0), not TRUE or FALSE. However, length(character(0)) = 0. Therefore, if(length(widget2_right)==0) will be TRUE whenever no selections are in the right-box.