R ggplot2中的图例颜色中的图例颜色文本

时间:2016-11-07 20:52:19

标签: r ggplot2 facet geom-text

我有一个示例数据框:

dput(数据)

structure(list(DAF = c(0.00704225, 0.00352113, 0.00352113, 0.028169, 
0.00352113, 0.00704225, 0.0105634, 0.00352113, 0.0105634, 0.00352113, 
0.00352113, 0.00352113, 0.0176056, 0.0140845, 0.00352113, 0.0140845, 
0.00352113, 0.0105634, 0.00352113, 0.00352113, 0.0140845, 0.00352113, 
0.084507, 0.00352113, 0.0669014, 0.00704225, 0.00352113, 0.00352113, 
0.00704225, 0.00352113, 0.00704225, 0.00352113, 0.00352113, 0.028169, 
0.00352113, 0.00704225, 0.0105634, 0.00352113, 0.0105634, 0.00352113, 
0.00352113, 0.00352113, 0.0176056, 0.0140845, 0.00352113, 0.0140845, 
0.00352113, 0.0105634, 0.00352113, 0.00352113, 0.0140845, 0.00352113, 
0.084507, 0.00352113, 0.0669014, 0.00704225, 0.00352113, 0.00352113, 
0.00704225, 0.00352113), TYPE = structure(c(2L, 2L, 2L, 2L, 2L, 
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("All SVs", "bDEL"), class = "factor"), 
Function = structure(c(2L, 2L, 2L, 1L, 2L, 2L, 2L, 2L, 2L, 
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 
2L, 2L, 2L, 2L, 2L, 1L, 2L, 2L, 2L, 1L, 2L, 2L, 2L, 2L, 2L, 
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 
2L, 2L, 2L, 2L, 2L, 1L), .Label = c("Genic", "Intergenic"
), class = "factor")), .Names = c("DAF", "TYPE", "Function"
), class = "data.frame", row.names = c(NA, -60L))

我使用“

绘制
p1<-ggplot(sv,aes(x=DAF,y=..density..,fill=Function))+geom_histogram(position="dodge",binwidth=0.02)+facet_wrap( ~ TYPE, scales = "free",ncol=2)

数据框中带注释的文本:

> dput(dat)
structure(list(x = c(0.05, 0.05, 0.05, 0.05, 0.05, 0.05), y = c(20L, 
17L, 14L, 35L, 30L, 25L), labs = structure(c(3L, 4L, 6L, 1L, 
2L, 5L), .Label = c("mean=0.0173", "mean=0.0190", "mean=0.0415", 
"mean=0.0440", "p=0.0393", "p=1.47e-08"), class = "factor"), 
    TYPE = structure(c(1L, 1L, 1L, 2L, 2L, 2L), .Label = c("All SVs", 
    "bDEL"), class = "factor")), .Names = c("x", "y", "labs", 
"TYPE"), class = "data.frame", row.names = c(NA, -6L))


p2<-p1+geom_text(aes(x, y, label=labs),size=1,data=dat,inherit.aes = F)

给出了以下情节:

enter image description here

但是,我需要通过相应的图例颜色为每个方面内的文本“mean = ...”着色。即在方面所有SV中,'mean = 0.0415'应为“Genic”颜色,'mean = 0.0440'为'Intergenic'颜色。

1 个答案:

答案 0 :(得分:2)

您需要在“dat”中添加一列来表示每行/标签应该在哪个组中。我使用NA作为p值。

dat$Function = c("Genic", "Intergenic", NA, "Genic", "Intergenic", NA)

然后,您可以将此变量映射到color中的geom_text。您可以使用NA

避免将show.legend = FALSE添加到图例中
p1 + geom_text(aes(x, y, label = labs, color = Function), 
               size = 1, data = dat, inherit.aes = FALSE, show.legend = FALSE)

NA颜色默认为grey50,如果scale_color_discrete需要,您可以将其更改为其他内容。

p1 + geom_text(aes(x, y, label = labs, color = Function), 
               size = 1, data = dat, inherit.aes = FALSE, show.legend = FALSE) +
    scale_color_discrete(na.value = "black")