Shiny reactive data plotting using ggplot

Hi,
I am creating a shiny application consisting in plotting data from different datasets.
Basically user has to choose two times using one radiobutton and one selectinput for getting desired plot. This is my code for creating reactive data:

data_intacc <- reactive({
# Return the appropriate data source depending on
# the chosen radio button
if (input$ind_access == "reason_access" & input$dissag_access == "age_access") {
data <- lim_internet %>% select("Reason", "9–11", "12–14", "15–17")
} else if (input$ind_access == "reason_access" & input$dissag_access == "gender_access") {
data <- lim_internet %>% select(Reason, Male, Female)
} else if (input$ind_access == "reason_access" & input$dissag_access == "reason_access") {
data <- lim_internet %>% select(Reason, Total)
}
else if (input$ind_access == "places_access" & input$dissag_access == "age_access") {
data <- place_access %>% select("Place", "9–11", "12–14", "15–17")
} else if (input$ind_access == "places_access" & input$dissag_access == "gender_access") {
data <- place_access %>% select(Place, Male, Female)
} else if (input$ind_access == "places_access" & input$dissag_access == "reason_access") {
data <- place_access %>% select(Place, Total)
}
else if (input$ind_access == "freq_access") {
data <- device_freq}

return(data)

})

I have created one function for plotting:

output$gmplot <-renderPlot({

p1 <- ggplot(data = data_intacc(), aes(x, y, fill= Total)) +geom_bar(stat= "identity")
print(p1)

})

and in my ui.R I have:

plotOutput("gmplot")

My problem is that based on user input data is different, so I need to figure out one way to subset reactive data inside ggplot2 to define aes(x, y).

Any idea how to deal with this case?

Thank you

Not sure if this is what you are looking fore but you can pass your input values into aes() using the aes_string() function. So:

p1 <- ggplot(data = data_intacc(), aes_string(input$dissag_access , input$ind_access , fill= Total)) +geom_bar(stat= "identity")
print(p1)

Have a look at the below thread at Stack overflow:

Alternatively you can wrap your aes() function in an if statement:

p1 <- ggplot(data = data_intacc(), 
{if (input$ind_access == "reason_access" & input$dissag_access == "age_access") {
aes(x=value_1, y=value_2, fill= Total)
}}
{if (input$ind_access == "reason_access" & input$dissag_access == "gender_access") {
aes(x=value_3, y=value_4, fill= Total)
}}
)
+geom_bar(stat= "identity")
print(p1)
1 Like

Thank you @noveld. With some minor changes the second solution worked great.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.