gpt4 book ai didi

从 ggplot2 map 中删除南极洲

转载 作者:行者123 更新时间:2023-12-04 02:59:48 24 4
gpt4 key购买 nike

我正在尝试重现 this tutorial关于如何绘制类似散点图的 map 。下面是完整的代码和输出:

library(readr)
library(dplyr)
library(DT)

datatable(rladies, rownames = FALSE,
options = list(pageLength = 5))
url_csv <- 'https://raw.githubusercontent.com/d4tagirl/R-Ladies-growth-maps/master/rladies.csv'
rladies <- read_csv(url(url_csv)) %>%
select(-1)

library(ggplot2)
library(maps)
library(ggthemes)

world <- ggplot() +
borders("world", colour = "gray85", fill = "gray80") +
theme_map()

map <- world +
geom_point(aes(x = lon, y = lat, size = followers),
data = rladies,
colour = 'purple', alpha = .5) +
scale_size_continuous(range = c(1, 8),
breaks = c(250, 500, 750, 1000)) +
labs(size = 'Followers')

enter image description here

我想从 map 中移除南极洲,这样它就不会占用太多空白空间。我试着按照另一个 similar Stackoverflow question 的解决方案如下:

world <- map_data("world") %>% 
filter(region != "Antarctica") %>%
ggplot(aes(long, lat, group = paste(region, group))) +
geom_polygon() +
coord_fixed()

map <- world +
geom_point(aes(x = lon, y = lat, size = followers),
data = rladies,
colour = 'purple', alpha = .5) +
scale_size_continuous(range = c(1, 8),
breaks = c(250, 500, 750, 1000)) +
labs(size = 'Followers')

但是当我尝试显示 map 时出现以下错误:

Error in paste(region, group) : object 'region' not found

还有其他方法可以去除 Antartica 吗?


更新:子集 尝试失败

countries <- map_data("world")
map_df <- subset(countries, region != "Antarctica")
map_base <- ggplot(data = map_df, mapping = aes(x = long, y = lat, group = group)) + coord_fixed(1.3) + geom_polygon(color = "black", fill = "gray")
# The base map is created successfully but I cannot plot points on it
map_base + geom_point(aes(x = lon, y = lat, size = followers), data = rladies, colour = 'purple', alpha = .5)

错误:

Error in eval(expr, envir, enclos) : object 'group' not found

最佳答案

根据 hrbmstr 的建议,这是一个使用适当投影和 sf 包(使用 ggplot2 开发版本中的 geom_sf)的解决方案。请注意,我们使用 coord_sf 来设置限制。

library(sf)

world <- map_data("world")
world.sf <- sf::st_as_sf(world, coords = c("long", "lat"), crs = 4326) %>%
group_by(group) %>%
summarize(do_union = FALSE) %>%
st_cast("POLYGON") %>%
ungroup()

world <- ggplot() +
geom_sf(data = world.sf, colour = "gray85", fill = "gray80") +
coord_sf(ylim = c(-50, 90), datum = NA) +
theme(panel.background = element_rect(fill = 'white'))

world +
geom_point(aes(x = lon, y = lat, size = followers),
data = rladies,
colour = 'purple', alpha = .5) +
scale_size_continuous(range = c(1, 8),
breaks = c(250, 500, 750, 1000)) +
labs(size = 'Followers', x = NULL, y = NULL)

enter image description here

关于从 ggplot2 map 中删除南极洲,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50201048/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com