我正在处理R
中spData
包中的world
和worldbank_df
个数据集,需要对我的数据进行子集,并将结果绘制成图表.我 Select 了"大陆"和"城市流行"列,删除所有NA值,按大陆分组,总结所有大陆的平均城市人口.然而,当我使用geom_sf
调用绘制结果时,我得到了一个错误:
Error in FUN(X[[i]], ...) : object 'mean_urban_pop' not found
我需要在世界 map 中绘制这些数据,但它对我不起作用,因为geom
个坐标没有被转移到我的新数据集中.
How can I get these results graphed?
注:下面投影的坐标系是我必须使用的坐标系.
这是我的代码:
library(tidyverse)
library(sf)
library(spData)
library(ggplot2)
#Load in the data
world <- spData::world
wdb <- spData::worldbank_df
#Combine the data frames
wld_jn <- left_join(world, wdb, by = c('iso_a2', 'name_long' = 'name'))
#Reproject to required coordinate system. Obtained from: https://spatialreference.org/ref/sr-org/6/
wld_jn <- st_transform(wld_jn, '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs')
def_wld_jn <- st_set_crs(wld_jn, '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs')
#Graph mean urban population across continent:
wld_jn %>%
select(continent, urban_pop) %>%
drop_na() %>%
group_by(continent) %>%
summarise_at(vars(urban_pop), list(mean_urban_pop = mean)) %>%
ggplot(.) +
geom_sf(data = wld_jn, aes(fill = mean_urban_pop)) +
scale_fill_gradient2(midpoint = 285)+
guides(fill = guide_colorbar(title = "Population",
title.position = "bottom",
title.theme = element_text(size = 10,
face = "bold",
colour = "gray70",
angle = 0))) +
ggtitle("World Urban Population") +
theme(plot.title = element_text(hjust = 0.5))