R Shiny, Part 2

In the last blog post, I went over how you can use R’s Shiny package to create interactive plots like this one. Before you continue with this post, I recommend you to go back and take a look at that. More information about R Shiny can be found in many of the online instructions, such as here and here. In this post, I show you how to create interactive maps using the Shiny library.

First, let’s load the Shiny library.

library(shiny)

You can set your working directory here. Keep in mind that if you’re developing an online app, you can’t set a working directory. A

The following procedure loads the “openxlsx” library and reads our input file.

library(openxlsx)

You can read your input excel file using the following command and the input file can be downloaded from here.

crop_data<-read.xlsx("YOUR-ADDRESS/Input to Shiny-2.xlsx", "Final")

User Interface

Now we can define the user interface of our interactive plot (or online app). In this example, the UI part of the app is very simple, but you can make your own a lot prettier and more elegant.

ui <- fluidPage( 
  
# Here we define the title of our interactive plot:
  titlePanel("Acreage of Important Crops in California"),

# We use the fluid row command to have a better handle on 
# the way we define the positions of different elements. 
# But as I mentioned, I’ll keep the UI very simple in this example.

  fluidRow(

# First, let's design our selection panel.

                  column(10, offset = 4,
# In this example, we use a drop-down menu. 
# Users can choose between different crop types. 
# We use the "selectInput" command to do this.

                         selectInput("Crops", label = "Crops", choices = c("Almond", "Grape" , "Hay"))
                ),
                
# Here we define our main panel, which displays our map.
                column(10, offset = 1,
                       mainPanel(

# This command indicates that we are creating a map and defines the size of it.           
                  leafletOutput("mymap", width = "900", height = "800")
                )
                )

  ) #fluidRow
) # fluid page

Server

Remember that the server part of the code basically takes care of calculations and generates graphs, table, maps, and so forth.

server<-function(input, output){
  
# First, you need to make sure that the maps package is 
# installed on your machine .Then you need to load it. 
# The following procedure does that for you.

#install.packages("maps")
#library(maps)

# The “map” command in the maps library allows you to generate 
# different types of maps.
# We use the following command to generate a map of the State 
# of California that includes its counties.

    mapStates = map('county', 'california', , fill = TRUE, col = palette())

# Here we create the output map that we will send back to the user interface.
    output$mymap<- renderLeaflet({
  
# Here we read the column corresponding to the 
# crop that the user has selected.
# Note that there are two input arguments when we define our server function, 
# "input" and "output." These are used to transfer information between the server and UI components.

# The "input$Crops" part of the code basically takes the choice the 
# user made in UI part of the model and makes it available to the server part.
      
    values<-as.numeric(unlist(crop_data[paste(input$Crops, "_Acres", sep ="" )]))
    
# This part of the code defines the bins and a sequence of colors. Then we assign colors to bins.
  bins <- c(0, 1000, 5000, 10000, 20000, 50000, 100000, 150000, 200000, 250000, Inf)
  palette_crop <- colorBin("BrBG", domain = values, bins = bins)


# This part of the program defines the labels that will be 
# displayed when the user hovers the pointer over different parts of the map.
# We use the "sprintf" command to convert plain text combinations 
# (such as the ones we make with the paste command) into visually attractive and meaningful objects on the map.
  
  labels <- sprintf(
    "<strong>%s</strong><br/>%g Acres </sup>",
    crop_data$NAME, values # crop_data$Hay_Acres
  ) %>% lapply(htmltools::HTML)
  
# We use the "leaflet" command from the leaflet package to generate a background map, 
# and then we put our California map on top of it. 
# The following commands can be used to install and load the leaflet library.

#install.packages("leaflet")
#library(leaflet)
  
    leaflet(data = mapStates) %>% addTiles( ) %>%
# We use the “add polygon” command from leaflet package to add more 
# information to the map. In this case, we add our color-coded pallet to the plot. 

      addPolygons(
        fillColor = ~palette_crop(as.numeric(unlist(crop_data[paste(input$Crops, "_Acres", sep ="" )]))),
        weight = 2,
        opacity = 1,
        color = "white",
        dashArray = "3",
        fillOpacity = 0.7,
# Here we define how the polygons should be highlighted.
        highlight = highlightOptions(
          weight = 5,
          color = "#666",
          dashArray = "",
          fillOpacity = 0.7,
          bringToFront = TRUE),
        label = labels,
        labelOptions = labelOptions(
          style = list("font-weight" = "normal", padding = "3px 8px"),
          textsize = "15px",
          direction = "auto"))%>%
# Now we can add legends to the map.
    addLegend(pal = palette_crop, values = ~density, opacity = 0.7, title = NULL,
              position = "bottomleft")
  })
  
}

Finally, the following command ties together the UI and server functions and creates a Shiny app.

shinyApp(ui, server)

You can find the code and the online app produced in this example here.

Leave a comment