从rastermap包到ggplot2
我的问题:我想用从rastermap包到ggplot2,r,ggplot2,maps,ggmap,R,Ggplot2,Maps,Ggmap,我的问题:我想用ggplot2绘制通过rastermap包获得的地图 在搜索ggmap包的替代方案时,我找到了rastermap包,它提供了一种从外部来源获取地图的简便方法。提供了一个非常简单的示例: # install.packages("devtools") devtools::install_github("hadley/rastermap") houston <- fetch_region(c(-95.80204, -94.92313), c(29.38048, 30.14344
ggplot2
绘制通过rastermap
包获得的地图
在搜索ggmap
包的替代方案时,我找到了rastermap
包,它提供了一种从外部来源获取地图的简便方法。提供了一个非常简单的示例:
# install.packages("devtools")
devtools::install_github("hadley/rastermap")
houston <- fetch_region(c(-95.80204, -94.92313), c(29.38048, 30.14344),
stamen("terrain"))
houston
plot(houston)
#安装程序包(“devtools”)
devtools::安装github(“hadley/rastermap”)
休斯顿
你为什么想要一个替代品?您可以从以下网站获得雄蕊图:
rastermap
生成十六进制字符串的颜色矩阵(#RRGGBB
格式)。将其转换为更常见的空间数据形式可能是最简单的,即多波段光栅砖,其中红色、绿色和蓝色为单独的图层
我们可以编写一个简短的帮助函数,将十六进制字符串转换为单独的整数值(即,这与rgb()
函数相反):
使用此函数,我们将rastermap矩阵转换为三波段光栅砖:
library(raster)
m = as.matrix(houston)
l=lapply(m[], un_rgb)
r=g=b=matrix(, dim(m)[1], dim(m)[2])
r[] = sapply(l, function(i) i[1])
g[] = sapply(l, function(i) i[2])
b[] = sapply(l, function(i) i[3])
rgb.brick = brick(raster(r), raster(g), raster(b))
并将新光栅的范围设置为原始光栅地图的范围
extent(rgb.brick) = extent(matrix(unlist(attributes(houston)$bb), nrow=2))
现在我们有了更常见的光栅对象形式,我们可以用它做各种事情。例如,我们可以使用库(RStoolbox)
在ggplot中绘制它:
或者我们可以将其另存为图像,用作ggplot中的注释背景:
png('test.png', dim(rgb.brick)[2], dim(rgb.brick)[1])
plotRGB(rgb.brick, 1, 2, 3)
dev.off()
img <- png::readPNG("test.png")
gr <- grid::rasterGrob(img, interpolate=TRUE)
ggplot() + annotation_custom(gr, -Inf, Inf, -Inf, Inf)
png('test.png',dim(rgb.brick)[2],dim(rgb.brick)[1])
绘图rgb(rgb.brick,1,2,3)
发展主任()
img是否愿意分享您为尝试使用ggplot2而编写的代码?了解您尝试执行的操作的上下文会很有帮助。到目前为止,我已尝试使用ggplot2
软件包中的map\u data()
函数,也尝试了graster
软件包。所有错误都与对象的类别有关…服务期限。。。和谷歌地图API的上限^^^^请再次检查。上述方法不使用谷歌地图API。只是为了学习使用rastermap
软件包。您的解决方案将抛出以下错误:Map from URL:http://tile.stamen.com/terrain/10/239/422.jpg readJPEG(tmp)中出错:JPEG解压缩错误:不是JPEG文件:以0x89 0x50开头
extent(rgb.brick) = extent(matrix(unlist(attributes(houston)$bb), nrow=2))
ggRGB(rgb.brick, r=1, g=2, b=3)
png('test.png', dim(rgb.brick)[2], dim(rgb.brick)[1])
plotRGB(rgb.brick, 1, 2, 3)
dev.off()
img <- png::readPNG("test.png")
gr <- grid::rasterGrob(img, interpolate=TRUE)
ggplot() + annotation_custom(gr, -Inf, Inf, -Inf, Inf)