如何将ggplot2中的离散填充等高线图例改为连续型?
关于ggplot2离散图例转连续平滑图例的调整方法
我有一个关于ggplot2图例的疑问。我提供了一段可复现的R代码,当前代码生成的是离散分段的图例,但我希望将其改为平滑的连续型图例(如附图右侧样式)。代码较长但可能仅需修改一行即可实现,请问如何调整?
用户提供的原代码:
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()
调整方案
要实现平滑连续的图例,核心是替换离散填充图层和手动色标为连续型选项,只需修改2处:
- 将
geom_contour_filled()替换为geom_raster(aes(fill = value), interpolate = TRUE)——直接渲染栅格数据的连续颜色,interpolate=TRUE让颜色过渡更自然 - 将
scale_fill_manual()替换为scale_fill_continuous(type = "Zissou1")——使用连续色标生成平滑渐变图例
修改后的完整代码:
library(sf) library(sp) library(raster) library(ggplot2) # 生成模拟数据(原代码保留) r <- raster(t((volcano[,ncol(volcano):1] - 94) * 4.95)) poly <- st_as_sfc(st_bbox(st_as_sf(rasterToPolygons(r)))) 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) # 加载数据并绘图 r <- raster(t((volcano[,ncol(volcano):1] - 94) * 4.95)) pg <- st_read("1aa.shp") centile90 <- quantile(r, 0.90) df <- as.data.frame(as(r, "SpatialPixelsDataFrame")) colnames(df) <- c("value", "x", "y") ggplot(df, aes(x, y)) + # 替换为连续栅格填充 geom_raster(aes(fill = value), interpolate = TRUE) + geom_contour(aes(z = value), breaks = centile90, colour = "pink", size = 0.5) + geom_sf(data=pg, fill="black", inherit.aes = FALSE) + # 替换为连续色标 scale_fill_continuous(type = "Zissou1") + scale_x_continuous(expand = c(0, 0)) + scale_y_continuous(expand = c(0, 0)) + theme_classic()
说明
geom_contour_filled是基于等高线生成离散分段填充,因此图例必然是离散的;而geom_raster直接根据每个像素的数值渲染连续颜色,配合连续色标就能得到平滑渐变的图例。- 如果需要保留原有的分段参考,也可以在
scale_fill_continuous中添加breaks = mybreaks参数,让图例显示指定的刻度点,但颜色依然是平滑过渡的。
内容的提问来源于stack exchange,提问作者user_3264
相关产品推荐
相关产品推荐

