首页 > 解决方案 > 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“画”一条线到给定点并定位在地图/情节的其他地方吗?我想将“伦敦”放在一边,并提供少量信息,即人口等。有没有办法做到这一点?

标签: rdictionaryggplot2

解决方案


使用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)

在此处输入图像描述


推荐阅读