我正在用sf
绘制(映射)ggplot2
对象。我的理解是,自版本2.2.1 ggplot2
以来,地理元素geom_sf
用于简单要素对象。
我可以通过执行以下操作来生成所需的确切地图:
library(sf)
library(ggplot2)
# some points to start with
a <- st_as_sf(data.frame(lon = c(1,4,6), lat = c(0,0,-3)), coords = c('lon', 'lat'))
b <- st_as_sf(data.frame(lon = c(2.5,4), lat = c(-4.5,-5)), coords = c('lon', 'lat'))
# circles around those points
buf.a <- st_buffer(a, 1)
buf.b <- st_buffer(b, 1)
# colors to mark the points
sol.a = rgb(1,0,0)
sol.b = rgb(0,0,1)
# colors to fill the circles
fil.a = adjustcolor(sol.a, alpha.f = .25)
fil.b = adjustcolor(sol.b, alpha.f = .25)
# the plot I want
g = ggplot() +
geom_sf(data = buf.a, fill = fil.a, color = NA) +
geom_sf(data = buf.b, fill = fil.b, color = NA) +
geom_sf(data = a, color = sol.a, shape = 20, size = 3) +
geom_sf(data = b, color = sol.b, shape = 20, size = 3)
g
产生
这是我想要的,除了它缺少图例。为此,我正在做
cols.fill = c("GROUP A" = fil.a, "GROUP B" = fil.b)
cols.sol = c("GROUP A" = sol.a, "GROUP B" = sol.b)
g = ggplot() +
geom_sf(data = buf.a, color = NA, aes(fill = 'GROUP A')) +
geom_sf(data = buf.b, color = NA, aes(fill = 'GROUP B')) +
geom_sf(data = a, shape = 20, size = 3, aes(color = 'GROUP A')) +
geom_sf(data = b, shape = 20, size = 3, aes(color = 'GROUP B')) +
scale_fill_manual(name = "circles", values = cols.fill) +
scale_color_manual(name = "points", values = cols.sol)
g
给出
那不是我想要的,因为在传说中:
如果图例可以尊重我的颜色的透明度(在此示例中如此),那就太好了。
我试图将上述内容的最后几行更改为
scale_fill_manual(name = "circles", values = cols.fill,
guide = guide_legend(override.aes = list(shape = c(19, 19)))) +
scale_color_manual(name = "points", values = cols.sol,
guide = guide_legend(override.aes = list(shape = c(20, 20))))
但这对我的情节没有任何作用。
想法?
注意:如果最终对于绘图来说更简单,则可以更改数据的结构,例如,通过在同一简单要素对象中合并对象a
和b
并添加一列指示组(与buf.a
和buf.b
相同)。
答案 0 :(得分:0)
这是我设法到达的距离。
g = ggplot() +
geom_sf(data = buf.a, color = NA, aes(fill = 'GROUP A'), show.legend = "point") +
geom_sf(data = buf.b, color = NA, aes(fill = 'GROUP B'), show.legend = "point") +
geom_sf(data = a, shape = 20, size = 3, aes(color = 'GROUP A'), show.legend = "point") +
geom_sf(data = b, shape = 20, size = 3, aes(color = 'GROUP B'), show.legend = "point") +
scale_color_manual(name = "points", values = cols.sol,
guide = guide_legend(override.aes = list(shape = c(20, 20)))) +
scale_fill_manual(name = "circles", values = cols.fill,
guide = guide_legend(override.aes = list(shape = c(20, 20), color = cols.fill, size = 8)))
g
要摆脱图例符号中的灰色背景,
g + theme(legend.key = element_rect(fill = "white"))
这里唯一的问题是圈子没有我想要的透明度。这很奇怪。
答案 1 :(得分:0)
要获得图例中的透明度,需要将其添加到override.aes中,请尝试:
guide = guide_legend(override.aes = list(alpha = 0.5, shape = c(20, 20), color = cols.fill, size = 8, )))