首页 > 解决方案 > 在 geom_sf 中填充连续颜色

问题描述

我正在运行代码以在 R 中创建地图:

library(tidyverse)
library(ggplot2)
library(eurostat)
library(janitor)
library(sf)

eugd <- eurostat_geodata_60_2016 %>% clean_names()
eugdtr <- eugd %>% st_transform(crs = 3035)
gd_de <- eugdtr %>% filter(cntr_code == "DE", levl_code == 2) 

# download the dataset 
# Economically active population (unit: 1000)
df_d <- get_eurostat("lfst_r_lfp2act")

df_de <- df_d %>% 
  filter(
    geo %>% str_sub(1,2) == "DE", # only Italy
    geo %>% paste %>% nchar == 4, # only NUTS-2 
    age %in% c("Y15-24")# my guess is that most of our problems were because of the Russian Doll (Matreshka) effect of the way spatial data is organized
  ) %>% 
  transmute(
    id = geo %>% paste,
    year = time %>% lubridate::year(),
    eap = values,
    sex = sex
  ) %>% 
  group_by(id,year) %>% 
  summarise(eap= sum(eap)) %>% ungroup()

de <- left_join(gd_de, df_de, "id")

library(viridis)
library(cowplot)

# choose year=2000
de %>% 
  filter(year %in% c(2000)) %>%
  ggplot()+
  geom_sf(aes(fill = eap), color = NA)+
  scale_fill_viridis_b()+
  coord_sf(datum = NA)+
  theme_map()+
  theme(legend.position="right",
        plot.title = element_text(hjust = 0.5,color = "Gray40", size = 16, face = "bold"),
        plot.subtitle = element_text(color = "blue"),
        plot.caption = element_text(color = "Gray60"))+ 
  guides(fill = guide_legend(title = "Unit: 1000", title.position = "bottom", title.theme =element_text(size = 10, face = "bold",colour = "gray70",angle = 0)))

我得到这样的数字:

在此处输入图像描述

但是,我想更改图例以及用连续颜色填充地图的颜色(因为特征“eap”是一个连续变量),不像这样,看起来像一个离散变量。例如,像这样:

在此处输入图像描述

我已经试过了

scale_fill_viridis_c()

scale_colour_gradient2()

两者都不起作用。

如果有人可以帮助我,将不胜感激非常感谢。

标签: rggplot2geomviridis

解决方案


您可以使用scale_fill_gradient2()手册midpointguide_colorbar()获得所需的效果:

de %>% 
  filter(year %in% c(2000)) %>%
  ggplot() +
  geom_sf(aes(fill = eap), color = NA) +
  scale_fill_gradient2(midpoint = 275) +
  coord_sf(datum = NA) +
  theme_map() +
  theme(legend.position="right",
        plot.title = element_text(hjust = 0.5,
                                  color = "Gray40",
                                  size = 16,
                                  face = "bold"),
        plot.subtitle = element_text(color = "blue"),
        plot.caption = element_text(color = "Gray60"))  +
guides(fill = guide_colorbar(title = "Unit: 1000",
                             title.position = "bottom",
                             title.theme = element_text(size = 10,
                                                        face = "bold",
                                                        colour = "gray70",
                                                        angle = 0)))

情节:

梯度图


推荐阅读