maudib528
maudib528

Reputation: 71

How can I make an interactive line graph through Shiny?

Problem

I'm new to Shiny, so apologies if I'm way off on this. I'm trying to make an interactive line graph through Shiny so a country can be chosen through drop down list, and then an accompanying line graph can show how suicides/100k people within that country have changed from 1987 to 2015. It looks like I have the Input portion correct, but I am struggling with coding the appropriate output plot. More specifically, I am unsure of where to introduce the reactivity portion of this (where do I put the input$country?).

Data Structure (only first 3 rows)

|year| |age group| |country  | |Suicides Per Age Group Per 100K Population|
|----| |---------| |---------| |------------------------------------------|
|1987| |5 - 14   | |Argentina| |.47                                       |
|1987| |5 - 14   | |Australia| |.28                                       |
|1987| |5 - 14   | |Austria  | |.44                                       |

My current code

library(shiny)
library(tidyverse)

# UI
ui <- fluidPage(selectInput(inputId = "country", 
                            label = "Choose a Country", 
                            choices = data$country[!duplicated(data$country)]), # list of non-duplicated countries
                plotOutput("line"))

server <- function(input, output) {
  output$line <- renderPlot({ggplot(dash_plot_data, 
                                    aes(year, 
                                        `Suicides Per Age Group Per 100K Population`, 
                                        color = age, group = age,
                                        aes())) + 
      geom_line()
  })
}

# View App
shinyApp(ui, server)

Again, I'm not sure where to insert the input$country portion. Any help would be greatly appreciated.

Upvotes: 1

Views: 5041

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388982

Try the following :

library(shiny)
library(dplyr)
library(ggplot2)


ui <- fluidPage(
  selectInput(inputId = "country", 
               label = "Choose a Country", 
                choices = unique(data$Country)), 
                plotOutput("line")
)

server <- function(input, output) {
  output$line <- renderPlot({
    ggplot(data %>% filter(Country == input$country), 
           aes(year, `Suicides Per Age Group Per 100K Population`, 
          color = age, group = age)) + geom_line()
  })
}

Upvotes: 1

Related Questions