世界地图与ggmap [英] World map with ggmap

查看:866
本文介绍了世界地图与ggmap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ggmap,并希望有一张以澳大利亚为中心的世界地图,我可以轻松地绘制地理编码点。与其他一些映射包相比,ggmap似乎更容易使用。然而,当我通过一个使用下面的代码错误的地图。

  gc<  -  geocode('australia')
中心< - as.numeric(gc)
> map< - get_map(location = center,source =google,maptype =terrain,zoom = 0)
错误:zoom必须是介于1和21之间的整数



从get_map help:
zoom:map zoom,一个从 0(整个世界)到21 (建筑物),默认值10(城市)。openstreetmaps限制缩放18,并且雄蕊地图上的限制取决于maptype。'auto'自动确定边界框规格的缩放比例,缺省值为10中心/缩放规格。



将缩放比例更改为1不会导致get_map错误,但可以绘制该贴图

  map<  -  get_map(location = center,source =google,maptype =terrain,zoom = 1)
ggmap(map)

警告信息:
1:在min(x)中:没有非缺少参数为min;返回Inf
2:在max(x)中:没有非缺少参数为max;返回-Inf
3:在min(x)中:没有非缺少参数min;返回Inf
4:在max(x)中:没有非缺失参数为max;返回-Inf

看起来经度没有被拉过。
最后缩放为2它确实有效,但没有通过整个世界的地图



所以,我的问题是如何使用get_map获得世界地图?



会话信息:


sessionInfo()
R版本2.15.0(2012-03-30)
平台:i386-pc-mingw32 / i386(32位)



  locale:
[1] LC_COLLATE = English_United Kingdom.1252
[2] LC_CTYPE = English_United Kingdom.1252
[3] LC_MONETARY = English_United Kingdom.1252
[4] LC_NUMERIC = C
[5] LC_TIME = English_United Kingdom.1252

附加基本套餐:
[1] stats graphics grDevices utils数据集方法base

其他附加软件包:
[1] mapproj_1.1-8.3 maps_2.2-6 rgdal_0.7-12 sp_0.9-99
[5] ggmap_2.1 ggplot2_0.9.1

通过命名空间加载(并未附加):
[1] colorspace_1.1-1 dichr omat_1.2-4 digest_0.5.2 grid_2.15.0
[5] labels_0.1 lattice_0.20-6 MASS_7.3-17 memoise_0.1
[9] munsell_0.3 plyr_1.7.1 png_0.1 -4 proto_0.3-9.2
[13] RColorBrewer_1.0-5 reshape2_1.2.1 RgoogleMaps_1.2.0 rjson_0.2.8
[17] scales_0.2.1 stringr_0.6 tools_2.15.0
编辑:更新到ggplot2 v 0.9.3 : / p>

我尝试了类似的方法,但收效甚微。但是,有很多方法可以从 map 包中居中映射世界:请参阅这里中的阴阳经络在绘图 - 世界地图,以及 here 。使用后者的代码,这里是一个将世界地图放在经度160上的例子,绘制了CRAN镜像位置(使用ggmap包中的 geocode()函数获得的坐标)使用ggplot2绘制的世界地图,以及新西兰的颜色(使用 geom_polygon )。将地图定位在经度160上,可以将地图左侧的所有非洲地图以及地图右侧的格陵兰岛大部分地图保留。

  library(maps)
library(plyr)
library(ggplot2)
library(sp)
library(ggmap)

#绘制CRAN镜像
镜像= getCRANmirrors(全部= FALSE,local.only = FALSE)

镜像$ Place = paste(镜像$ City,,,镜像$ Country,sep =)#耐心等待
tmp = geocode(Mirrors $ Place)
Mirrors = cbind(Mirrors,tmp)

########### ################################################## ######################################
#最近的世界地图(和镜像坐标)经度160
###代码克劳迪娅恩格尔2012年3月19日,www.stanford.edu/~cengel/blog

###接收者####
中心< - 160#正值仅

#移位坐标到中性CRAN镜像
镜像$ long.recenter< - ifelse(镜像$ lon< center - 180,镜像$ lon + 360 ,镜子$ lon)

#移动坐标到recenter worldmap
worldmap< - map_data(world)
worldmap $ long.recenter< - ifelse(worldmap $ long <中心 - 180,世界地图$ long + 360,worldmap $ long)

###重新组合分割线和多边形的功能
#使用长且唯一的组变量获取数据帧,列,返回df并添加了一个名为group.regroup的列
RegroupElements< - function(df,longcol,idcol){
g< - rep(1,length(df [,longcol]))
if diff(范围(df [,longcol]))> 300){#检查组内的经度是否相差超过300度,即如果元素被分割
d <-df [,longcol]>>平均值(范围(df [,longcol]))#我们使用均值来帮助我们分离极端值
g [!d]< - 1#某些留在原地的标记(我们在这里作弊,因为我们没有考虑凹多边形)
g [d] < - 2#移动的部分
}
g < - 粘贴(df [,idcol],g,sep =。)#附加到id为数据集创建唯一的组变量
df $ group.regroup< -g
df
}

## #函数关闭重新组合的多边形
#获取数据帧,检查第一个和最后一个经度值是否相同,如果不是,则首先插入最后一个并重新分配顺序变量
ClosePolygons< - function(df,longcol,如果(df [1,longcol]!= df [nrow(df),longcol]){
tmp< - df [1,]
df< - rbind (df,tmp)
}
o < - c(1:nrow(df))#rassign命令变量
df [,ordercol] < - o
df
}

#now regroup
worldmap.rg< - ddply(worldmap,。(group),RegroupElements,lon g.recenter,group)

#关闭多边形
worldmap.cp< - ddply(worldmap.rg,。(group.regroup),ClosePolygons,long.recenter ,order)#使用新的分组var
################################### ##########################################

#使用worldmap.cp中的数据绘制世界地图
windows(9.2,4)
worldmap = ggplot(aes(x = long.recenter,y = lat),data = worldmap.cp)+
geom_polygon(aes(group = group.regroup),fill =#f9f9f9,color =grey65)+
scale_y_continuous(limits = c(-60,85))+
coord_equal() + theme_bw()+
theme(legend.position =none,
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
)axis.title.x = element_blank(),
axis.title.y = element_blank(),
#axis.text.x = element_blank(),
axis.text.y = element_blank(),
axis.ticks = element_blank(),
panel.border = element_rect(color =black))

#绘制CRA N镜像
worldmap = worldmap + geom_point(data =镜像,aes(long.recenter,lat),
color =red,pch = 19,size = 3,alpha = .4)

#颜色新西兰
#照顾worldmap.cp中的变量名
head(worldmap.cp)
worldmap + geom_polygon(data = subset(worldmap.cp, region ==New Zealand,select = c(long.recenter,lat,group.regroup)),
aes(x = long.recenter,y = lat,group = group.regroup),fill =蓝色)


I am using ggmap and wish to have a map of the world centered on Australia to which I can easily plot geocoded points. ggmap seems to be a lot easier to use compared to some of the other mapping packages. Yet when I bring through a map using the code below it errors.

gc <- geocode('australia')
center <- as.numeric(gc) 
> map <- get_map(location = center, source="google", maptype="terrain", zoom=0)
Error: zoom must be a whole number between 1 and 21

From the get_map help: "zoom: map zoom, an integer from 0 (whole world) to 21 (building), default value 10 (city). openstreetmaps limits a zoom of 18, and the limit on stamen maps depends on the maptype. 'auto' automatically determines the zoom for bounding box specifications, and is defaulted to 10 with center/zoom specifications."

Changing the zoom to one does not error for get_map but does for plotting that map

map <- get_map(location = center, source="google", maptype="terrain", zoom=1)
ggmap(map)

Warning messages:
1: In min(x) : no non-missing arguments to min; returning Inf
2: In max(x) : no non-missing arguments to max; returning -Inf
3: In min(x) : no non-missing arguments to min; returning Inf
4: In max(x) : no non-missing arguments to max; returning -Inf

It looks like the longitude isn't being pulled through. Finally with a zoom of 2 it does work but does not bring through a map of the whole world

So, my question is how can I use get_map to get a world map?

Session info:

sessionInfo() R version 2.15.0 (2012-03-30) Platform: i386-pc-mingw32/i386 (32-bit)

locale:
[1] LC_COLLATE=English_United Kingdom.1252 
[2] LC_CTYPE=English_United Kingdom.1252   
[3] LC_MONETARY=English_United Kingdom.1252
[4] LC_NUMERIC=C                           
[5] LC_TIME=English_United Kingdom.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] mapproj_1.1-8.3 maps_2.2-6      rgdal_0.7-12    sp_0.9-99      
[5] ggmap_2.1       ggplot2_0.9.1  

loaded via a namespace (and not attached):
[1] colorspace_1.1-1   dichromat_1.2-4    digest_0.5.2       grid_2.15.0       
[5] labeling_0.1       lattice_0.20-6     MASS_7.3-17        memoise_0.1       
[9] munsell_0.3        plyr_1.7.1         png_0.1-4          proto_0.3-9.2     
[13] RColorBrewer_1.0-5 reshape2_1.2.1     RgoogleMaps_1.2.0  rjson_0.2.8       
[17] scales_0.2.1       stringr_0.6        tools_2.15.0 

解决方案

EDIT: Updated to ggplot2 v 0.9.3

I tried something similar recenty but with little success. However, there are a number of ways to centre a world map from the map package: see here, here, and here. Using code from the latter, here's an example that centers the world map on longitude 160, plots CRAN mirror locations (coordinates obtained using the geocode() function from the ggmap package) on the world map plotted using ggplot2, and colours New Zealand (using geom_polygon). Centering the map on longitude 160 keep all of Africa on the left of the map, and most of Greenland on the right of the map.

library(maps)
library(plyr)
library(ggplot2)
library(sp)
library(ggmap)

# Get some points to plot - CRAN Mirrors
Mirrors = getCRANmirrors(all = FALSE, local.only = FALSE)

Mirrors$Place = paste(Mirrors$City, ", ", Mirrors$Country, sep = "")    # Be patient
tmp = geocode(Mirrors$Place)
Mirrors = cbind(Mirrors, tmp)

###################################################################################################
# Recentre worldmap (and Mirrors coordinates) on longitude 160
### Code by Claudia Engel  March 19, 2012, www.stanford.edu/~cengel/blog

### Recenter ####
center <- 160 # positive values only

# shift coordinates to recenter CRAN Mirrors
Mirrors$long.recenter <- ifelse(Mirrors$lon < center - 180 , Mirrors$lon + 360, Mirrors$lon)

# shift coordinates to recenter worldmap
worldmap <- map_data ("world")
worldmap$long.recenter <- ifelse(worldmap$long < center - 180 , worldmap$long + 360, worldmap$long)

### Function to regroup split lines and polygons
# Takes dataframe, column with long and unique group variable, returns df with added column named group.regroup
RegroupElements <- function(df, longcol, idcol){
  g <- rep(1, length(df[,longcol]))
  if (diff(range(df[,longcol])) > 300) { # check if longitude within group differs more than 300 deg, ie if element was split
    d <- df[,longcol] > mean(range(df[,longcol])) # we use the mean to help us separate the extreme values
    g[!d] <- 1 # some marker for parts that stay in place (we cheat here a little, as we do not take into account concave polygons)
    g[d] <- 2 # parts that are moved
  }
  g <- paste(df[, idcol], g, sep=".") # attach to id to create unique group variable for the dataset
  df$group.regroup <- g
  df
}

### Function to close regrouped polygons
# Takes dataframe, checks if 1st and last longitude value are the same, if not, inserts first as last and reassigns order variable
ClosePolygons <- function(df, longcol, ordercol){
  if (df[1,longcol] != df[nrow(df),longcol]) {
    tmp <- df[1,]
    df <- rbind(df,tmp)
  }
  o <- c(1: nrow(df)) # rassign the order variable
  df[,ordercol] <- o
  df
}

# now regroup
worldmap.rg <- ddply(worldmap, .(group), RegroupElements, "long.recenter", "group")

# close polys
worldmap.cp <- ddply(worldmap.rg, .(group.regroup), ClosePolygons, "long.recenter", "order") # use the new grouping var
#############################################################################

# Plot worldmap using data from worldmap.cp
windows(9.2, 4)
worldmap = ggplot(aes(x = long.recenter, y = lat), data = worldmap.cp) + 
  geom_polygon(aes(group = group.regroup), fill="#f9f9f9", colour = "grey65") + 
  scale_y_continuous(limits = c(-60, 85)) + 
  coord_equal() +  theme_bw() + 
  theme(legend.position = "none",
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    axis.title.x = element_blank(),
    axis.title.y = element_blank(),
    #axis.text.x = element_blank(),
    axis.text.y = element_blank(),
    axis.ticks = element_blank(), 
    panel.border = element_rect(colour = "black"))

# Plot the CRAN Mirrors
worldmap = worldmap + geom_point(data = Mirrors, aes(long.recenter, lat),
   colour = "red", pch = 19, size = 3, alpha = .4)

# Colour New Zealand
# Take care of variable names in worldmap.cp
head(worldmap.cp)
worldmap + geom_polygon(data = subset(worldmap.cp, region == "New Zealand", select = c(long.recenter, lat, group.regroup)), 
          aes(x = long.recenter, y = lat, group = group.regroup), fill = "blue")

这篇关于世界地图与ggmap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆