#- Dear Friends! Please help me
#- I want to display plot immediately, and then after pressing button, draw points on plot.
#- my problems:
#- first plot is displayed immediately, but does not draw a min point
#- second plot is NOT displayed immediately, only after click button, and I see min point
library(shiny)
#------------------ function for investigation
mfun <- function(x) {
return((x + 3)^2 * sin(x - 2))
}
#------------------ function for searching min value f(x)
findMin <- function(mini, maxi, f) {
x <- runif(min = mini, max = maxi, n = 1e+7)
return(x[which.min(f(x))])
}
#-------------------------
ui <- fluidPage(
#-- set range for plot
numericInput(inputId = 'xmin', label = 'x left', value = 0),
numericInput(inputId = 'xmax', label = 'x right', value = 15),
#-- button for calc min value
actionButton(inputId = 'btMin', label = 'find min f(x)'),
#--- results
textOutput(outputId = 'xlocmin'),
textOutput(outputId = 'ylocmin'),
#-- first plot is displayed immediately, but does not draw a min point
plotOutput(outputId = 'plot_1', width = '100%', height = '300px'),
#-- second plot is NOT displayed immediately, only after press button!
plotOutput(outputId = 'plot_2', width = '100%', height = '300px')
)
#=================================
server <- function(input, output) {
#----- define points for plot()
xgr <- reactive({seq(
from = input$xmin,
to = input$xmax,
by = (input$xmax - input$xmin) / 200)
})
#----- calc xlocmin in range input$xmin and input$xmax for our function
xlocmin <- eventReactive(eventExpr = input$btMin,
{findMin(mini = input$xmin, maxi = input$xmax, f = mfun)})
#-------- calc mfun(xlocmin)
ylocmin <- reactive({round(mfun(xlocmin()), 3)})
#------- make output for coordinates point with min value
output$xlocmin <- renderText({paste0('x_min = ', round(xlocmin(), 3))})
output$ylocmin <- renderText({paste0('f(x_min) = ', round(ylocmin(), 3))})
#--------- draw plot without min point
output$plot_1 <- renderPlot(expr = {
plot(x = xgr(),
y = mfun(xgr()),
type = 'l',
lwd = 3,
col = 'red')
}, res = 70)
#--------- draw plot with min point
output$plot_2 <- renderPlot(expr = {
plot(x = xgr(),
y = mfun(xgr()),
type = 'l',
lwd = 3,
col = 'red')
points(x = xlocmin(),
y = ylocmin(),
type = 'p',
pch = 21,
col = 'blue',
bg = 'yellow',
cex = 2)
}, res = 70)
}
shinyApp(ui = ui, server = server)