arjan-hada
arjan-hada

Reputation: 269

Shiny and ggplot2

I made a ggplot plot using the following R code and it works perfectly fine. Here is a link to the data: https://www.dropbox.com/s/xzauims7rqwurga/who_ghg_complete.csv?dl=0

library(tidyverse)
ghg_complete <- read_csv("who_ghg_complete.csv")
p1 <- ghg_complete %>% 
  filter(`Country Name` == "China") %>% 
  ggplot(aes(x = year, y = ghg_emissions)) +
  geom_point(size = 2, shape = 21) +
  geom_line(group = 1) +
  labs(title = "Total greenhouse gas emissions (kt of CO2 equivalent)",
       x = NULL,
       y = NULL) +
  scale_x_discrete(breaks = seq(1970, 2012, by = 5)) +
  theme_bw() 
print(p1)

enter image description here I tried using similar code for Shiny app and I have two issues. 1) The selected country in selectInput does not show up by default. 2) The x-axis ticks and x-axis tick labels are missing. https://arjan-hada.shinyapps.io/App-1/

Here is the shiny code:

library(shiny)
library(tidyverse)

# Read the dataset
ghg_complete <- read_csv("who_ghg_complete.csv")

shinyUI(fluidPage(
  titlePanel("Greenhouse gas emissions"),
  
  sidebarLayout(
    sidebarPanel(
      selectInput("country",
                  label = "Country:",
                  choices = ghg_complete$`Country Name`,
                  selected = "United States")
    ),
    
    mainPanel(plotOutput("linePlot"))
  )
))

library(shiny)
library(tidyverse)

ghg_complete <- read_csv("who_ghg_complete.csv")


shinyServer(function(input, output) {
  
  ghg_subset <- reactive({
    ghg_complete %>% 
      filter(`Country Name` == input$country)
  })
  
  output$linePlot <- renderPlot({
    p <- ggplot(data = ghg_subset(), aes(x = year, y = ghg_emissions)) +
      geom_point() +
      geom_line(group = 1) +
      labs(title = "Total greenhouse gas emissions (kt of CO2 equivalent)",
           x = NULL,
           y = NULL) +
      scale_x_discrete(breaks = seq(1970, 2012, by = 5)) +
      theme_bw() 
    print(p)
  })
})

Upvotes: 0

Views: 1772

Answers (1)

SBista
SBista

Reputation: 7694

For the first issue "the selected country in selectInput does not show up by default", ghg_complete$Country Name has occurrence of "United States" more than 1 time hence the select input should be as follows:

selectInput("country",
                  label = "Country:",
                  choices = unique(ghg_complete$`Country Name`),
                  selected = "United States")

Here we will only take the unique occurrence of the country names.

The second issue of "The x-axis ticks and x-axis tick labels are missing" can be solved by replacing this scale_x_discrete(breaks = seq(1970, 2012, by = 5))with scale_x_discrete(limits = seq(1970, 2012, by = 5))

Hope it helps!

Upvotes: 2

Related Questions