带有两个不同geom_point的ggplot2图例

时间:2014-01-21 13:00:37

标签: r ggplot2

我有以下ggplot图表,其中圆圈表示观察到的数据和每个治疗的平均值:

d <- data.frame(Number = rnorm(12,100,20), 
                Treatment = rep(c("A","B","C", "D"), each = 3))
av <- aggregate(d["Number"], d["Treatment"], mean)

ggplot(data = d, aes(y = Number, x = Treatment)) + 
    geom_point(shape = 1, size = 6,  color = "grey50") +
    geom_point(data=av, shape = 4) +
    theme_bw()

我想在图表顶部添加一个带有完全相同符号的图例,但我有点迷失...我用aes强制创建图例,然后尝试用手动刻度修改它但是结果并不令人信服。我想有一个大小为6的灰色圆圈。对于这样一个基本的东西来说听起来也很复杂......可能有一个更简单的解决方案。

ggplot(data = d, aes(y = Number, x = Treatment)) + 
    geom_point(aes(shape = "1", size = "6",  color = "grey50")) +
    geom_point(data=av, aes(shape = "4")) +
    theme_bw() +
    scale_shape_manual(name = "", values = c(1,4), labels = c("observed values", "mean")) +
    scale_size_manual(name = "", values = c(6,1), labels = c("observed values", "mean")) +
    scale_color_manual(name = "", values = c("grey50","black"), 
                       labels = c("observed values", "mean")) +
    theme(legend.position = "top",
          legend.key = element_rect(color = NA))

http://imagizer.imageshack.us/v2/320x240q90/842/4pgj.png

1 个答案:

答案 0 :(得分:3)

ggplot2方法将所有内容组合成一个data.frame,如下所示:

av$Aggregated <- "mean"
d$Aggregated <- "observed value"
d <- rbind(d, av)

ggplot(data = d, aes(y = Number, x = Treatment, 
                     shape=Aggregated, size=Aggregated, colour=Aggregated)) + 
   geom_point() 

而不是使用手动缩放和主题进行自定义。