【发布时间】:2017-05-30 02:31:47
【问题描述】:
我正在使用this post 中概述的方法在与一维 x 和 y 密度图配对的地图上创建密度热图。我能够生成以下图像:Density Heatmap
但是,我很难将顶部密度图中的阴影区域与地图上的热图对齐。我发现这与我在代码中应用墨卡托投影来生成热图有关,而顶部和右侧的密度图只是使用数据中的坐标。
有没有办法可以将热图中的投影坐标与一维密度图中的非投影坐标对齐?
下面是我的代码的相关部分(我使用了 grid/gtable 包来组合不同的图表)。
编辑:数据由三列组成:UniqueID、Lon 和 Lat。在这种情况下,所有 Lon/Lat 对都在纽约市内/附近,但出于故障排除目的,只要可以预测准确的对并不重要。
library(gtable)
library(ggplot2)
library(ggmap)
ny <- get_map(location = "Washington Heights, New York City", zoom = 12, color = "bw")
ggm <- ggmap(ny, extent = "normal", maprange = F) %+% data +
aes(x = Lon, y = Lat) +
stat_density2d(aes(fill = ..level..,
alpha = ..level..), color = "darkgreen",
geom = "polygon", show.legend = TRUE) +
geom_polygon(aes(x, y),
data.frame(x = c(Inf, Inf, -73.90, -73.90), y = c(Inf, 40.84, 40.84, Inf)),
alpha = 0.5, colour = NA, fill = "red") +
coord_map(projection = "mercator",
xlim = c(attr(ny, "bb")$ll.lon, attr(ny, "bb")$ur.lon),
ylim = c(attr(ny, "bb")$ll.lat, attr(ny, "bb")$ur.lat))
xd <- data.frame(density(data$Lon)[c("x", "y")])
gg1 <- ggplot(xd, aes(x, y)) +
theme(panel.grid.minor = element_line(colour = NA),
panel.background = element_rect(fill = NA, colour = NA)) +
labs(y = "Density") +
geom_area(data = subset(xd, x > -73.90), fill = "red") +
geom_line() +
coord_cartesian(c(attr(ny, "bb")$ll.lon, attr(ny, "bb")$ur.lon))
image <- gtable_filter(ggplotGrob(ggm), pattern = "panel", trim = TRUE, fixed=TRUE)
image <- gtable_add_cols(image, unit(0.2, "null"), 1)
image <- gtable_add_grob(image, gtable_filter(ggplotGrob(gg1), pattern = "panel", trim = TRUE, fixed=TRUE), 1, 1)
【问题讨论】:
-
没有
data,很难提供帮助。 -
感谢您的评论,我在我的问题中添加了对数据框的描述,希望能够清除它。
标签: r ggplot2 gis ggmap density-plot