3

我有我正在使用ggplot's绘制的数据facet_grid

我的数据:

species <- c("spcies1","species2")
conditions <- c("cond1","cond2","cond3")
batches <- 1:6

df <- expand.grid(species=species,condition=conditions,batch=batches)

set.seed(1)
df$y <- rnorm(nrow(df))
df$replicate <- 1
df$col.fill <- paste(df$species,df$condition,df$batch,sep=".")

我的情节:

integerBreaks <- function(n = 5, ...)
{
  library(scales)
  breaker <- pretty_breaks(n, ...)
  function(x){
    breaks <- breaker(x)
    breaks[breaks == floor(breaks)]
  }
}

library(ggplot2)
p <- ggplot(df,aes(x=replicate,y=y,color=col.fill))+
  geom_point(size=3)+facet_grid(~col.fill,scales="free_x")+
  scale_x_continuous(breaks=integerBreaks())+
  theme_minimal()+theme(legend.position="none",axis.title=element_text(size=8))

这使: 在此处输入图像描述

显然标签很长并且在图中很乱,所以我想知道是否有办法在ggplot对象(p)或gtable///对象gTree()中编辑这些标签grobgDescggplotGrob(p)

我知道获得更好标签的一种方法是在创建对象labeller function时使用,ggplot但在我的情况下,我专门寻找一种在ggplot创建对象后编辑构面标签的方法。

4

1 回答 1

4

正如我在评论中提到的,构面名称深深地嵌套在给你的gtable那个中。ggplotGrob()但是,这仍然是可能的,因为 OP 明确希望在绘制后编辑它们,您可以这样做:

library(grid)
gg <- ggplotGrob(p)

edited_grobs <- mapply(FUN = function(x, y) {
                                  x[["grobs"]][[1]][["children"]][[2]][["children"]][[1]][["label"]] <- y
                                  return(x)
                              },
                        gg$grobs[which(grepl("strip-t",gg$layout$name))],
                        unique(gsub("cond","c", df$condition)),
                        SIMPLIFY = FALSE)

gg$grobs[which(grepl("strip-t",gg$layout$name))] <- edited_grobs
grid.draw(gg)

在此处输入图像描述

请注意,这会提取所有使用的条带gg$grobs[which(grepl("strip-t",gg$layout$name))]并将它们传递给要使用其注释中指定的 OPmapply进行重置。gsub(...)

通常,如果您只想访问其中一个文本标签,我在我的 中使用了一个非常相似的结构mapply

num_to_access <- 1
gg$grobs[which(grepl("strip-t",gg$layout$name))][[num_to_access]][["grobs"]][[1]][["children"]][[2]][["children"]][[1]]$label

因此,例如,要访问第 4 个标签,您需要做的就是更改num_to_acces为 4。希望这会有所帮助!

于 2017-10-01T20:26:22.360 回答