2014-06-17 50 views
5

我正在使用Ramnath Vaidyanathan在http://rmaps.github.io/blog/posts/leaflet-heat-maps/index.html的精彩演示,我想重現他的熱圖以適合我的閃亮應用。使用rCharts在r和shiny中創建Leaflet熱圖

當我嘗試使用Ramnath的代碼時,雖然我只設法獲取地圖,但不是熱圖。 可能是我的問題的部分原因是Ramnath的原始代碼在使用rCharts(同時由Ramnath開發)時使用了rMaps,因爲它更發達/更好地與閃亮整合,當然還包括Leaflet。我試圖用閃亮的HTML通用命令renderUIhtmlOutput來使用rMaps,但沒有成功。

這是閃亮的代碼不起作用(它只是顯示在地圖無視熱點庫):

library(rCharts) 
library(shiny) 

runApp(
list(ui = (pageWithSidebar(
headerPanel("Heatmap"), 
sidebarPanel(width=2), 
mainPanel(
mapOutput("leafmap") 
) 
)), 
server = function(input, output) { 
output$leafmap <- renderMap({ 
L2 <- Leaflet$new() 
L2$setView(c(29.7632836, -95.3632715), 10) 
L2$tileLayer(provider = "MapQuestOpen.OSM") 
data(crime, package = 'ggmap') 
library(plyr) 
crime_dat = ddply(crime, .(lat, lon), summarise, count = length(address)) 
crime_dat = toJSONArray2(na.omit(crime_dat), json = F, names = F) 
L2$addAssets(jshead = c(
"http://leaflet.github.io/Leaflet.heat/dist/leaflet-heat.js" 
)) 
L2$setTemplate(afterScript = sprintf(" 
           <script> 
           var addressPoints = %s 
           var heat = L.heatLayer(addressPoints).addTo(map)   
           </script> 
           ", rjson::toJSON(crime_dat) 
)) 

L2 
}) 
} 
)) 
+0

[熱圖中有光澤的r圖表](http://stackoverflow.com/q/33193546/4002530)有一個解決方案 – tospig

回答

4

談到我的意見爲答案(making use of this question/answer

library(rCharts) 
library(shiny) 
library(data.table) 

runApp(
    list(ui = (pageWithSidebar(
    headerPanel("Heatmap"), 
    sidebarPanel(width=2), 
    mainPanel(
     chartOutput("baseMap", "leaflet"), 
     tags$style('.leaflet {height: 500px;}'), 
    tags$head(tags$script(src="http://leaflet.github.io/Leaflet.heat/dist/leaflet-heat.js")), 
     uiOutput('heatMap') 
    ) 
)), 
    server = function(input, output) { 

    data(crime, package="ggmap") 
    crime <- as.data.table(crime) 

    output$baseMap <- renderMap({ 
     baseMap <- Leaflet$new() 
     baseMap$setView(c(29.7632836, -95.3632715), 10) 
     baseMap$tileLayer(provider = "MapQuestOpen.OSM") 
     baseMap 
    }) 

    output$heatMap <- renderUI({ 

     ## changed to use data.table for speed 
     crime_dat <- crime[(lat != ""), .(count = .N), by=.(lat, lon)] 
      ## there's a blank in there somewhere 

     ## I was having issues with toJSON, so I'm creating my own JSON 
     j <- paste0("[",crime_dat[,lat], ",", crime_dat[,lon], ",", crime_dat[,count], "]", collapse=",") 
     j <- paste0("[",j,"]") 

     tags$body(tags$script(HTML(sprintf(" 
         var addressPoints = %s 
         var heat = L.heatLayer(addressPoints).addTo(map)" 
             , j 
    )))) 

    }) 
    } 
)) 

而且來展示它的工作原理

enter image description here

+0

我可以把什麼地方的規模時,是藍色,橙色或紅色? –