图例和标签(州缩写)不会在闪亮应用程序的美国choropleth中显示。但是,当我在global中运行代码时。R函数在RStudio控制台中,标签和图例都显示得很好。请帮忙!
这是代码:
全局.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
}
服务器:
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") )
))
事实证明,rCharts中的"DataMaps"库版本没有显示图例和标签,但rMaps版本显示了图例和标签。当这两个包都在Shiny中加载时,默认情况下它使用rCharts版本的"DataMaps"。我不得不更改ui中的代码。R使用"rMaps"包。
已更正的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") )
))