Creating Interactive Shiny App

  1. Select X and Y Axes: Users can choose the variables for the X and Y axes from dropdown menus.
  2. Select Plot Type: They can select between Scatter Plot, Line Plot, and Bar Plot using radio buttons.
  3. Select Data Range: Specify a range of data based on the “mpg” variable using sliders.
  4. Show Data Table: Users can toggle the display of a data table showing the filtered dataset using a checkbox.
  5. Download Data: Download the displayed data table as a CSV file.
  6. Additional Options: Users can customize the appearance of the plot by selecting point shapes and colors, inputting a custom plot title, and updating the plot with the selected customizations using an action button.
  7. Custom CSS Styles: The app includes custom CSS styles to enhance the appearance of the buttons.
R
library(shiny)
library(ggplot2)
library(DT)

# Define UI
ui <- fluidPage(
  titlePanel("mtcars Data Exploration"),
  
  sidebarLayout(
    sidebarPanel(
      selectInput("x_axis", "Select X Axis:", 
                  choices = c("mpg", "cyl", "disp", "hp", "drat", "wt", "qsec", "vs", 
                              "am", "gear", "carb")),
      selectInput("y_axis", "Select Y Axis:", 
                  choices = c("mpg", "cyl", "disp", "hp", "drat", "wt", "qsec", "vs", 
                              "am", "gear", "carb")),
      radioButtons("plot_type", "Select Plot Type:", 
                   choices = c("Scatter Plot", "Line Plot", "Bar Plot"), 
                   selected = "Scatter Plot"),
      sliderInput("data_range", "Select Data Range:",
                  min = min(mtcars$mpg), max = max(mtcars$mpg),
                  value = c(min(mtcars$mpg), max(mtcars$mpg)), step = 1),
      actionButton("plotBtn", "Plot"),
      checkboxInput("showTable", "Show Data Table", value = FALSE),
      downloadButton("downloadData", "Download Data"),
      hr(),
      # Additional options
      selectInput("point_shape", "Select Point Shape:", 
                  choices = c(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 
                              16, 17, 18, 19, 20)),
      selectInput("point_color", "Select Point Color:", 
                  choices = c("red", "blue", "green", "yellow", "orange", "purple", 
                              "black")),
      textInput("plot_title", "Plot Title:", value = "Custom Plot"),
      actionButton("updateBtn", "Update Plot")
    ),
    
    mainPanel(
      plotOutput("plot"),
      DTOutput("dataTable")
    )
  ),
  # Add custom CSS styles
  tags$head(tags$style(HTML("
    .btn-primary { background-color: #FF5733; border-color: #FF5733; }
    .btn-primary:hover { background-color: #FF7851; border-color: #FF7851; }
    .btn-primary:focus { background-color: #FF7851; border-color: #FF7851; }
    .btn-primary:active { background-color: #FF7851; border-color: #FF7851; }
  ")))
)

# Define server logic
server <- function(input, output) {
  # Reactive expression to filter data based on selected data range
  filteredData <- reactive({
    subset(mtcars, mpg >= input$data_range[1] & mpg <= input$data_range[2])
  })
  
  # Generate plot based on selected options
  output$plot <- renderPlot({
    plot_data <- filteredData()
    if (input$plot_type == "Scatter Plot") {
      ggplot(plot_data, aes_string(x = input$x_axis, y = input$y_axis)) +
        geom_point(shape = input$point_shape, color = input$point_color) +
        labs(title = input$plot_title,
             x = input$x_axis, y = input$y_axis) +
        theme_minimal()
    } else if (input$plot_type == "Line Plot") {
      ggplot(plot_data, aes_string(x = input$x_axis, y = input$y_axis)) +
        geom_line(color = input$point_color) +
        labs(title = input$plot_title,
             x = input$x_axis, y = input$y_axis) +
        theme_minimal()
    } else {
      ggplot(plot_data, aes_string(x = input$x_axis)) +
        geom_bar(fill = input$point_color) +
        labs(title = input$plot_title,
             x = input$x_axis, y = "Count") +
        theme_minimal()
    }
  })
  
  # Show/hide data table based on checkbox
  output$dataTable <- renderDT({
    if (input$showTable) {
      filteredData()
    } else {
      NULL
    }
  })
  
  # Download data table as CSV
  output$downloadData <- downloadHandler(
    filename = function() {
      paste("mtcars_data", ".csv", sep = "")
    },
    content = function(file) {
      write.csv(filteredData(), file, row.names = FALSE)
    }
  )
}

# Run the application
shinyApp(ui = ui, server = server)

Output:

R Shiny

R Shiny Examples

Shiny is an R package that allows us to build interactive web applications directly from the R Programming Language. It bridges the gap between data analysis in R and web development, enabling us to create interactive dashboards.

Similar Reads

Basic Structure of Shiny

The UI component defines the layout and appearance of the application, while the server logic dictates how the app responds to user input and generates output....

UI and Server Components

User Interface (UI)...

Shiny Elements

1. Sliders: Sliders let users pick a value by sliding a knob along a track. Great for selecting ranges or adjusting parameters....

Layout Management

Layout management is simply the arrangement and organization of visual elements within a user interface (UI). It involves deciding where to put buttons, text fields, images, and other elements to make them easy to find and use. In Shiny, layout management means using functions like fluidPage() or navbarPage() to structure our app’s layout. These functions help us decide where to place different parts of our app, like the main content, sidebars, or navigation bars....

Interactive plotting

Interactive plotting allows users to engage with data visualizations in real-time. Unlike static plots, interactive plots enable users to:-...

Creating Interactive Shiny App

Select X and Y Axes: Users can choose the variables for the X and Y axes from dropdown menus.Select Plot Type: They can select between Scatter Plot, Line Plot, and Bar Plot using radio buttons.Select Data Range: Specify a range of data based on the “mpg” variable using sliders.Show Data Table: Users can toggle the display of a data table showing the filtered dataset using a checkbox.Download Data: Download the displayed data table as a CSV file.Additional Options: Users can customize the appearance of the plot by selecting point shapes and colors, inputting a custom plot title, and updating the plot with the selected customizations using an action button.Custom CSS Styles: The app includes custom CSS styles to enhance the appearance of the buttons....

Conclusion

Shiny apps provide a user-friendly and interactive way to explore data and create data-driven applications. By combining the power of R programming with web development, Shiny allows users to build dynamic and customizable interfaces without requiring extensive coding knowledge. With its wide range of input widgets, reactive programming capabilities, and seamless integration with popular R packages like ggplot2 and DT, Shiny enables users to create engaging and informative visualizations and dashboards. Whether for data analysis, reporting, or sharing insights, Shiny offers a versatile platform for data exploration and communication....