I’m building an app that uses input widgets to filter data of interest, and conditionalPanels
to determine what the plotOutput
should be using ggplot2
as the plot generator. The ui
works, and I suspect the issue is caused in the server
section of my app.
The desired result would be a density plot for “univariate” plot types, and a scatter plot for “bivariate” plot types. Right now, nothing appears in the main panel.
library(shiny)
library(ggplot2)
# plotting functions; these work as-is
univar_plot <- function(df, var) {
# assign variable to axis
p <- df |>
ggplot(aes(get(var)))
# create density plot
p <- p + geom_density(alpha=0.5)
p + xlab(var)
}
scatter_plot <- function(df, x, y) {
p <- df |>
ggplot(aes(get(x), get(y)))
# create scatter plot
p <- p + geom_point()
p + xlab(x) + ylab(y)
}
# Define UI for application that draws plots for single variables or pairs of variables
ui <- fluidPage(
# Application title
titlePanel("MT Cars Variable Explorer"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
sliderInput("cylinder", "Cylinders", 4, 8, value = 4),
selectInput("gear", "Gears",
choices = c(3, 4, 5)
),
selectInput("relation", "Relationship Type",
c("univariate", "bivariate")
),
conditionalPanel(
condition = "input.relation == 'univariate'",
selectInput(
"univariable", "Select variable",
c("mpg", "disp", "wt", "hp")
)
),
conditionalPanel(
condition = "input.relation == 'bivariate'",
selectInput(
"x", "X variable",
c("mpg", "disp", "wt", "hp")
),
selectInput(
"y", "Y variable",
c("mpg", "disp", "wt", "hp")
)
)
),
mainPanel(plotOutput("plot"))
)
)
# Define server logic required to draw plots based on relationship types
server <- function(input, output) {
inputData <- reactive({
mtcars[mtcars$gear == input$gear & mtcars$cyl == input$cylinder, ]
}
)
output$Plot <- renderPlot({
if(input$relation == "univariate") {
univar_plot(inputData(), input$univariable)
}
if(input$relation == "bivariate") {
scatter_plot(inputData(), input$x, input$y)
}
})
}
# Run the application
shinyApp(ui = ui, server = server)