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

dva*_*nic 4 r ggplot2

有没有办法对ggplot2 的facet_grid 中的facet 的名称或条形背景进行着色(不是实际网格的背景,正如这篇文章中所回答的: 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
Run Code Online (Sandbox Code Playgroud)

有没有办法根据分类变量(例如,我在上面指定的数据框中的“类别”,因此所有控件都有一个红色条,所有的 exp - 一个绿色条)?

提前致谢!

PS我实际上想做的是展示生物实验的结果:

  • 每个基因的两个箱线图以显示变异性;基因名称在条带中

  • 网格的背景是白色或灰色,灰色显示作为对照的基因

  • 我想使用标题中文本的颜色来表示该基因在我的实验中是否重要(我需要在同一图中显示经过验证的基因和未经验证的基因)

Sim*_*lon 5

grid@Roland 教我在这个问题上使用图形对象:

使用他的建议,您可以(粗俗地)遍历复杂的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 )
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述