0

我有一个我想绘制的 sf 对象。这是一张瑞典县(21 个县)的地图,对于每个县,我都有一个值。然而,该值可以是正值或负值,甚至是 NA。我想在瑞典绘制地图并将所有具有 NA 的县着色为白色,然后为所有连续值用渐变(取决于值)为所有其他县着色。但是当我尝试时,我只收到此错误消息:错误:提供给离散刻度的连续值

这不是我的真实数据,但我不确定如何演示 sf-object。所以这只是一个带有县名和值的数据框(所以没有坐标或任何东西):

data <- data.frame(Diff = c("NA", "NA", "5", "6.89", "9", "-4", "3.56"), 
                   County = c("Halland", "Gotland", "Skane", "Jonkoping", "Gotaland",
                              "Blekinge", "Dalarna"))

ggplot(data) +
  geom_sf(aes(fill = Diff), color = "black") +
  scale_fill_manual(values = c("blue", "yellow", viridis::viridis(4))) +
  coord_sf(datum = NA) 

所以我想绘制整个地图,如果一个县有 NA,该县应该是白色的。然后我想为每个县的值(从负值到正值)设置不同的颜色渐变。

有没有人遇到过同样的问题?

4

1 回答 1

2

以下代码适用于我

library(sf)
library(tidyverse)

#Downloading data from DIVA GIS website
get_sweden_map <- function(cong=113) {
  tmp_file <- tempfile()
  tmp_dir  <- tempdir()
  zp <- sprintf("http://biogeo.ucdavis.edu/data/diva/adm/SWE_adm.zip",cong)
  download.file(zp, tmp_file)
  unzip(zipfile = tmp_file, exdir = tmp_dir)
  fpath <- paste(tmp_dir)
  st_read(fpath, layer = "SWE_adm1")
}

swe <- get_sweden_map(114)

#Plot the Counties
plot(swe[5])

data <- tibble(Diff = c("NA", "NA", "5", "6.89", "9", "-4", "3.56"), 
                   County = c("Halland", "Gotland", "Skane", "Jonkoping", "Gotaland",
                              "Blekinge", "Dalarna"))

#Join the data to the swe shapefile
sweden <- swe %>% left_join(data, by=c("NAME_1"="County"))

#Plotting the data
ggplot(sweden) +
  geom_sf(aes(fill = Diff), color = "black") +
  scale_fill_manual(values = c("blue", "yellow", viridis::viridis(4))) +
  coord_sf(datum = NA) 

在此处输入图像描述

于 2021-04-09T09:48:02.000 回答