[英]How to plot boxplots with different background using face_grid in ggplot2?
我有一系列針對不同情況的箱線圖(對照vs病人)。 我想根據條件中值(對照)>中值(患者)為箱圖(而不是箱圖的填充)提供不同的背景顏色。 我正在使用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。
我喜歡把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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.