如何使用 ggplot2 [duplicate] 在地图上绘制 R 中的国家/地区名称

How can I plot the country name in R over a map using ggplot2 [duplicate]

提问人:slow_learner 提问时间:11/16/2022 更新时间:11/16/2022 访问量:56

问:

大家好,我已经生成了一些南美国家的地图作为

library(maps)
library(ggplot2)
library(dplyr)


p=c("Brazil", "Argentina", "Chile", "Uruguay", "Paraguay", "Ecuador", "Peru", "Venezuela",
         "Colombia", "Bolivia")

mp<-map_data("world", region=p) 

mlola <- mp %>%  group_by(region) %>% 
  summarize(mlo= mean(long), mla=mean(lat))


ggplot(mapa_paises,aes( x= long, y = lat, group=group, fill=region)) +
  geom_polygon( )+
  theme(panel.background = element_rect(fill=NA))

现在我想使用变量绘制国家/地区的名称,该变量包含每个国家/地区内的位置。但是,我不知道该怎么做。我认为可以使用geom_text来完成,但是,我所有的尝试都失败了。有人可以帮我吗?mlola

r ggplot2 绘图 dplyr

评论


答:

2赞 Allan Cameron 11/16/2022 #1

由于您正在绘制 x、y 数据,因此使用标签位置的简单纬度和经度平均值将获得合理的结果:

library(maps)
library(ggplot2)
library(dplyr)

p <- c("Brazil", "Argentina", "Chile", "Uruguay", "Paraguay", 
       "Ecuador", "Peru", "Venezuela", "Colombia", "Bolivia")

mp <- map_data("world", region = p)

ggplot(mp, aes(x = long, y = lat, group = group, fill = region)) +
  geom_polygon(col = "gray75", alpha = 0.25) +
  geom_text(data = . %>% group_by(region) %>% summarise_all(mean),
            aes(label = region), size = 5, fontface = 2, color = "gray20") +
  scale_fill_discrete(guide = "none") +
  theme(panel.background = element_rect(fill = NA))

enter image description here

评论

0赞 slow_learner 11/16/2022
感谢您的回答,它运行良好。如果我还能标记这些国家的首都,我正在卷曲,例如-34.1 N,-58.06 E是布宜诺斯艾利斯的位置。我的想法是创建另一个向量,例如,我不知道如何使用您的解决方案来做到这一点mlola <- mp %>% group_by(region) %>% summarize(mlo= mean(long), mla=mean(lat))
0赞 Allan Cameron 11/16/2022
@slow_learner 你有每个城市的坐标吗?
0赞 slow_learner 11/16/2022
让我们用 -34.1 N,-58.06 E 为布宜诺斯艾利斯,-12N,-77 E 为利马,其余的我稍后会尝试计算
1赞 Allan Cameron 11/16/2022
你可以做到+ annotate(geom = "text", x = c(-58.06, -77), y = c(-34.1, -12), labels = c("Buenos Aires", "Lima"))
1赞 Allan Cameron 11/16/2022
@slow_learner对不起,那应该是而不是labellabels