ggplot2 中有两个图重叠的错误颜色图例

Wrong color legends with two plots overlay in ggplot2

我正在尝试以这种方式使用 ggplot2 在空间图中给出组合配色方案:

我发现没有比堆叠两个图更简单的方法了,上面一个是灰色渐变来模拟饱和度:

    ggplot(data = italian.regions) +
  geom_sf(fill = c("#BFD6FF", "#FFEBBF")[as.numeric(as.factor(regions.lookup$`engine.top`))], lwd = .2) +
  geom_sf(aes(fill = regions.lookup$`engine.diff`), lwd = .2, alpha = .3) +
  scale_fill_gradient(high = "#666666", low = "#EFEFEF")

我使用美学来填充渐变,这很有效。这是一个示例图:

但是(当然)颜色图例是指美学,但用一个描述 'engine.top' 中离散值的图例应该更有意义。

可以吗?有没有更简单的方法来获得双色调渐变配色方案而不堆叠两个图?

我的首选方法是使用 scale_fill_identity()hcl()。看看这是否适合你

library(sf)
library(tidyverse)

# this file is already on your computer 
nc <- st_read(system.file("shape/nc.shp", package="sf"))


nc_colors <-
  nc %>% 
  mutate(
    # 220 = blue and # 40 = orange
    hue = ifelse(str_detect(CNTY_ID, "^18"), 220, 40),
    light = AREA/max(AREA)*100,
    # the hcl function returns a hex code
    hex = hcl(h = hue, l = light)
  )


ggplot() +
  geom_sf(data = nc_colors, aes(fill = hex)) +
  scale_fill_identity()

您可以使用的另一种解决方案是执行类似 aes(...fill = hue, alpha = AREA) 的操作,然后使用 scale_fill_manual()