Why am I getting 'server not found' error in my shiny app? - r

I'm trying to learn shiny on my own and it's been very fun so far. I'm trying to plot a singular point on a graph with both inputs coming from the user. I am getting a "Error in shinyApp(ui = ui, server = server) : object 'server' not found". Here's my code:
ui <- fluidPage(
titlePanel("Title"),
sidebarPanel(
sliderInput(inputId ="x1", 'I', min = 4, max = 12, value = 4),
sliderInput(inputId = "y1", 'Y', min = 0, max = 10, value = 1)),
plotOutput("Scale")
)
server() <- function(input, output){
output$Scale <- renderPlot({
ggplot(aes_string(x = input$x1, y = input$y1))+
geom_point() })
}
shinyApp(ui = ui, server = server)

Here is a complete working example, I hope this will help.
The slider inputs will provide numerical information for your plot. This might be easier to conceptualize if placed in a data frame (see below).
The aes aesthetic mapping provides information on x and y axis for your plot, and uses data to indicate dataset to use for plot.
Finally, added limits to appreciate the point moving around the graph with slider changes (otherwise, the axis will automatically rescale).
Lots more you can learn on ggplot2 here:
https://ggplot2.tidyverse.org/
library(ggplot2)
library(shiny)
ui <- fluidPage(
titlePanel("Title"),
sidebarPanel(
sliderInput(inputId ="x1", 'I', min = 4, max = 12, value = 4),
sliderInput(inputId = "y1", 'Y', min = 0, max = 10, value = 1)),
plotOutput("Scale")
)
server <- function(input, output){
output$Scale <- renderPlot({
my_data <- data.frame(x = input$x1, y = input$y1)
ggplot(aes(x = x, y = y), data = my_data)+
geom_point() +
xlim(4, 12) +
ylim(0, 10)
})
}
shinyApp(ui = ui, server = server)

Related

R syntax problems -- part 2 redux

All I have is a csv file which has rows of monthly dates and columns that are numerical whole number counts.
All I want to do is have the user select a category e.g. number of chats and have it make a plot of the time series.
The uiOutput simply won't work regardless of where I put it. I keep getting errors like
object server not found, object UI not found Error in output$regionSel = renderUI(selectInput("region", "Type of Questions:", :
object 'output' not found
I have spent four days on this and am about to give up as this seems not a solvable problem even though I see lots of examples of much more complex interactions. I have read tutorials and watched youtube videos on this endlessly with no positive effect.
Is this because I am using dates and R has a problem with dates?
UI
# Rely on the 'WorldPhones' dataset in the datasets
# package (which generally comes preloaded).
library(datasets)
library(ggplot2)
library(readr)
oboler_data <- read_csv(file = "C:/Users/12083/Desktop/ref.csv")
rdate <- as.Date(oboler_data$DATE,"%m/%d/%y")
# Use a fluid Bootstrap layout
fluidPage(
# Give the page a title
titlePanel("Teephones by region"),
# Generate a row with a sidebar
sidebarLayout(
# Define the sidebar with one input
sidebarPanel(
uiOutput("regionSel")
#selectInput("region", "Region:",
# choices=colnames(oboler_data)),
# ),
# Create a spot for the barplot
mainPanel(
plotOutput("myPlot")
)
#)
#)
server
# Rely on the 'WorldPhones' dataset in the datasets
# package (which generally comes preloaded).
library(datasets)
library(ggplot2)
oboler_data <- read_csv(file = "C:/Users/12083/Desktop/ref.csv")
rdate <- as.Date(oboler_data$DATE,"%m/%d/%y")
# Define a server for the Shiny app
function(input, output) {
output$regionSel = renderUI(selectInput("region", "Type of Questions:",
choices=colnames(oboler_data)))
# Fill in the spot we created for a plot
output$myPlot = renderPlot({
# Render a barplot
ggplot(data = oboler_data, aes_string(x = "rdate", y = input$regionSel)) +
geom_point() +
labs(x = "Date",
y = "Total Transactions",
title = "Library Data",
subtitle = "July 2020-June 2021")
})
You have left out the assignment of the ui and server functions to the objects ui and server. So write ui <- FluidPage() and server <- function(input, output) instead FluidPage() and function(input, output). This explains the first two error codes. Finally, in aes_string(x = "rdate", y = input$regionSel) I think that you need to refer to input$region: this is the id of the selectInput widget. regionSel is the id related to the uiOutput. When using dynamic ui you need to keep these id's apart.
Once you fix that things will work. Here's a simple shiny application that does what you are after.
library(shiny)
library(dplyr)
library(tibble)
library(ggplot2)
data <- tibble(
DATE = seq.Date(from = as.Date("2020/01/01"), to = as.Date("2020/06/19"), by = "day"),
VAR1 = seq(1, 171, 1) + round(runif(n = 171, min = 0, max = 100), 0),
VAR2 = seq(1, 171, 1) + round(runif(n = 171, min = 0, max = 100), 0),
VAR3 = seq(1, 171, 1) + round(runif(n = 171, min = 0, max = 100), 0),
VAR4 = seq(1, 171, 1) + round(runif(n = 171, min = 0, max = 100), 0),
VAR5 = seq(1, 171, 1) + round(runif(n = 171, min = 0, max = 100), 0)
)
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("Library Statistics"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
uiOutput("select")
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot")
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
output$select <- renderUI(
selectInput(inputId = "select_question",
label = "Type of question",
choices = data %>% select(-DATE) %>% colnames(.)
))
output$distPlot <- renderPlot({
req(input$select_question)
var <- input$select_question
ggplot(data = data, aes_string(x = "DATE", y = var)) +
geom_point() +
labs(x = "Date",
y = "Total Transactions",
title = "Library Data",
subtitle = "July 2020-June 2021")
})
}

R Shiny ggplot reactive to dateRangeInput

I am relatively new to R, and I'm trying to build a reactive ggplot in Shiny where the X-axis (dates) is reactive to a dateRangeInput in the UI. I've been googling everywhere, but every thing I try returns an error.
In the ggplot, the aes() calls from a dataset called datecorrected_totals, where x is the dates, and y=load are the two values that I would like to be reactive to the dateRangeInput so the ggplot will adjust the scale based on the period within the daterangeinput.
library(tidyverse)
library(shiny)
library(tidyr)
library(lubridate)
library(zoo)
data <- read_csv("--")
# Define UI ----
ui <- fluidPage(
titlePanel("--"),
sidebarLayout(
sidebarPanel(
h3("Calculator"),
dateRangeInput("dates", label = "Dates",
start = ("10-18-2018"),
end = max("05-29-2019"),
min = min("10-18-2018"),
max = max("05-29-2019"),
format = "mm-dd-yyyy"),
sliderInput("slider_a", label = "--",
min = 0,
max = 7,
value = 0),
sliderInput("slider_c", label = "--",
min = 7,
max = 42,
value = 7)
),
mainPanel(plotOutput('bar_chart'))
)
)
# Define server logic ----
server <- function(input, output, session) {
RE <- reactive({
})
output$bar_chart <- renderPlot(
ggplot(data = datecorrected_totals, aes(x = x, y = load)) +
geom_bar(stat = "identity")
)
}
# Run the app ----
shinyApp(ui = ui, server = server)
You need to filter the original dataset by the input dates. In this example data would be your original dataset.
RE <- reactive({
data %>%
filter(x>=input$dates[1] & x<=input$dates[2])
})
output$bar_chart <- renderPlot(
ggplot(data = RE(), aes(x = x, y = load)) +
geom_bar(stat = "identity")
There is no need to create a separate reactive() expression (unless required otherwise). The filter can be applied directly in renderPlot(). Thus, output$bar_chart becomes
output$bar_chart <- renderPlot(
datecorrected_totals %>%
filter(between(x, input$dates[1], input$dates[2])) %>%
ggplot(aes(x = x, y = load)) +
geom_bar(stat = "identity")
)
Below is a self-contained minimal reproducible example:
library(tidyverse)
library(lubridate)
library(shiny)
datecorrected_totals <- tibble(x = seq(as.Date("2018-10-18"), as.Date("2019-05-29"), length.out = 10L),
load = day(x))
# Define UI ----
ui <- fluidPage(
titlePanel("--"),
sidebarLayout(
sidebarPanel(
h3("Calculator"),
dateRangeInput("dates", label = "Dates",
start = mdy("10-18-2018"),
end = mdy("05-29-2019"),
min = mdy("10-18-2018"),
max = mdy("05-29-2019"),
format = "mm-dd-yyyy"),
),
mainPanel(plotOutput('bar_chart'))
)
)
# Define server logic ----
server <- function(input, output, session) {
output$bar_chart <- renderPlot(
datecorrected_totals %>%
filter(between(x, input$dates[1], input$dates[2])) %>%
ggplot(aes(x = x, y = load)) +
geom_col()
)
}
# Run the app ----
shinyApp(ui = ui, server = server)
Note that the date strings have been coerced to valid Date objects by calling mdy() to avoid error messages.
In addition, geom_bar(stat = "identity") has been replaced by geom_col().

R Shiny animation scatterplot speed performance

I want to make an animation in R Shiny where my scatter plot is progressively updated at each iteration, here is my current plot
library(shiny)
library(plotly)
ui <- fluidPage(
titlePanel(""),
sidebarLayout(
sidebarPanel(
actionButton("launch", "Launch Simulation"),
radioButtons("display","Show every iteration", selected = 10,
choices = c(1,5,10,50),inline = FALSE),
numericInput("iter","Maximum number of iterations", value = 2000,
min = 500,max = 5000, step = 500)
),
mainPanel(
plotlyOutput('plot')
)
)
)
server <- function(input, output) {
rv <- reactiveValues(i = 0,
df = data.frame(x = -1,y = -1))
observeEvent(input$launch,{
rv$i = 0
rv$df = data.frame(x = runif(5000, min = -1,max = 1),
y = runif(5000, min = -1,max = 1))
})
observe({
isolate({
rv$i = rv$i + as.numeric(input$display)
})
if ((rv$i < input$iter)&input$launch){
invalidateLater(0)
}
})
output$plot <- renderPlotly({
df = data.frame(x = 0,y = -1)
df = rbind(df,rv$df)
plot_ly(df[1:(rv$i + 1),], x = ~x, y = ~y,
type = 'scatter', mode = 'markers',
marker = list(size = 4), hoverinfo="none") %>%
layout(showlegend = FALSE)
})
}
shinyApp(ui = ui, server = server)
The code is working fine at the beginning but after around 1000 iterations, the animation becomes very slow. I think the main problem is that because in my code, I have to re-make the plot all over again at each iteration, is there a smoother way to do what I want to do?
(Not necessarily with Plotly but it is important to me that I keep track of the number of the iterations outside of the plot (here rv$i))

R shiny error: Error in html tools::validateCssUnit(height); CSS units must be a single-element numeric or character vector

Am learning to use R shiny and I am trying to create a heatmap that allows the user to specify the height in plotlyOutput to prevent labels from being clumped together. My minimal working code:
library(shiny)
library(plotly)
ui <- fluidPage(
titlePanel("Heatmap"),
sidebarLayout(
sidebarPanel(
sliderInput("mapHeight",
"Heatmap Height",
min = 500,
max = 1000,
value =500),
sliderInput("L", "left adjust", min = 0, max =900, value = 80)
),
mainPanel(plotlyOutput("heatmap"))
)
)
server <- function(input, output) {
output$heatmap <- renderPlotly({
p<- heatmaply(mtcars, plot_method = "plotly")%>%
layout(margin = list(l = input$L, r =50 , t=0, b=90))
#not sure why this is being ignored
ggplotly(p, height = input$mapHeight)
})
}
shinyApp(ui = ui, server = server)
The constraint is related to the heatmaply package, the solution below is temporary while plotly continues to accept the height argument in layout.
Warning: Specifying width/height in layout() is now deprecated.
Please specify in ggplotly() or plot_ly()
You could approach the developer on their GitHub and raise and issue or better yet a pull request with the changes you propose. For the time being, the solution below works with Plotly 4.7.1.
app.R
library(shiny)
library(heatmaply)
ui <- fluidPage(
titlePanel("Heatmap"),
sidebarLayout(
sidebarPanel(
sliderInput("mapHeight", "Heatmap Height",
min = 500, max = 1000, value = 500),
sliderInput("L", "left adjust", min = 0, max = 900, value = 80)
),
mainPanel(plotlyOutput("heatmap"))
)
)
server <- function(input, output) {
output$heatmap <- renderPlotly({
heatmaply(mtcars) %>%
layout(margin = list(l = input$L, r = 50, t = 0, b = 90),
height = input$mapHeight)
})
}
shinyApp(ui = ui, server = server)

Shiny nearPoints() with slider input

I was wondering if I can get rows data using nearPoints() from an interactive graph with slider input. My app.R file looks like:
library('shiny')
library('ggplot2')
dt <-read.csv('file.csv')
ui <- fluidPage(
plotOutput("plot1", height = 550, click = "plot1_click"),
fluidRow(
column(3,
sliderInput("Obs", "Number of Books", min = 1, max = nrow(up), value = 50)
),
column(3, offset = 3,
h4("Legends"),
verbatimTextOutput("selected")
)
)
)
server <- function(input, output) {
mydata <- reactive({
dt[1:as.numeric(input$Obs),]
})
output$plot1 <- renderPlot({
test <- mydata()
ggplot(data = test, aes(x = test[,2], y = test[,1])) + geom_point()
})
output$selected <- renderPrint({
file <- mydata()
nearPoints(file, input$plot1_click, threshold = 10, maxpoints = 1,
addDist = FALSE)
})
}
shinyApp(ui = ui, server = server)
Shiny nearPoints() is working perfectly without this slider input. When I used slider input, I can't get the row data until max. Is there any approach to work with the slider input? Any help is appreciated.
The following code works for me. It seems nearPoints is not able to tell which columns of your dataset are displayed because of the aes(x = test[,2], y = test[,1]) statement. Another possible fix sould be to set the parameters xvar and yvar in nearPoints.
library('shiny')
library('ggplot2')
dt <-mtcars
ui <- fluidPage(
plotOutput("plot1", height = 550, click = "plot1_click"),
fluidRow(
column(3,
sliderInput("Obs", "Number of Cars", min = 1, max = nrow(dt), value = 50)
),
column(3, offset = 3,
h4("Legends"),
verbatimTextOutput("selected")
)
)
)
server <- function(input, output) {
mydata <- reactive({
dt[1:as.numeric(input$Obs),]
})
output$plot1 <- renderPlot({
test <- mydata()
ggplot(data = test, aes(mpg, wt)) + geom_point()
})
output$selected <- renderPrint({
file <- mydata()
nearPoints(file, input$plot1_click, threshold = 100, maxpoints = 1,
addDist = FALSE)
})
}
shinyApp(ui = ui, server = server)
Quick note: Please try to make the code in your question reproducible by using one of the default datasets in R. You can get a list of all available datasets by calling data().

Resources