我正在创建地图,然后在其上添加一些城市,并且我想拥有多个图例项。
到目前为止,我有以下代码:
library(tidyverse)
library(raster)
library(sf)
library(maptools)
#a location to add to the map
city <- tibble(y = c(47.7128),
x = c(74.0060))
city <- st_as_sf(city, coords = c("x", "y"), crs = "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs +towgs84=0,0,0")
#world map to plot, along with a raster of distance from a point
data(wrld_simpl)
wrld_simpl_sf <- sf::st_as_sf(wrld_simpl)
r <- raster(wrld_simpl, res = 1)
wrld_r <- rasterize(wrld_simpl, r)
#
pt1 <- matrix(c(100,0), ncol = 2)
dist1 <- distanceFromPoints(r, pt1)
values(dist1)[values(dist1) > 5e6] <- NA
plot(dist1)
gplot_data <- function(x, maxpixels = 50000) {
x <- raster::sampleRegular(x, maxpixels, asRaster = TRUE)
coords <- raster::xyFromCell(x, seq_len(raster::ncell(x)))
## Extract values
dat <- utils::stack(as.data.frame(raster::getValues(x)))
names(dat) <- c('value', 'variable')
dat <- dplyr::as.tbl(data.frame(coords, dat))
if (!is.null(levels(x))) {
dat <- dplyr::left_join(dat, levels(x)[[1]],
by = c("value" = "ID"))
}
dat
}
gplot_dist1 <- gplot_data(dist1)
gplot_wrld_r <- gplot_data(wrld_r)
#plot data
ggplot() +
geom_sf(data = wrld_simpl_sf, fill = "grey20",
colour = "white", size = 0.2) +
geom_tile(data = gplot_dist1,
aes(x = x, y = y, fill = value)) +
scale_fill_gradient("Distance",
low = 'yellow', high = 'blue',
na.value = NA) +
geom_sf(data = city, fill = "red", color = "red", size = 3, shape = 21)
返回:
这很好,但是现在我只想将geom_sf(data = city, fill = "red", color = "red", size = 3, shape = 21)
的红点添加到带有标题“城市”的图例中。
答案 0 :(得分:3)
您可以使用scale_color_manual函数。以我的理解(今天我发现了这一点),它使您可以将颜色映射到随后出现在图例中的“色阶”。
更改代码以使其具有以下功能即可。
geom_sf(数据=城市,填充=“红色”, aes(颜色=“城市”),大小= 3,形状= 21)+
scale_color_manual(values = c(“ Cities” =“ red”))