Trying to sketch a stacked barplot with shiny app in R and would like some assistance. There are two selectinputs, one for the x axis which are agegp, tobgp and alcgp and the distribution variable which are alcgp and tobgp. I just cant quite figure out why its not displaying.
Any help would be greatly appreciated!
I have also provided a sample data set for esoph
esoph <- data.frame(
agegp = c("18", "35", "65"),
alcgp = c("Never", "Current", "Former","Current", "Former","Current"),
tobgp = c("Never", "Current", "Former", "Never", "Current","Former"),
cases = c(50, 75, 30, 40, 60, 25)
)
ui <- fluidPage(
titlePanel("Oesophagus Cancer Risk Dashboard"),
tabsetPanel(
# Stacked Bar Graph
tabPanel("Stacked Bar Graph",
fileInput("upload_graph_data", "Upload CSV file"),
downloadButton("download_graph", "Export Graph (PNG)"),
hr(),
selectInput("x_variable", "X - Variable:",
choices = c("Age", "Tobacco Consumption", "Alcohol Consumption"),
selected = "Age"
),
selectInput("distribution_variable", "Distribution Variable:",
choices = c("Tobacco Consumption", "Alcohol Consumption"),
selected = "Tobacco Consumption"
),
plotOutput("stacked_bar_graph")
)
)
)
server <- function(input, output, session) {
# Stacked Bar Graph
filtered_data <- reactive({
esoph_data <- esoph
# Map X-Variable to appropriate column
x_column <- switch(input$x_variable,
"Age" = "esoph$agegp",
"Tobacco Consumption" = "esoph$tobgp",
"Alcohol Consumption" = "esoph$alcgp"
)
# Filter by selected X-Variable
esoph_data <- esoph_data[, c(x_column, input$distribution_variable)]
# Filter by age group
age_group_filter <- input$age_group
if (age_group_filter[1] > 0) {
esoph_data <- esoph_data %>%
filter(agegp >= age_group_filter[1])
}
if (age_group_filter[2] < 75) {
esoph_data <- esoph_data %>%
filter(agegp <= age_group_filter[2])
}
return(esoph_data)
})
# Rendered stacked bar graph
output$stacked_bar_graph <- renderPlot({
esoph_data <- filtered_data()
esoph_data %>%
group_by(.data[[x_column]], .data[[input$distribution_variable]]) %>%
summarize(total_cases = sum(ncases)) %>%
group_by(.data[[x_column]]) %>%
mutate(percentage = 100 * total_cases / sum(total_cases)) %>%
filter(!is.na(percentage) & percentage != 0) %>%
ggplot(., aes_string(x = x_column, y = "percentage", fill = input$distribution_variable)) +
geom_col(stat = "identity", position = "fill") +
theme_minimal() +
geom_text(aes(label = paste(format(percentage, digits = 1), "%")), size = 4, position = "fill", hjust = 0.5, vjust = 1.1) +
scale_y_continuous(labels = scales::percent_format()) +
labs(
title = paste("Stacked Bar Chart of Case Distribution of", input$distribution_variable, "by", input$x_variable),
subtitle = "Data Source: `esoph`",
x = input$x_variable,
y = "% of Cases",
fill = input$distribution_variable
)
})
}
shinyApp(ui, server)