Create a scatter plot interactive application. In this application, use the census data from earlier in the book, and let the user determine the X-axis, the Y-axis, the color (optional), and the size based on what the user would like to see. To do this, you will need multiple-choice menus, one for each selection the user needs to make. You can do this by following the direction written in the text book. Enjoy.
For your information:
The data is available through this link:
Add all of your libraries that you use for this assignment here.
# Add your library below.
library(shiny)
## Warning: package 'shiny' was built under R version 4.2.3
library(ggplot2)
Build the UI below.
ui <- fluidPage(
titlePanel("Interactive Census Data Scatter Plot Application"),
sidebarLayout(
sidebarPanel(
selectInput("x", "X-axis", choices = c("Select" = "")),
selectInput("y", "Y-axis", choices = c("Select" = "")),
selectInput("color", "Color", choices = c("None" = "", "Select" = "")),
selectInput("size", "Size", choices = c("None" = "", "Select" = "")),
actionButton("update", "Update Plot")
),
mainPanel(
plotOutput("scatterPlot")
)
)
)
Build the Server below.
server <- function(input, output, session) {
censusData <- reactive({
url <- "http://www2.census.gov/programs-surveys/popest/tables/2010-2011/state/totals/nst-est2011-01.csv"
census <- read.csv(url, skip = 2, nrows = 52, stringsAsFactors = FALSE)
# Removing commas and convert to numeric for population columns
census[, 3:6] <- lapply(census[, 3:6], function(x) as.numeric(gsub(",", "", x)))
# Renaming columns
names(census) <- c("State", "April 1, 2010", "Estimates Base", "2010", "2011")
return(census)
})
observe({
updateSelectInput(session, "x", choices = names(censusData()))
updateSelectInput(session, "y", choices = names(censusData()))
updateSelectInput(session, "color", choices = c("None" = "", names(censusData())))
updateSelectInput(session, "size", choices = c("None" = "", names(censusData())))
})
# Rendering scatter plot
output$scatterPlot <- renderPlot({
req(input$update)
plot_data <- censusData()
# Selecting variables for x and y axes
x_var <- input$x
y_var <- input$y
# Filtering out NA values for color and size columns
if (input$color != "") {
plot_data <- plot_data[!is.na(plot_data[[input$color]]), ]
}
if (input$size != "") {
plot_data <- plot_data[!is.na(plot_data[[input$size]]), ]
}
# Creating scatter plot
ggplot(plot_data, aes_string(x = x_var, y = y_var)) +
geom_point(aes(color = input$color, size = input$size)) +
labs(x = x_var, y = y_var) +
theme_minimal()
})
}
Deploy the shiny app.
shinyApp(ui = ui, server = server)