0
votes

I created an interactive plot using shiny and ggplot2. I use radioButtons where I have 4 plots and by choosing one of the two possible buttons for each of the 2 radioButtons a plot (Age/Gender) is printed.

ui <- fluidPage(
            titlePanel(title=h3("Life", align="center")),
            sidebarPanel( 
            radioButtons('gender', "Choose Gender:", choices = c('Males' = 'm', 'Females' ='f')),
            radioButtons('age', "Choose Age:", choices = c('At birth' = 'b', 'At Age 65' ='s'))),

            mainPanel(plotOutput("plot2"))
            )

. server <- function(input,output){

output$plot2<-renderPlot({
    if (input$gender == 'f' & input$age == 'b') { 
        ggplot(df, aes(x = year, y = value, group = variable, color=variable)) +  ...

In order to print the 2nd:

if (input$gender == 'm' & input$age == 'b') 
    { 
        ggplot() ...}

In order to print the 3rd plot:

if (input$gender == 'm' & input$age == 's') 
    { ggplot ...}

In order to print the 4 plot:

if (input$gender == 'm' & input$age == 's') 
    {etc.... }

I have 4 dataframes for each plot, the plots without shiny works fine.

My problem is that the shiny ui shows only the last plot, for the other 3 the output is blank?

What I am doing wrong???

1

1 Answers

1
votes

You have to use else if:

output$plot2 <- renderPlot({
    if (input$gender == 'f' && input$age == 'b') { 
        ggplot(df, aes(x = year, y = value, group = variable, color=variable)) + ...
    } else if (input$gender == 'm' && input$age == 'b') { 
        ggplot() ...
    } else if ....
})

Otherwise your expression returns only the last if, and it is NULL is the condition is not met.