将轮廓颜色添加为点属性

时间:2016-08-17 16:36:11

标签: r ggplot2

这是一个愚蠢的data.frame

df <- read.table(textConnection(
"pole medal  bag     x     y
north gold   paper   0.852 0.423
north gold   plastic 0.277 0.055
north silver paper   0.257 0.211
north silver plastic 0.457 0.614
north bronze paper   0.825 0.299
north bronze plastic 0.672 0.126
south gold   paper   0.482 0.764
south gold   plastic 0.603 0.869
south silver paper   0.327 0.451
south silver plastic 0.147 0.672
south bronze paper   0.140 0.466
south bronze plastic 0.833 0.325
"), header = TRUE)

我知道如何以一种使用颜色和形状来表示这两个因子属性的方式绘制这些数据的散点图。例如:

library(ggplot2)
ggplot(data = df, aes(x = x, y = y)) +
geom_point(size = 4, aes(shape = pole, color = bag))

enter image description here

我想再添加一个点功能来指示第三个因子属性(在本例中为medal)。想到的一种可能性是彩色轮廓。

有没有方便的方法呢? (问题的一个棘手方面是轮廓的调色板必须与用于点填充的调色板不同,因为对于每个点,轮廓和填充必须在视觉上可区分。)

更新:

当我尝试Gregor的建议时,这些观点看起来是对的,但传说搞砸了:

enter image description here

1 个答案:

答案 0 :(得分:5)

是的,你可以! ?geom_point的帮助中有一个例子:

# For shapes that have a border (like 21), you can colour the inside and
# outside separately. Use the stroke aesthetic to modify the width of the
# border
ggplot(mtcars, aes(wt, mpg)) +
  geom_point(shape = 21, colour = "black", fill = "white", size = 5, stroke = 5)

在您的情况下,您将要使用形状21(带轮廓的圆圈)和24(带轮廓的三角形),如下所示:

ggplot(data = df, aes(x = x, y = y)) +
  geom_point(aes(shape = pole, color = medal, fill = bag),
             size = 4, stroke = 2) + 
  scale_shape_manual(values = c(21, 24))

请注意,使用两者时,fill对应于点的中心,color对应于轮廓。您可以通过设置stroke来更改轮廓的重量。

如评论中所述,您必须做一些额外的调整才能使传奇正确。添加到上面的图:

fill_col = c("pink", "white")
outline_col = c("brown", "gold", "grey74")

scale_fill_manual(values = fill_col) + 
scale_color_manual(values = outline_col) +
guides(fill = guide_legend(override.aes = list(color = fill_col)),
       color = guide_legend(override.aes = list(shape = 21)))