I am trying to make a shiny app that will allow to color the points of the scatterplot based on the selected categorical variables.
library(shiny)
data<-data.frame(iris)
ui <- navbarPage("Summary",
tabsetPanel(
tabPanel("Graph", fluid=T,
fluidPage(
sidebarPanel(selectInput(inputId = "varColor",
label = "Color",
choices = c("Species", "Other_Category"),
selected = "Species")),
mainPanel(plotOutput(outputId = "plot"))
)
)
)
)
server <- function(input, output) {
p<-reactive({ggplot(data,
aes(y = Sepal.Length, x = Petal.Length))
# This Part needs help
geom_point(aes( input$varColor)) })
output$plot <- renderPlot({
p()
})
}
shinyApp(ui, server)
I think that now, the program reads the color selection from the input as a string, instead of taking it as category. Thank you for help.
CodePudding user response:
The issue is that input$colorVar
is simply a character. Hence, ggplot2 will treat this character value as the one and only category. Hence, you end up with one color.
To tell ggplot2 that it should color the plot according to the data column whose named is stored in input$colorVar
you could make use of the so called .data
pronoun provided by the rlang
package, i.e. do aes(color = .data[[input$varColor]])
:
library(shiny)
library(ggplot2)
data <- data.frame(iris)
ui <- navbarPage(
"Summary",
tabsetPanel(
tabPanel("Graph",
fluid = T,
fluidPage(
sidebarPanel(selectInput(
inputId = "varColor",
label = "Color",
choices = c("Species", "Other_Category"),
selected = "Species"
)),
mainPanel(plotOutput(outputId = "plot"))
)
)
)
)
#> Warning: Navigation containers expect a collection of `bslib::nav()`/
#> `shiny::tabPanel()`s and/or `bslib::nav_menu()`/`shiny::navbarMenu()`s. Consider
#> using `header` or `footer` if you wish to place content above (or below) every
#> panel's contents.
server <- function(input, output) {
p <- reactive({
ggplot(
data,
aes(y = Sepal.Length, x = Petal.Length)
)
# This Part needs help
geom_point(aes(color = .data[[input$varColor]]))
})
output$plot <- renderPlot({
p()
})
}
shinyApp(ui, server)
#>
#> Listening on http://127.0.0.1:3070