ggplot-制作自定义地图

时间:2020-04-29 04:28:37

标签: r ggplot2

我需要根据平均年龄,收入等一些指标为克罗地亚的不同县涂上不同的颜色。但是,在能够做到这一点之前,我想知道如何将R的位置数据导入R每个县。

我找不到任何包含此数据的预先存在的软件包(如果不正确,我深表歉意,我是ggplot中处理地图的新手。)

我唯一拥有的是一张显示每个县的边界的图片,下面附上。但是,我不知道如何将其转换为ggplot可以使用的东西。

enter image description here

2 个答案:

答案 0 :(得分:0)

您可以通过选择国家作为克罗地亚从https://www.diva-gis.org/gdata下载shapefile。然后使用以下代码

library(rgdal)
df <- readOGR(dsn = "C:\\Users\\User\\Desktop\\HRV_adm", layer = "HRV_adm1")

#To view the attributes
head(df@data)

#For plotting the map
plot(df["NAME_1"], axes = TRUE)

要使用ggplot2进行绘制,可以使用

library(sf)
library(ggplot2)
#Plotting Using ggplot2
sf <- st_read(dsn="C:\\Users\\User\\Desktop\\HRV_adm", layer="HRV_adm1")

ggplot(sf) + 
  geom_sf(aes(fill = NAME_1)) + theme(legend.position = "none")+
  geom_sf_text(aes(label = NAME_1), check_overlap = T)

enter image description here

答案 1 :(得分:0)

您需要克罗地亚县的shapefile。

您可以先下载并解压缩shapefile from this page

您可以使用readOGR()包中的rgdal将shapefile读入R。

您可以使用readOGRfortify的输出转换为数据帧。然后,您需要按县名将其他数据加入该数据框。

这是绘制地图的基本步骤。

library(rgdal)
library(ggplot2)
library(dplyr)

# change the path here to wherever the .shp file is located
croatia <- readOGR("../../Downloads/gadm36_HRV_shp/gadm36_HRV_1.shp")

croatia_df <- fortify(croatia, region = "NAME_1")

# let's add some fake data called Var
set.seed(1001)
croatia_df <- 
  croatia_df %>% 
  distinct(id) %>% 
  mutate(Var = sample(1:100, 21, replace = TRUE)) %>% 
  left_join(croatia_df)

ggplot(croatia_df) + 
  aes(long, lat, group = group, fill = Var) + 
  geom_polygon() +
  geom_path(color="white") +
  coord_map() + 
  scale_fill_viridis_c()

结果:

enter image description here