5 minute readRshiny: it’s here, now it’s your turn to play with coffee

Rshiny is R without the difficult language

After making the previous worldmap here and playing with ggplot2 here, it’s time for the third and last coffee post: using Rshiny.

Here is what we are going to make:


Below you can play with the app, and here is the app link:
https://timonweitkamp.shinyapps.io/Where-is-the-coffee/

What is Rshiny?

To cite from R :

“Easy web applications in R: Shiny is an open source R package that provides an elegant and powerful web framework for building web applications using R”

R

What does this mean? It means that I can put an “app” online which others can use, without needing R and related stuff on their own laptop. Once the “app” is published, anyone can access it (you can also add accounts if you want :D).

So in the continuation spirit of coffee I’ve made an app that makes it possible for you to view the data and to make similar graphs.

Setup

You will need the shiny, shinythemes and shinywidgets packages installed on your laptop. After that you can copy the code and the app will run itself after pressing the run button.

As you can see in the screenshot above, there are three main tabs: Interactive map, Data explorer (Data) and Data explorer (Graph). Each tab will have its own way of showing data, but I’ll get into that in a bit. First, the code.

The shiny code

This is probably not the most elegant way of making the app, but if it works…. it works.

library(shiny)
library(shinyWidgets)
library(ggplot2)  # data visualization
library(dplyr)    # data wrangling
library(tidyr)    # reshaping data
library(rworldmap)# get worldmap background
library(shinythemes) # theme

choices <- unique(All_data$Country)
choicesYear <- unique(All_data$Year)

ui <- navbarPage("How much coffee?",id="nav", theme = shinytheme("flatly"), #ui = user interface
  
  # First tab ----
  tabPanel("Interactive map",
  
  # Sidebar layout with input and output definitions ----
  sidebarLayout(
    
    # Sidebar panel for inputs ----
    sidebarPanel(
      
      # Input: select country or countries of interest (all is possible)
      pickerInput("country", "Select your country:", choices, options = list(`actions-box` = TRUE),multiple = T, selected = "Zambia"),
      # pickerInput("year", "Select your year:", choicesYear, options = list(`actions-box` = TRUE),multiple = T, selected = "1993"),
      selectInput("colour","What do you want to show?", choices=c("Prod_ton","Cons_ton","Exp_ton")),
      sliderInput("time","Which year do you want to see?",min=1990, max=2018, step=1, value=1993, sep="")
      ), #closing sidebarPanel
  
    # Main panel for displaying outputs ----
    mainPanel(
      # Create the map ----
        plotOutput('map'),
        tableOutput('summary')) #closing mainPanel
    ) #closing sidebarLayout
  ), #closing tabPanel
  
  # Second tab ----
  tabPanel("Data explorer (table)",
           
           # Sidebar layout with input and output definitions ----
           sidebarLayout(
             
             # Sidebar panel for inputs ----
             sidebarPanel(
               
               # Input: select country or countries of interest (all is possible)
               pickerInput("country2", "Select your country:", choices, options = list(`actions-box` = TRUE),multiple = T, selected = "Zambia"),
               pickerInput("year2", "Select your year:", choicesYear, options = list(`actions-box` = TRUE),multiple = T, selected = "1993")
             ), #closing sidebarPanel
             
             # Main panel for displaying outputs ----
             mainPanel(
               # Create the map ----
               tableOutput('map2')) #closing mainPanel
             
           ) #closing sidebarLayout
  ),
  
  # third tab
  tabPanel("Data explorer (graph)",
           
           # Sidebar layout with input and output definitions ----
           sidebarLayout(
             
             # Sidebar panel for inputs ----
             sidebarPanel(
               
               # Input: select country or countries of interest (all is possible)
               selectInput("xaxis", "Select your x-axis:", c('None', names(All_data)), selected = "Year"),
               selectInput("yaxis", "Select your y-axis:", c('None', names(All_data)), selected = "Prod_ton"),
               selectInput("x2", "Select your second y-axis:", c(None='.', names(All_data))),
               selectInput("y2", "Select your second y-axis:", c(None='.', names(All_data))),
               selectInput("colGraph","Select your colour variable", c(none ='None', names(All_data)), selected = "Continent"),
               selectInput("type","Select graph type", choices = c("Point","Line")),
               selectInput("legend","Hide legend?",choices=c("Yes","No"))
             ), #closing sidebarPanel
             
             # Main panel for displaying outputs ----
             mainPanel(
               # Create the map ----
               plotOutput('graph')) #closing mainPanel
             
           ) #closing sidebarLayout
  )
  
)

#========================
# server
#========================

# Define server logic required to draw a histogram ----
server <- function(input, output) {
  
  # Selected data ---- reactive lets the data change as you select variables
  selectedData <- reactive({
    map_coffee %>% filter(region %in% input$country & Year %in% input$time)
  })
  
  selectedData2 <- reactive({
    All_data %>% filter(Country %in% input$country2 & Year %in% input$year2)
  })
  
  graphData <- reactive({
    All_data 
  })
  
  # Create the map ----
  output$map <- renderPlot({
   g<-  ggplot()+
      geom_polygon(data=map.world, aes(x = long, y = lat, group = group))  
   
   if(input$colour == "Prod_ton") # if you elected Prod_ton, this graph wil be plotted
    g<-g + geom_polygon(data=selectedData(),aes(fill = Prod_ton,x = long, y = lat, group = group))
   
   if(input$colour == "Cons_ton")
    g<-g + geom_polygon(data=selectedData(),aes(fill = Cons_ton,x = long, y = lat, group = group))
   
   if(input$colour == "Exp_ton")
   g<-g + geom_polygon(data=selectedData(),aes(fill = Exp_ton,x = long, y = lat, group = group))
   
    g + scale_fill_viridis_c()
  })
  
  # Create the table ---- (nothing special happening here, table is just plotted )
  output$map2 <- renderTable({
    selectedData2()
  })
  
  
  # Create the graph
  output$graph <- renderPlot({

       p<- ggplot(data=graphData(), aes_string(x= input$xaxis, y=input$yaxis))
   if(input$type == "Point") #data is shown as point if selected
     p <- p+ geom_point()

   if(input$type == "Line")
     p <- p+geom_line()

   if(input$legend == "Yes")
     p <- p + theme(legend.position="none")
   
   if (input$colour != 'None')
     p <- p + aes_string(color=input$colGraph)
   
   facets <- paste(input$x2, '~', input$y2)
   if (facets != '. ~ .')
     p <- p + facet_grid(facets)
   p# + facet_grid(input$y2, input$x2)
  })
}

#========================
# run
#========================
shinyApp(ui, server) #running the app

So,… what does it say….?

Rshiny splits the app into to things: UI and Server. The UI is where you see the options which you can click. The Server is where the magic and plotting happens. The other stuff I that happens is explained in the code after the # sign. If you want to know more about how to build these apps, there are more than enough sources on internet that can help out. You can start in the rshiny gallery: https://shiny.rstudio.com/gallery/ which provides nice examples and codes for you to copy.

And here is the link 😀

Just click here: https://timonweitkamp.shinyapps.io/Where-is-the-coffee/ to see the app.



Edit: this is the third of three posts. Click here for the first and here for the second post in this coffee exploring theme.

2 Comments

Add a Comment

Your email address will not be published. Required fields are marked *