rshinyrchartschoroplethrmaps

rMaps in Shiny: Legend and labels are not getting displayed in US choropleth in shiny app


Legend and Labels (state abbreviations) are not getting displayed in US choropleth in shiny app. However, when I run the code in global.R functions in RStudio console, both labels and legend are displayed fine. Please help!

Here is the code:

global.R

#install.packages("Quandl")
library(Quandl)
library(lubridate)
library(rMaps)
library(plyr)
library(shiny)
library(reshape2)
library(rCharts)

getData <- function()
{
  birth.rate <- Quandl("CDC/42512_40827_00")
  birth.rate
}

transformData <- function()
{
  birth.rate <- Quandl("CDC/42512_40827_00")
  birth.rate <- melt(birth.rate, variable.name = 'State', value.name = 'Birth.Rate', id = 'Year')
  b <- transform(birth.rate, State = state.abb[match(State, state.name)], 
                 Year = year(birth.rate$Year),
                 fillKey = cut(Birth.Rate, quantile(Birth.Rate, seq(0, 1, 1/4)), 
                               include.lowest=TRUE, labels = LETTERS[1:4]))
  b[is.na(b)] <- "DC"
  b
}

createMap <- function(data)
{
  fillColors <- setNames(
    RColorBrewer::brewer.pal(4, 'Greens'),
    c(LETTERS[1:4])
  )

  d <- Datamaps$new()
  fml = lattice::latticeParseFormula(Birth.Rate~State, data = data)

  d$set(
    scope = 'usa', 
    data = dlply(data, fml$right.name),
    fills = as.list(fillColors),
    legend = TRUE,
    labels = TRUE)

  d
}

Server:

source('global.R')
b <- transformData()
shinyServer(function(input, output) {

  output$animatedChart = renderChart({
    animatedChart=createMap(b[b$Year==input$Year,]
    )
    animatedChart$addParams(dom = 'animatedChart') 
    return(animatedChart)
  })
})

UI:

library(shiny)
shinyUI(bootstrapPage(
  div(class="row",
      div(class="span4",
          sliderInput("Year","", min=1990, max=2009, value=1990,step=1))),

  mainPanel(
    showOutput("animatedChart","datamaps")  )
))

Solution

  • It turns out the version of 'DataMaps' library in rCharts does not display the legend and labels but the one is rMaps does. When both the packages are loaded in Shiny, it uses the rCharts version of 'DataMaps' by default. I had to change the code in ui.R to use 'rMaps' package instead.

    Corrected UI:

    library(shiny)
    shinyUI(bootstrapPage(
      div(class="row",
          div(class="span4",
              sliderInput("Year","", min=1990, max=2009, value=1990,step=1))),
    
      mainPanel(
        showOutput("animatedChart","datamaps", package="rMaps")  )
    ))