use*_*264 4 r raster legend shapefile ggplot2
我对 ggplot2 中的图例几乎没有疑问。如何从所附代码中连续制作图例。在此代码中,图例采用离散形式,我想将其设为连续形式(平滑连续模式)。代码是可重现的(有点长,但可能在此代码中一行会发生变化)
library(sf)
library(sp)
r <- raster(t((volcano[,ncol(volcano):1] - 94) * 4.95))
# Let's mock with a shapefile
poly <- st_as_sfc(st_bbox(st_as_sf(rasterToPolygons(r))))
# Sample 4 points
set.seed(3456)
sample <- st_sample(poly, 4)
sample <- st_buffer(sample, c(0.01, 0.02, 0.03))
sample <- st_sf(x=1:4, sample)
st_write(sample, "1aa.shp", append = FALSE)
# Mocked data
# Now let's start with code -------
r <- raster(t((volcano[,ncol(volcano):1] - 94) * 4.95))
# Use sf!!
pg <- st_read("1aa.shp") # loadshapfile
plot(r)
plot(st_geometry(pg), add= TRUE,) # it appears here like first picture
(left).
centile90 <- quantile(r, 0.90)
df <- as.data.frame(as(r, "SpatialPixelsDataFrame"))
colnames(df) <- c("value", "x", "y")
library(ggplot2)
mybreaks <- seq(0, 500, 50)
ggplot(df, aes(x, y, z = value)) +
geom_contour_filled(breaks = mybreaks) +
geom_contour(breaks = centile90, colour = "pink",
size = 0.5) +
# And here we have it
geom_sf(data=pg, fill="black", inherit.aes = FALSE) +
scale_fill_manual(values = hcl.colors(length(mybreaks)-1, "Zissou1", rev
= FALSE)) +
scale_x_continuous(expand = c(0, 0)) +
scale_y_continuous(expand = c(0, 0)) +
theme_classic() +
theme()
Run Code Online (Sandbox Code Playgroud)
运行此代码后,我得到了这种形式的图例(附图的左侧),意味着不连续,但我想让这个图例看起来像(附图的右侧)。但在我的代码中,我给出了连续缩放的命令。有人可以告诉我如何使此代码满足所需图例的平滑连续模式。
您可以使用该函数geom_tile并scale_fill_gradientn获得连续比例而不是离散比例图例,如下所示:
library(ggplot2)
library(sf)
library(sp)
library(raster)
mybreaks <- seq(0, 500, 50)
ggplot(df, aes(x, y, fill = value)) +
geom_tile() +
scale_fill_gradientn(
colours = hcl.colors(length(mybreaks)-1, "Zissou1", rev = FALSE),
breaks = mybreaks
) +
geom_sf(data=pg, fill="black", inherit.aes = FALSE) +
scale_x_continuous(expand = c(0, 0)) +
scale_y_continuous(expand = c(0, 0)) +
theme_classic() +
theme()
Run Code Online (Sandbox Code Playgroud)
输出: