r - geom_label 可以将点绘制到地图上的某个位置吗?
问题描述
我正在使用 制作地图ggplot2
,并且我想在地图上放置一些点标签(在地图的边缘或可能是边缘),并带有一些描述该点的文本。例如,以下代码产生:
require(tidyverse)
# UK Base polygon
UK <- map_data(map = "world", region = "UK",interior = T)
# Cities to plot as geom_points
UK_cities <- world.cities %>%
filter(country.etc == 'UK')
# Filter for the ones of interest
UK_cities <- UK_cities %>%
filter(name %in% c('London',
'Edinburgh',
'Glasgow',
'Birmingham',
'Edinburgh'))
# plot with ggplot
ggplot(data = UK, aes(x = long, y = lat, group = group)) +
geom_polygon(aes(x = long, y = lat, group = group),fill = 'grey80',
color = 'grey80') +
geom_point(data = UK_cities,aes(long, lat,group = name))+
geom_text(data = UK_cities,
aes(long, lat,label = name,group = name),
color = 'black',
size = 3)+
coord_map()+
theme_void()
我的问题是:可以geom_label
“画”一条线到给定点并定位在地图/情节的其他地方吗?我想将“伦敦”放在一边,并提供少量信息,即人口等。有没有办法做到这一点?
解决方案
使用ggrepel
'sgeom_text_repel
方法:
library(tidyverse)
library(maps)
library(ggrepel)
# UK Base polygon
UK <- map_data(map = "world", region = "UK",interior = T)
# Cities to plot as geom_points
UK_cities <- world.cities %>%
filter(country.etc == 'UK')
# Filter for the ones of interest
UK_cities <- UK_cities %>%
filter(name %in% c('London',
'Edinburgh',
'Glasgow',
'Birmingham',
'Edinburgh'))
# plot with ggplot
plot = ggplot(data = UK, aes(x = long, y = lat, group = group)) +
geom_polygon(aes(x = long, y = lat, group = group),fill = 'grey80',
color = 'grey80') +
geom_point(data = UK_cities,aes(long, lat,group = name))+
geom_text_repel(data = UK_cities,
aes(long, lat,label = name,group = name),
color = 'black',
size = 3,
box.padding = 0.7, point.padding = 0.5) +
coord_map()+
theme_void()
print(plot)
推荐阅读
- android - Agora.io React Native SDK 问题:找不到符号方法
- c# - XML错误地将节点序列化为父类而不是子类
- java - Java/Spring MVC:列出 mediaTypes / 读取内容协商设置
- python - 矩阵链应用程序中所有可能的分组
- bash - 在脚本中使用 psql 将视图和表的 ownerhsip 从 postgres 超级用户转移到另一个用户
- ios - Swift - didFinish 导航从未在加载方法上调用
- ruby-on-rails - 使用回形针上传后图像权重更高
- reactjs - 使用 MemoryRouter 时如何知道当前 url
- list - Haskell - 根据函数返回的条件创建列表
- c++ - std::variant<>::get() 不能与 Apple LLVM 10.0 一起编译