Created
October 8, 2020 04:14
-
-
Save aagarw30/0a1d46b8ab9fdfec09ff90257b7434c4 to your computer and use it in GitHub Desktop.
USAArrests simple R Shiny App
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Load required packages | |
library(shiny) | |
library(ggplot2) | |
library(dplyr) | |
# Adding State column to the original dataset for easy data manipulation at a later stage | |
states = row.names(USArrests) | |
crimedata = USArrests %>% | |
mutate("State" = as.factor(states)) # convert State to a factor variable | |
ui <- fluidPage( | |
selectInput(inputId = "state", | |
label = "Select States(s)", | |
choices = levels(crimedata$State), | |
multiple = TRUE, | |
selected = levels(crimedata$State)), | |
selectInput(inputId = "crime", label = "Select the Crime", | |
choices = c("Murder","Assault", "Rape" )), | |
actionButton(inputId ="update" , label = "Update & Show Plot"), | |
plotOutput("bar") | |
) | |
server <- function(input, output, session) { | |
## Reactive function to subset the data based on the selected states by the user and on click of the button | |
s_data <- eventReactive(input$update, | |
crimedata %>% | |
filter(State %in% input$state)) | |
## Render plot for the ggplot | |
output$bar <- renderPlot({ | |
p = ggplot(data=s_data(), aes(x=State, y=get(input$crime))) + | |
geom_bar(stat = "identity") + | |
xlab("Selected States") + | |
ylab(paste(("Selected Crime: "), input$crime)) + | |
ggtitle("States Bar Plot with Crime") + | |
theme(axis.text.x = element_text(angle = 45, vjust = 0.5, hjust=1)) | |
print(p) | |
}) | |
} | |
shinyApp(ui, server) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment