将 geom_hline 个图例添加到现有几何条图例

Add geom_hline legend to existing geom bar legend

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

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)   

正如@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')) 

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

ggplot 的一个一般特征是要生成图例,您需要 映射 您的 aesthetics(例如 linetype)到数据中的一个变量,而不是设置它为常量。在 geom_hline 的情况下,这可以通过将拦截放在单独的数据帧中来实现。另请注意 show_guide = TRUE

然后使用 scale_linetype_manual 自定义图例。使用 override.aes.

删除 fill 图例中的黑线

这是您的代码的精简版本,仅显示最必要的步骤:

df2 <- data.frame(yi = 0.15)

ggplot(data = df, aes(x = Outcome2, y = d, fill = study)) + 
  geom_bar(position = "dodge", stat = "identity") +
  geom_hline(data = df2, aes(yintercept = yi, linetype = factor(yi)), show_guide = TRUE) +
  scale_linetype_manual(name = "avg tx effect", values = "dashed", labels = "") +
  guides(fill = guide_legend(override.aes = list(linetype = "blank")))