Home > Blockchain >  R shiny : Color plot using ggplot
R shiny : Color plot using ggplot

Time:05-20

I am creating a plot in R shiny app based on usr input. My filtering of data is a bit complicated and I am unsure fow to pass it to "fill" in ggplot. Below is my code:

data <- reactive({
    req(input$name)
    req(input$type)
    fp %>%
      dplyr::filter(
        name %in% input$name,
        if_any(
          matches(
            str_c('status___', tolower(input$type))), ~
                 .x ==2),
        on_date >= input$Dates[1] &
          off_date <= input$Dates[2]
        ) %>%
      group_by(country) %>%
      summarize(All = n(), .groups = "drop")

  })

##Plot
output$plot <- renderPlot({
    g <- ggplot(data(), aes( y = All, x = country)) #this is wehere I want to use fill to color the plot by "type"
    g   geom_bar(stat = "sum")
  })

CodePudding user response:

When you want to pass reactive input as variables in the ggplot aes() you need to use aes_string().

Try this ggplot code :

geom_bar(data = data(),
         aes_string(y = "All",
                    x = "country",
                    fill = input$type), 
         stat = "sum")

CodePudding user response:

Your problem is that your data() does not contain a column called type. You can verify that, by including a dataTableOutput element to your UI and render data to that. summarize will include only the grouping variables (country in your case) and the aggregated column (All).

Maybe you can provide a full reprex then we cna help better.

  • Related