R-地图缩放功能,使绘图成为圆形而不是正方形
我从一位同事那里继承了一些代码,我正试图“改进” 本质上,它需要一张地图,然后放大一个位置,然后使用gridExtra将地图和缩放的地图绑定在一起 工作正常,功能如下:R-地图缩放功能,使绘图成为圆形而不是正方形,r,R,我从一位同事那里继承了一些代码,我正试图“改进” 本质上,它需要一张地图,然后放大一个位置,然后使用gridExtra将地图和缩放的地图绑定在一起 工作正常,功能如下: map_zoom <- function(map, location="London", layout=rbind(c(1, 1, 1), c(1, 3, 2),
map_zoom <- function(map, location="London", layout=rbind(c(1, 1, 1),
c(1, 3, 2),
c(1, 1, 1))) {
###
#
# Input: a pre-existing map of the UK,
# and details of where to zoom in
#
# Output: the input map, with the zoomed in map inset
#
###
require(grid)
require(gridExtra)
#A data frame of where to zoom for various locations in the UK
locations <- data.frame(rbind(
c("London", 505000, 555000, 155000, 205000),
c("Liverpool & Manchester", 330000, 400000, 370000, 440000),
c("Leeds & Sheffield", 400000, 470000, 370000, 440000),
c("Coventry & Birmingham", 380000, 450000, 250000, 320000),
c("Edinburgh & Glasgow", 230000, 370000, 630000, 700000),
c("Cambridge", 500000, 570000, 220000, 290000),
c("Oxford", 420000, 490000, 170000, 240000),
c("Bristol", 310000, 380000, 140000, 210000)))
xlim <- as.numeric(locations[locations[,1] == location,2:3])
ylim <- as.numeric(locations[locations[,1] == location,4:5])
zoomed_map <- map +
labs(subtitle = location) +
theme(legend.position = "none",
#plot.margin = unit(c(2,-5,2,2), "cm"),
plot.title = element_blank()) +
coord_fixed(1, xlim = xlim, ylim = ylim)
legend <- extract_legend(map)
map <- map + theme(legend.position="none")
map <- grid.arrange(map, zoomed_map, legend,
layout_matrix = layout)
return(map)
}
在map\u zoom
功能中,是否有一种简单的方法可以将正方形变成一个圆,或者我必须找到某个半径内的每一个长/lat才能形成一个圆
多谢各位
编辑:
提取图例功能是:
extract_legend <- function(map) {
###
#
# Input: a ggplot object with a legend
#
# Output: a ggplot object of just the legend
#
###
tmp <- ggplot_gtable(ggplot_build(map))
leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
legend <- tmp$grobs[[leg]]
return(legend)
}
extract_legend对于圆,我们可以通过边界框围绕其质心的半径来缓冲边界框,例如伦敦。然后可以使用该缓冲区与初始地图数据相交
我不确定如何在圆和地图之间添加“缩放线”,因为它们是两个独立的图
我使用了sf
来读取数据,并使用rmapshaper
来简化图形以更快地绘制。您链接的文件的详细程度可能不是英国概览所必需的
为测试创建地图数据
库(sf)
图书馆(tidyverse)
图书馆(rmapshaper)
我试图重现的nuts1:您的map
变量是什么样子的?我可以使用一些默认的或包特定的教程值吗?嘿,这是一个几何多边形对象,使用的是来自ONS的shapefile。够了吗?我可以把所有的代码都放在这个问题上,但它相当长。谢谢BTW因为一些值是硬编码的(英国城市坐标和位置),所以可以复制。您是从一个没有相同形状文件就很难复制的多边形文件中获取多边形文件的吗。你从哪里得到这个文件的?此外,还会调用函数extract\u legend
。你创建了这个函数还是它是一个包的一部分?嘿,在这里找到了shapefile:我还在我的问题中添加了Extract_legend函数。谢谢你,很抱歉反应太慢!这张地图只是一张cholopeth地图,为英国的坚果1区域分配数字。嘿,克里斯,这太完美了。非常感谢。我也很欣赏用代码回复的冗长信息。我可以搞乱缩放线的事情,这是次要的得到一个圆圈缩放地图。再次感谢大家!!!没问题!我现在意识到我忽略了一件事,那就是我认为它需要你的输入地图有一个geom\u sf
层,这样地图数据就可以用ggplot\u build
来提取。希望这不会成为问题。嘿,克里斯,那很好,根本不是问题:)
extract_legend <- function(map) {
###
#
# Input: a ggplot object with a legend
#
# Output: a ggplot object of just the legend
#
###
tmp <- ggplot_gtable(ggplot_build(map))
leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
legend <- tmp$grobs[[leg]]
return(legend)
}