【问题标题】:How can I add a base map to data split by a factor level?如何将底图添加到按因子级别拆分的数据?
【发布时间】:2016-12-14 18:25:29
【问题描述】:

我有一张地图

library(maps)       
library(mapdata)    
map('worldHires', c('Ireland', 'UK'), xlim=c(-16,-5.5), ylim=c(51,56))    

而且我有一些跟踪数据,可以根据动物 ID 的身份进行绘制

lat <- c(-11.385668, -11.389855,-12.142785,-11.94954,-11.17716, -10.456175)
lon <- c(53.543667, 53.561507, 52.687934, 52.855068, 52.803291, 52.858737)
ID <- c("A","A","B","B","C","C")
df = data.frame(lat, lon, ID);df

op <- par(mfrow = c(1,3))
sapply(split(df[1:2], df$ID), plot)

我希望能够设置一个函数,以便将原始地图设置为 3 个单独轨道中的每一个的基础层。

【问题讨论】:

    标签: r plot gis spatial


    【解决方案1】:

    您的问题对您最终想要的结果不是很清楚。我发现 ggmap 库对于映射问题非常有用。这是为您的问题提供一些指导的尝试。 geom_path 函数对于连接一系列位置非常有用。在这个例子中,我只连接了 ID==B 的点,根据需要将剩余的 ID 连接起来应该很简单。

    #Sample Data
    lat <- c(-11.385668, -11.389855,-12.142785,-11.94954,-11.17716, -10.456175)
    lon <- c(53.543667, 53.561507, 52.687934, 52.855068, 52.803291, 52.858737)
    ID <- c("A","A","B","B","C","C")
    df = data.frame(lat, lon, ID)
    
    library(ggmap)
    library(RColorBrewer)
    
    #locate the center of the map
    center<-c(mean(range(df$lon)), mean(range(df$lat)))
    #in this case zoom is set by trial and error
    mymap<-qmap(location = center, zoom = 8, maptype= "terrain")
    mymap<-mymap + geom_point(aes(x=lon, y=lat, color=ID), data=df)
    mymap<-mymap + scale_size(range = c(2, 4)) + scale_color_brewer(palette = "Set1")
    mymap<-mymap + geom_path(aes(x=lon, y=lat), data=df) 
    
    mymap<-mymap + facet_wrap(~ID, nrow =2)
    print(mymap)
    

    您可能需要查看这个问题才能让 ggplot2 和 ggmap 正常工作:ggmap Error: GeomRasterAnn was built with an incompatible version of ggproto

    【讨论】:

    • 对不起,我应该更清楚。这个想法是创建一个面板图,每个动物 ID 都有一张地图,而不是全部在一张地图上。我试过了,由于某种原因,它适用于我的完整数据集,但不适用于我提供的样本! mapFunc &lt;- function(data) { map('worldHires', c('Ireland', 'UK'), xlim=c(-16,-5.5), ylim=c(51,56)) points(data$lon,data$lat,pch=16, cex=5, map.axes(cex.axis=0.8),title("Storm Petrels"), xlab="longitude",ylab="latitude") }
    • @Manassa,好的,我在绘图创建中添加了 facet_wrap 函数并将其分离出来。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-01
    相关资源
    最近更新 更多