1

I am trying to figure out how to add multiple graphs to my shiny app. Below is my code for my shiny app which lands on the main page.

library(shiny)
library(markdown)
library(DT)
library(ggplot2)
library(dplyr)
library(plotly)
library(shinythemes)

happiness2015 <- read.csv("2015.csv", stringsAsFactors = TRUE)
happiness2016 <- read.csv("2016.csv", stringsAsFactors = TRUE)
happiness2017 <- read.csv("2017.csv", stringsAsFactors = TRUE)
happiness2018 <- read.csv("2018.csv", stringsAsFactors = TRUE)
happiness2019 <- read.csv("2019.csv", stringsAsFactors = TRUE)
countries_all <- read.csv("countries.csv", stringsAsFactors = TRUE)



# Define UI for application that draws a histogram
ui <- navbarPage(
    theme = shinytheme("readable"),
    title = "World Happiness",
    tabPanel("Plot",
             sidebarPanel(width = 3,
                          br(),
                          span("Data from ", 
                               tags$a("World Happiness Report.", href = "http://worldhappiness.report")),
                          br(), hr(),
                          helpText("Select year"),
                          actionButton("button2015", "2015"),
                          actionButton("button2016", "2016"),
                          actionButton("button2017", "2017"),
                          actionButton("button2018", "2018"),
                          actionButton("button2019", "2019"),
                          br(), br(), 
                          helpText("Choose variables"),
                          uiOutput("variable_1"),
                          uiOutput("variable_2"),
                          br(),
                          helpText("Press command to see multiple countries"),
                          uiOutput("country"),
                          br(), hr(),
                          span("Data source:", 
                               tags$a("Kaggle",
                                      href = "https://www.kaggle.com/unsdsn/world-happiness")),
                          br(), br(),
                          em(

                              span("Code", a(href = "https://github.com/raishamdahya/INFO281", "on GitHub"))
                          )),

             mainPanel(
                 tabsetPanel(
                     tabPanel("Plot",
                              br(),
                              h2(textOutput("year_name_plot")),
                              plotlyOutput("scatterplot", 
                                           height = 800)
                     ),

                     tabPanel("Table", 
                              br(),
                              DT::dataTableOutput("results_table")
                     ),

                     tabPanel(textOutput("tab_name_rankings"),
                              h1(textOutput("year_name")),
                              h2("Top 10"),
                              wellPanel( 
                                  dataTableOutput("rank_table_top")),
                              br(), 
                              h2("Bottom 10"),
                              wellPanel(
                                  dataTableOutput("rank_table_bottom"))
                     )
                 )
             )),

    tabPanel("About"))





##############################################
### SERVER STARTS HERE #######################
##############################################

server <- function(input, output, session) {

    output$variable_1 <- renderUI({
        selectInput("variable_1", "Y-variable:", 
                    choices = c("Happiness.Rank", "Happiness.Score", "Economy", 
                                "Family", "Health", "Freedom", "Government.Corruption", 
                                "Generosity", "Dystopia.Residual"), selected = "Happiness.Score")
    })


    output$variable_2 <- renderUI({
        selectInput("variable_2", "X-variable:", 
                    choices = c("Happiness.Rank", "Happiness.Score", "Economy", 
                                "Family", "Health", "Freedom", "Government.Corruption", 
                                "Generosity", "Dystopia.Residual"), selected = "Economy")
    })


    data_year <- reactiveValues(data = happiness2015, year = "2015")


    observeEvent(input$button2015, {
        data_year$data <- happiness2015
        year <- "2015"
    })


    observeEvent(input$button2016, {
        data_year$data <- happiness2016
        data_year$year <- "2016"
    })

    observeEvent(input$button2017, {
        data_year$data <- happiness2017
        data_year$year <- "2017"
    })

    observeEvent(input$button2018, {
        data_year$data <- happiness2018
        data_year$year <- "2018"
    })

    observeEvent(input$button2019, {
        data_year$data <- happiness2019
        data_year$year <-  "2019"
    })


    filtered_data <- reactive({
        data_year$data %>% 
            filter(Country %in% c(input$country)) %>% 
            arrange(Country)
    })


    output$year_name_plot <- renderText({ 
        paste("Data for ", data_year$year) 
    })


    countries <- reactive({ 
        df_small <- 
            countries_all %>% 
            select(Country) %>% 
            droplevels()

        c("Select All", levels(df_small$Country))

    })


    output$country <- renderUI ({

        selectInput("country", "Countries:", 
                    multiple = TRUE,
                    choices = countries(), 
                    selected = "Select All",
                    selectize = FALSE,
                    size = 10)
    })


    observe({
        if ("Select All" %in% input$country) {
            # choose all the choices _except_ "Select All"
            selected_choices <- setdiff(countries(), "Select All")
            updateSelectInput(session, "country", selected = selected_choices)
        }
    })


    output$scatterplot <- renderPlotly({
        if (is.null(data_year$data)) return()

        p <- ggplot(filtered_data()) +
            geom_point(aes_string(x = input$variable_2, y = input$variable_1, 
                                  colour = "Region", label = "Country"), size = 3) +
            ggtitle(paste0(input$variable_1, " vs. ", input$variable_2)) +
            theme_bw() +
            theme(legend.position = "bottom")

        ggplotly(p, tooltip = c("label", "x", "y"), height = 500) 
    })


    output$results_table <- DT::renderDataTable({
        if (is.null(data_year$data)) {
            return()
        } else {
            filtered_data()
        }
    },
    options = list(lengthChange = FALSE, 
                   scrollCollapse = TRUE,
                   scrollX = "100%"),
    selection = "single"
    )


    output$tab_name_rankings <- renderText({ 
        paste("Happiness Ranking: ", data_year$year) 
    })


    output$year_name <- renderText({ 
        paste("Happiness Ranking in ", data_year$year) 
    })


    output$rank_table_top <- DT::renderDataTable({
        if (is.null(data_year$data)) {
            return()
        } else {
            data_year$data %>% 
                mutate(Rank = Happiness.Rank) %>% 
                arrange(Rank) %>% 
                top_n(10, desc(Rank))
        }
    },
    options = list(lengthChange = FALSE,
                   scrollX = "100%")
    )


    output$rank_table_bottom <- DT::renderDataTable({
        if (is.null(data_year$data)) {
            return()
        } else {
            data_year$data %>% 
                mutate(Rank = Happiness.Rank) %>% 
                arrange(Rank) %>% 
                top_n(10, Rank)
        }
    },

    options = list(lengthChange = FALSE, 
                   scrollX = "100%")
    )

}

# Run the application 
shinyApp(ui = ui, server = server)

I am trying to add the following plotly plots to the page:

enter image description here enter image description here This is the code for the 2 graphs:

#read files
worklife<-read.csv('satisfaction-with-job-and-work-life-balance-(%)-by-usual-hours-worked,-2018.csv')
wellbeingmeasure<-read.csv('-average-rating-of-selected-wellbeing-measures-for-new-zealanders,-2018_19.csv')

colnames(worklife)
colnames(wellbeingmeasure)

ggplot(worklife, aes(x = Work.life.balance, y = Job.satisfaction)) +
  geom_point(aes(color = factor(Usual.hours.worked.in.main.job)))

ggplot(wellbeingmeasure, aes(x = Average.Rating, y = Selected.wellbeing.measures)) + geom_point()

library(plotly)

p1 <- plot_ly(data = worklife, x = ~Work.life.balance, y = ~Job.satisfaction, color = ~Usual.hours.worked.in.main.job)
p1

p2 <- plot_ly(data = wellbeingmeasure, x = ~Average.Rating, y = ~Selected.wellbeing.measures)
p2

Any help on this is appreciated. How do I add the above code into my shiny app?

Raisham
  • 47
  • 6
  • 1
    can you provide a reproducible example... it is very difficult without seeing data.. you can add another plotlyoutput() in your ui code and render it in server code. – Subhasish1315 Dec 13 '19 at 08:31
  • i added a screenshot of what my app looks like and when you click on the year and the x and y variables, i produces a plot similar to the one above – Raisham Dec 13 '19 at 08:44
  • Can you add more information what you want exactly? What do you want different from, for example, these answers: https://stackoverflow.com/questions/34384907/how-can-put-multiple-plots-side-by-side-in-shiny-r – Annet Dec 13 '19 at 08:48
  • I have edited the question and what exaclty it is that I want to add to my shiny app. – Raisham Dec 13 '19 at 08:59
  • Did you check this https://stackoverflow.com/questions/33941232/integrate-plotly-with-shinydashboard ? Here they also add multiple plotly to the shiny app – Annet Dec 13 '19 at 09:07
  • Yes I did, but it doesn't really make sense to me – Raisham Dec 13 '19 at 09:22

0 Answers0