How to change the type of graph based off a shiny input?

I'm trying to build a shiny app that changes the plot/graph type based off the input a use selects.

I have two graphs that are made using the same dataset. One is a bargraph and the other is a piechart.

I have a input where the user can select which type of graph they want to see. But my problem is I can't figure out to get the graph to change to based off the input. Here a screenshot of what I am working with. enter image description here

My desired output would be to have this change to a piechart when the user selects the piechart icon. Like below enter image description here

I just can't figure out to connect inputId in the UI to the server side of the app.

Here is the code I have

#APP
ui <-dashboardPage(
  dashboardHeader(title = "ShinyWidget Plot Change"),
  dashboardSidebar(),
  dashboardBody(
   fluidRow(
    box(plotOutput("plot1", height = 250)),
    box(checkboxGroupButtons(
      inputId = "change_plot",
      label = "Visualize:", 
      choices = c(`<i class='fa fa-bar-chart'></i>` = "bar", 
                  `<i class='fa fa-pie-chart'></i>` = "pie"),
      justified = TRUE)
        )
      )
    )
  )
)




server <- function(input, output) { 


  

  
output$plot1 <- renderPlot({ 
  ggplot(data,aes(Country, Count)) + 
  geom_bar(stat = "identity")
})
  
}
shinyApp(ui, server)

#graphs
barplot <- ggplot(data,aes(Country, Count)) + 
  geom_bar(stat = "identity")

piechart <- ggplot(data,aes(x="", y=Count, fill=Country)) + 
  geom_bar(stat = "identity", width = 1) + 
  coord_polar("y", start=0)

Solution 1:

You could achieve your desired result via an if ... else ... condition like so. Additionally as your buttons should switch the type of plot I switched to a radioGroupButtons:

Using some fake example data based on mtcars:

library(shiny)
library(shinydashboard)
library(shinyWidgets)
library(ggplot2)
library(dplyr)

data <- mtcars %>% 
  count(cyl) %>%
  mutate(cyl = factor(cyl)) %>% 
  rename(Country = cyl, Count = n)

# APP
ui <- dashboardPage(
  dashboardHeader(title = "ShinyWidget Plot Change"),
  dashboardSidebar(),
  dashboardBody(
    fluidRow(
      box(plotOutput("plot1", height = 250)),
      box(radioGroupButtons(
        inputId = "change_plot",
        label = "Visualize:",
        choices = c(
          `<i class='fa fa-bar-chart'></i>` = "bar",
          `<i class='fa fa-pie-chart'></i>` = "pie"
        ),
        justified = TRUE,
        selected = "bar"
      ))
    )
  )
)

server <- function(input, output) {
  output$plot1 <- renderPlot({
    if (input$change_plot %in% "bar") {
      ggplot(data, aes(Country, Count, fill = Country)) +
        geom_bar(stat = "identity")
    } else {
      ggplot(data, aes(x = "", y = Count, fill = Country)) +
        geom_bar(stat = "identity", width = 1) +
        coord_polar("y", start = 0)
    }
  })
}
shinyApp(ui, server)
#> 
#> Listening on http://127.0.0.1:3370