首页 > 解决方案 > R中的ggmap在世界地图中不需要的平行线

问题描述

我正在使用 ggmap 绘制世界地图。我的代码如下:

library(maps)
library(ggmap)
library(repr)
library(ggthemes)
library(ggplot2)
options(repr.plot.width=16, repr.plot.height=8)



world_map<-map_data("world")

world_map<-world_map[order(world_map$order),]
ggplot(world_map,aes(x=long,y=lat))+
     geom_polygon(aes(group = group, fill = "red"),color='white')+
       coord_map("mercator")+
            theme_map()

我收到不需要的线路(穿越俄罗斯)。

在此处输入图像描述

@mrhellmann 谢谢;它解决了这个问题;(由于某种原因无法回复)

标签: rggmap

解决方案


您可以使用该sf包来转换您从 ggplot2 获得的数据。

将数据框转换为sf对象,然后使用geom_sf.

library(dplyr)

library(ggplot2)
library(sf)

world_map <- map_data('world')

world_sf <- world_map %>% 
  st_as_sf(coords = c('long', 'lat'), crs = 4326) %>% 
  group_by(group) %>% 
  summarise(geometry = st_combine(geometry)) %>% 
  st_cast('POLYGON')

ggplot(world_sf) +
  geom_sf(fill = 'red')

或者,使用rnaturalearth包来获得一个干净的sf对象来使用:

library(rnaturalearth)

ne_world <- ne_countries(returnclass = 'sf')

ggplot(ne_world) +
  geom_sf(fill = 'red') +
  theme_void()

在此处输入图像描述 reprex 包(v0.3.0)于 2020 年 12 月 29 日创建


推荐阅读