ggplot2 facet_grid()strip_text_x()基于因子的不同颜色

时间:2014-03-17 15:10:14

标签: r ggplot2

有没有办法为ggplot2的facet_grid中的方面着色名称或剥离背景(不是实际网格的背景,如本文所述:Conditionally change panel background with facet_grid?)?

在以下示例中:

#create simple dataframe for plotting
xy <- data.frame(x = rep(1:10, times=3), y = rep(10:1, times=3), type = rep(LETTERS[1:2], each=5), type2 = rep(LETTERS[3:5], each=10), category = rep(c("control", "exp", "control"), each=10))
xy
#create base plot
plot <- ggplot(data = xy)+
geom_point(aes(x = x, y = y))+
facet_grid(type ~ type2)

#plot base plot   
plot

是否有办法为主题的文本或背景(strip.text.x = element_text(size = 11,face =“bold”))(?strip.background.x?)着色,具体取决于分类变量(例如,我在上面指定的数据框中的“类别”,所以所有的控件都有一个红色的条带,所有的exp都是绿色的?)

提前致谢!

PS 我实际上要做的是提供生物实验的结果:

  • 每个基因的两个箱图显示可变性;基因名称在条带

  • 网格的背景为白色或灰色,灰色显示作为控件的基因

  • 我想用标题中的文字颜色来表示我的实验中基因是否显着(我需要在同一个图中显示已验证和未验证的基因)

1 个答案:

答案 0 :(得分:4)

@Roland教会我使用this question上的grid图形对象进行黑客攻击:

使用他的建议,你可以( hackily )遍历复杂的grob对象并随意更改元素(但请记住ggplot有点设计用于将这些决定从非常好的理由 - 你可能会做出一些糟糕的图形设计选择!)。

尝试并弄清楚下面的工作方式,您将能够扩展它以改变其他方式 元素。对于$gp绘图,grid基本上是par等效的base选项。

gplot <- ggplotGrob( plot )
nms <- lapply( gplot$grobs , function(x) names( x[]$children ) )
grbs <- which( sapply( lapply( nms , function(x) grepl( "strip.background.rect" , x ) ) , any ) == 1 )
cl <- c("#2b8cbe","#fc9272","#2b8cbe")
for ( i in 1:length(grbs) ){
    col <- cl[i]
    i <- grbs[i]
    gplot$grobs[[i]]$children[[1]][]$gp$fill <- col

}
require(gridExtra)
grid.arrange( gplot )

enter image description here

相关问题