gpt4 book ai didi

r - 使用 rCharts 在 r 和shiny中创建传单热图

转载 作者:行者123 更新时间:2023-12-01 16:14:57 26 4
gpt4 key购买 nike

我正在使用 Ramnath Vaidyanathan 的精彩演示,网址为 http://rmaps.github.io/blog/posts/leaflet-heat-maps/index.html我想为我 Shiny 的应用程序重现他的热图。

当我尝试在 Shiny 中使用 Ramnath 的代码时,尽管我只能获取 map ,但不能获取热图。我的问题的部分原因可能是Ramnath的原始代码使用rMaps,而我使用rCharts(也是由Ramnath开发的),因为它更发达/与shiny集成得更好,当然还包括Leaflet。我尝试将 rMap 与 Shiny 的 HTML 通用命令 renderUIhtmlOutput 一起使用,但没有成功。

这是不起作用的 Shiny 代码(它只是显示 map ,忽略热点库):

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
})
}
))

最佳答案

将我的评论变成答案 ( 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

关于r - 使用 rCharts 在 r 和shiny中创建传单热图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24273444/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com