我正在绘制地图上两个独立图层的点数据,并希望在一个图例中显示两个图层的信息。
下面是一些说明问题的代码:
set.seed(42)
lat1 <- rnorm(10, 54, 12)
long1 <- rnorm(10, 44, 12)
val1 <- rnorm(10, 10, 3)
lat2 <- rnorm(10, 54, 12)
long2 <- rnorm(10, 44, 12)
val2 <- rnorm(10, 10, 3)
df1 <- as.data.frame(cbind(long1, lat1, val1))
df2 <- as.data.frame(cbind(long2, lat2, val2))
library(ggplot2)
library(scales)
f <- ggplot() +
geom_point(data=df1, aes(x=lat1, y=long1, size=val1, fill=val1), shape=21, alpha=0.6) +
scale_size_continuous(range = c(2, 12), breaks=pretty_breaks(4)) +
scale_fill_distiller(direction = -1, palette="RdYlBu", breaks=pretty_breaks(4)) +
guides(fill = guide_legend(), size = guide_legend()) +
theme_minimal()
p <- f + geom_point(data=df2, aes(x=lat2, y=long2, color="val2"), shape=17, size=3) +
scale_color_manual(values="black",name="")
p
我能管理的最好的办法是创建两个单独的图例,然后删除其中一个图例标题。理想情况下,实心圆圈和黑色菱形都应属于同一个图例,例如“价值”和黑色菱形将显示为“ NA”。任何帮助深表感谢!
答案 0 :(得分:2)
我们必须绘制两个不同的图例,但将它们彼此靠近(在legend.spacing.y
中使用负值需要ggplot2_3.0.0)。这种方法带来了另一个问题-两个图例无法对齐,因此我们必须绘制另一组菱形(较大以匹配非菱形,但看不见的alpha = 0
)
ggplot() +
geom_point(data = df1,
aes(lat1, long1, size = val1, fill = val1),
shape = 21, alpha = 0.6) +
geom_point(data = df2,
aes(lat2, long2, color = "val2"),
shape = 17, size = 3) +
geom_point(data = df2,
aes(lat2, long2, color = "val2"),
shape = 17, size = 11.5, alpha = 0) +
scale_size_continuous(range = c(2, 12), breaks = pretty_breaks(4)) +
scale_fill_distiller(direction = -1, palette = "RdYlBu", breaks = pretty_breaks(4)) +
scale_color_manual(values = "black", name = "Value\n") +
labs(fill = NULL,
size = NULL) +
guides(fill = guide_legend(),
size = guide_legend(),
color = guide_legend(order = 1)) +
theme_minimal() +
theme(legend.spacing.y = unit(-0.4, "cm"))