对于不同的病例,我有一系列的箱形图(对照与病人)。我想根据条件中位数(对照)>给箱图(不是填充箱图)提供不同的背景颜色。中位数(患者)。我正在使用facet_grid。
编辑:
library(data.table)
library(ggplot2)
set.seed(10)
my.t.test_p.value =function(...) {
obj=try(t.test(...), silent=TRUE)
if (is(obj, "try-error")) return(NA) else return(obj$p.value)
}
df <- data.frame(
site = sample(c("A", "B","C"), 30, replace = TRUE),
control = sample(c(0,1),30,replace = TRUE),
y=rnorm(30)
)
dt=data.table(df)
pval = dt[, list(pvalue = paste0("p= ",sprintf("%.3f", my.t.test_p.value(y~control)))), by=list(site)]
pval = as.data.frame(pval)
pval['sig']=as.numeric(gsub('p= ','',pval$pvalue)) <0.3 ## just for simplicity ;)
p=ggplot(data=df, aes(control,y)) + geom_boxplot(aes(fill=as.factor(control))) +
facet_grid(~site)
print(p)
我想使用pval $ sig绘制箱线图的背景。例如,红色为<0.3,绿色为> 0.3。
答案 0 :(得分:1)
我喜欢搞乱ggplot grobs,所以这里有一个可能性(我相信其他人可以比这更好地自动化):
library(ggplot2)
p <- ggplot(mtcars, aes(factor(cyl), mpg)) +
geom_boxplot() +
facet_grid(.~gear)
g <- ggplotGrob(p)
g
#TableGrob (7 x 9) "layout": 14 grobs
# z cells name grob
#1 0 (1-7,1-9) background rect[plot.background.rect.1216]
#2 1 (3-3,4-4) strip-top absoluteGrob[strip.absoluteGrob.1160]
#3 2 (3-3,6-6) strip-top absoluteGrob[strip.absoluteGrob.1166]
#4 3 (3-3,8-8) strip-top absoluteGrob[strip.absoluteGrob.1172]
#5 7 (4-4,3-3) axis-l absoluteGrob[GRID.absoluteGrob.1154]
#6 4 (4-4,4-4) panel gTree[GRID.gTree.1184]
#7 5 (4-4,6-6) panel gTree[GRID.gTree.1196]
#8 6 (4-4,8-8) panel gTree[GRID.gTree.1208]
#9 8 (5-5,4-4) axis-b absoluteGrob[GRID.absoluteGrob.1136]
#10 9 (5-5,6-6) axis-b absoluteGrob[GRID.absoluteGrob.1142]
#11 10 (5-5,8-8) axis-b absoluteGrob[GRID.absoluteGrob.1148]
#12 11 (6-6,4-8) xlab text[axis.title.x.text.1210]
#13 12 (4-4,2-2) ylab text[axis.title.y.text.1212]
#14 13 (2-2,4-8) title text[plot.title.text.1214]
我们希望在面板上工作,因此元素为6,7,8。使用str
我们可以找到需要更改的内容:
str(g$grobs[[6]], 4)
#List of 5
# $ name : chr "GRID.gTree.1184"
# $ gp : NULL
# $ vp : NULL
# $ children :List of 3
# ..$ grill.gTree.1183 :List of 5
# .. ..$ name : chr "grill.gTree.1183"
# .. ..$ gp : NULL
# .. ..$ vp : NULL
# .. ..$ children :List of 4
# .. .. ..$ panel.background.rect.1176 :List of 10
# .. .. .. ..- attr(*, "class")= chr [1:3] "rect" "grob" "gDesc"
#<snip>
str(g$grobs[[6]]$children[[1]]$children[[1]], 2)
#output omitted here
g$grobs[[6]]$children[[1]]$children[[1]]$gp$fill <- "blue"
g$grobs[[7]]$children[[1]]$children[[1]]$gp$fill <- "red"
g$grobs[[8]]$children[[1]]$children[[1]]$gp$fill <- "green"
plot(g)