ggplot2 – how can I compare between two ggplots in R studio in layers ( in other words having two plots over each other and compare them through my inputs )?

We can combine both plots and play around with alpha argument. I added two sliders that enables the user to control the level of transparency of both plots.

  output$plot <- renderPlot({
    ggplot() +
      geom_bar(data = data(), aes(y = output, x = code), stat = "sum", alpha = .5) +
      geom_bar(data = data2(), aes(y = output, x = code), stat = "sum", alpha = .5, fill = "lightblue")
  })

app:

germany_vaccinations_k <- read_tsv("germany_vaccinations_by_state.tsv")

ui <- basicPage(
  # first-input
  selectInput(
    inputId = "sel", label = "Möglichkeit auswählen",
    list("vaccinationsTotal", "peopleFirstTotal", "peopleFullTotal", "peopleBoosterTotal")
  ),

  # second-input
  selectInput(
    inputId = "sel2", label = "Möglichkeit auswählen",
    list("vaccinationsTotal", "peopleFirstTotal", "peopleFullTotal", "peopleBoosterTotal")
  ),
  sliderInput("alpha_sel", "Select First Alpha", min = .01, max = 1, value = 0.5),
  sliderInput("alpha_sel2", "Select Second Alpha", min = .01, max = 1, value = 0.8),


  # the both outputs
  plotOutput("plot")
)



server <- function(input, output, session) {

  # Summarize Data and then Plot
  data <- reactive({
    req(input$sel)
    df <- germany_vaccinations_k %>%
      group_by(code) %>%
      summarise(output = get(input$sel))
    print(df)
  })

  data2 <- reactive({
    req(input$sel2)
    df <- germany_vaccinations_k %>%
      group_by(code) %>%
      summarise(output = get(input$sel2))
    print(df)
  })


  output$plot <- renderPlot({
    ggplot() +
      geom_bar(data = data(), aes(y = output, x = code), stat = "sum", alpha = input$alpha_sel) +
      geom_bar(data = data2(), aes(y = output, x = code), stat = "sum", alpha = input$alpha_sel2, fill = "lightblue")
  })
}

shinyApp(ui, server)

enter image description here

Read more here: Source link