Reputation: 63
Im trying to create a shiny app where a ggplot is the main plot output, and I have gotten it to the point where the users can filter by date using dateRangeInput, as well as select the X and Y axes with selectVarInput. However, in the main ggplot output I would like the plot to have a color aesthetic to separate the different responses based on date. Here is what I have so far, but an error message is returned saying "Aesthetics must be either length 1 or the same as the data (10): colour". Any help would be greatly appreciated!
library(tidyverse)
library(shiny)
sampledf <- tibble(Name = c("John Smith"),
`Test 1` = c("Test 1"),
`Date` = lubridate::as_date(c("2020-04-22","2020-04-22", "2020-04-22", "2020-04-24", "2020-04-24", "2020-04-24", "2020-04-24", "2020-04-26", "2020-04-26", "2020-04-26")),
`Result 1` = rnorm(1:10),
`Result 2` = rnorm(1:10),
`Result 3` = rnorm(1:10))
# Define UI for application
ui <- navbarPage(
"Title",
tabPanel(
"Tab 1",
sidebarPanel(
h4("Inputs"),
selectInput(
"Name_Select",
label = "Select Name",
choices = sampledf$Name,
selected = TRUE
),
dateRangeInput(
"dates",
label = "Dates",
start = min(sampledf$Date),
end = max(sampledf$Date)
),
varSelectInput("X_Axis",
label = "Select Variable 1",
data = sampledf,
),
varSelectInput("Y_Axis",
label = "Select Variable 2",
data = sampledf,
),
)
),
mainPanel(plotOutput("plot")),
tabPanel("Tab2")
)
# Define server logic
server <- function(input, output) {
output$plot <- renderPlot({
Data %>%
filter(sampledf$Date >= input$dates[1], sampledf$Date <= input$dates[2]) %>%
ggplot(mapping = (aes_string(x = input$X_Axis, y = input$Y_Axis))) +
geom_line(color = input$dates) +
geom_point(color = input$dates)
})
}
# Run the application
shinyApp(ui = ui, server = server)
Upvotes: 1
Views: 948
Reputation: 13833
First of all, a minor point: You don't need to include parentheses around aes_string(...)
so it should be mapping = aes_string(...)
, but that's likely not causing the issue, as the error message references color.
The problem is that input$dates
is a dateRangeInput()
, which means it returns a vector of 2 dates (as you referenced correctly in the filter()
command above the plot. You can use dates, but you would need to reference "Date" in the sampledf
dataframe. So in this case, change the last two lines to this and it should work:
geom_line(color = Date) +
geom_point(color = Date)
With that being said, you should realize that the color scheme for a particular date will depend on the range selected with this code. That means that if you have 10 days in your range, "day #4" will not always be the same color with this code, but will depend on the range of the date selected. If you are cool with that, go ahead, but you may want to include a scale_color_manual
function to set the color based on the date explicitly.
Upvotes: 1