将geom_hline图例添加到现有的geom bar图例

时间:2015-07-21 18:19:31

标签: r ggplot2

我想在现有的代表虚线的图例下添加一个图例,这样虚线就可以标记为" avg tx effect"并被置于研究3之下。

enter image description here

library(ggplot2)
library(ggthemes)

#dput(df)

df=structure(list(study = structure(c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 
2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L), .Label = c("study1", "study2", 
"study3"), class = "factor"), d = c(-0.205, 0.1075, 0.3525, -0.37, 
0.3, 0.42, -0.28, 0.09, 0.59, 0.11, -0.05, 0.25, 0, 0.25, 0.49
), Outcome = c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 4L, 4L, 4L, 
5L, 5L, 5L), Outcome2 = structure(c(1L, 1L, 1L, 4L, 4L, 4L, 7L, 
7L, 7L, 10L, 10L, 10L, 13L, 13L, 13L), .Label = c("1", "1", "1", 
"2", "2", "2", "3", "3", "3", "4", "4", "4", "5", "5", "5"), class = "factor")), .Names = c("study", 
"d", "Outcome", "Outcome2"), row.names = c(NA, -15L), class = "data.frame")

ggplot(df, aes(x=Outcome2, y=d, fill=study)) + 
   geom_bar(position=position_dodge(), aes(x=Outcome2),stat="identity",
             colour="black", # Use black outlines,
             size=.3) +      # Thinner lines
    xlab("Outcome") +
    ylab("Cohen's D Effect Size") +
    scale_fill_grey(name="Study", 
                   labels=c("study1","study2", "study3"))+
        theme_bw()+
    geom_hline(yintercept=.15,linetype=2)   

2 个答案:

答案 0 :(得分:7)

ggplot的一般功能是,要生成图例,您需要将<{1}}理论(例如aes映射到其中的变量数据,而不是设置为常量。在linetype的情况下,这可以通过将截距放在单独的数据帧中来实现。另请注意geom_hline

然后使用show_guide = TRUE自定义图例。使用scale_linetype_manual删除fill图例中的黑线。

以下是代码的精简版,仅显示最必要的步骤:

override.aes

enter image description here

答案 1 :(得分:2)

正如@Gregor建议的那样,您可以通过添加annotate()来为此行使用直接标签,如下所示:

ggplot(df, aes(x=Outcome2, y=d, fill=study)) + 
   geom_bar(position=position_dodge(), aes(x=Outcome2),stat="identity",
             colour="black", # Use black outlines,
             size=.3) +      # Thinner lines
    xlab("Outcome") +
    ylab("Cohen's D Effect Size") +
    scale_fill_grey(name="Study", 
                   labels=c("study1","study2", "study3"))+
        theme_bw()+
    geom_hline(yintercept=.15,linetype=2) +annotate("text",x=.7,y=.17,size=3,label=c('avg tx ef')) 

enter image description here

如果空间有问题,您可以使用wrapper描述的here来包装文本。只需运行wrapper <- function(x, ...) paste(strwrap(x, ...), collapse = "\n"),然后添加+annotate("text",x=.7,y=.18,size=3,label=wrapper('avg tx effect',10))。产生:

enter image description here