r - ggplot2 在具有多个分组的图例中正确显示分层点

标签 r ggplot2 legend

我希望通过颜色和圈出它们来指示图中的某些点(用于黑白查看)。我已经在使用形状参数进行单独分组,但可以通过使用两个 geom_point 层来完成此操作。不幸的是,我不知道如何让图例与我的观点相对应。这是一个最小的例子来说明我的意思:

x <- data.frame(names = rep(letters[1:24],2), 
            grouping1 = factor(rep(c("Treatment", "Control"), each = 24)),
            grouping2 = factor(rep(rep(c("Matched","Unmatched"), each = 12), 2)), 
            values1 = runif(48, 60, 120), values2 = runif(48, 11, 25))


ggplot(data = x, aes(x = values1, y = values2, group = names)) +
     geom_point(aes(shape = grouping1, color = grouping2)) +
     geom_line(alpha = 0.2) +
     geom_point(data = x[x$grouping1 == 1 & x$grouping2 == 1,], aes(values1, values2), 
                shape = 21, size = 3, show.legend = TRUE)

如果我包含上面的 show.legend = TRUE ,则会圈出图例中的所有内容。我希望只有红点(如图所示)也被图例中的边框包围。感谢您的任何帮助。 enter image description here

最佳答案

如果将两个组组合起来,将它们全部放入图例中会更简单

x$bothgroups <- paste(x$grouping1, x$grouping2)    

然后使用具有颜色和填充特性的形状 21 - 25。这样,您可以将颜色设置为对要圈出的点使用黑色,创建深色轮廓,并对不需要圈出的点使用与填充相同的颜色,因此它们显示为没有轮廓的纯色点。

ggplot(data = x, aes(x = values1, y = values2, group = names)) +
  geom_point(aes(shape = bothgroups, color = bothgroups, fill = bothgroups,
                 stroke = 1.5)) + #make border thicker so it is visible
  geom_line(alpha = 0.2) +
  scale_shape_manual(values = c(21, 24, 21, 21)) + #circle triangle circle circle
  #fill sets color in center of points
  scale_fill_manual(values = c("green", "green", "tomato", "green")) +
  #color sets outline color - match to fill for points you don't want circled
  scale_color_manual(values = c("green", "green", "black", "black"))

enter image description here

关于r - ggplot2 在具有多个分组的图例中正确显示分层点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47597918/

相关文章:

c++ - 英特尔DAAL 2017 Beta更新1编译错误

r - 控制ggplot图例中的线条颜色和线条类型

r - 许多 "duplicated levels in factors are deprecated"警告与 ggplot2

python - 如何使用 matplotlib 为 3D 散点图创建标记大小图例?

r - 从位置 x 选择 R 中的每第 n 列

r - 按降序排列两个变量条形图

r - ggplot2 中刻度线间隔和密度曲线的错误

r - ggplot 更改由 x 轴值指定的线条颜色

d3.js - 如何在nvd3中禁用图例或限制其大小

javascript - D3圆包图中的图例