仅为出现在aes 中的变量创建图例。所以你需要给它添加shape。有许多不同的方法可以为满足一个条件的变量更改颜色,并且可能最简单的方法是您所做的,以绘制不同的子集。如果你决定这样做,最好的做法是不要在主调用中使用aes,因为它可能会搞乱你的情节。
我为您的形状使用了条件语句,并使用scale_shape 格式化该形状。我个人认为情节不必要的额外颜色差异,我可能不会这样做,但因为你已经要求它 - 我们开始吧。
我还将 carb 转换为字符 - 您也可以将其转换为因子。因为它是一个分类变量,所以也显示它是有意义的。
根据评论编辑
像往常一样,有很多方法可以实现目标。下面两种不同的方式更改/删除图例的标题,只显示4 的形状和值。代码中的注释。
选项 1:从没有 '4' 的子集中删除形状,更改图例标题,例如使用labs。
library(ggplot2)
ggplot() +
geom_point(data = subset(mtcars, carb !=4), aes(x = mpg, y = wt, color = as.character(carb)), shape = 1) +
geom_point(data = subset(mtcars, carb ==4), aes(x = mpg, y = wt, shape = carb == 4), color = 'black')+
scale_shape_manual(values = c(`TRUE` = 4, `FALSE` = 1)) +
labs(shape = NULL, color = 'Model prediction') +
guides(color = guide_legend(order = 1), shape = guide_legend(order = 2)) +
## I had to change the legend order, because the shape legend would draw on top otherwise. See link below!
facet_wrap(~ gear, nrow = 1)
现在 - 传说有点分开,相信我,将它们拉得更近是相当棘手的。
因此:
选项 2 分解您的分类数据,子集您的数据,在 scale_color 函数中使用 drop = FALSE,并使用 override.aes 更改图例美学。听起来像个 hack,但仍然比试图缩短两个传奇人物之间的距离更容易、更安全。
mtcars2 <- mtcars
mtcars2$carb2 <- factor(mtcars$carb, levels = c(1:3,6,8,4))
ggplot() +
geom_point(data = subset(mtcars2, carb != 4), aes(x = mpg, y = wt, color= carb2), shape = 1) +
geom_point(data = subset(mtcars, carb == 4), aes(x = mpg, y = wt), shape = 4, color = 'black') +
facet_wrap(~ gear, nrow = 1) +
scale_color_discrete(drop = FALSE) +
labs(color = 'Model prediction') +
guides(color = guide_legend(override.aes = list(shape = c(rep(1, 5), 4),
color = c(RColorBrewer::brewer.pal(5, 'Dark2'), 'black'))))
由reprex package (v0.3.0) 于 2020 年 2 月 3 日创建
一些学习的链接
Legend order is weird
change shapes in legend