代码之家  ›  专栏  ›  技术社区  ›  Krisselack

R ggplot2两级镶嵌面环绕

  •  0
  • Krisselack  · 技术社区  · 7 年前

    我想用facet\u wrap编辑ggplot图形的facet标签,如下所示:

    1. 我只想在左边写第一、第二和第三行,每行只写一次。

    这样的事可能吗?

    或者,我尝试使用grid arrange,但是“纯”ggplot图形看起来更好,而且代码更易于操作(每行的复制和粘贴更少)。我也遇到了问题,行高与网格安排(一些阴谋上帝切断)。

    例子:

    Anames <- list(
      '1'="FIRST",
      '2'="SECOND",
      '3'="THIRD")
    
    Bnames <- list(
      'A'="ALPHA",
      'B'="BETA")
    
    plot_labeller <- function(variable,value){
    
    # http://www.sthda.com/english/wiki/print.php?id=175
    
      if (variable=='variable') {
        return(Anames[value])
      } else {
        return(Bnames[value])
      }
    }
    
    tdat <- data.frame("variable" = c(rep(seq(1,3),10)), # Group Factor 1 
                       "B" = c(rep(seq(1,2),15)), # Group Factor 2
                       "time" = c(1:30),
                       "value" = sample(1:100,30))
    tdat$B <- ifelse(tdat$B==1,"A","B")
    
    library(ggplot2)
    ggplot(data=tdat, aes(x=time,y=value)) +
      geom_bar(stat="identity")+
      facet_wrap(~variable+B,
                 labeller=plot_labeller,
                 ncol=2,scales="free_y")
    
    2 回复  |  直到 7 年前
        1
  •  3
  •   C. Braun    7 年前

    对于比较两种类型的变量,它通常更容易使用 facet_grid

    ggplot(data=tdat, aes(x=time,y=value)) +
        geom_bar(stat="identity")+
        facet_grid(rows = vars(variable), cols = vars(B), 
                   labeller = plot_labeller, scales="free_y", switch = 'y')
    

    enter image description here

        2
  •  2
  •   csgroen    7 年前

    你可以用 facet_grid switch 设置为“y”以在左侧打印标签。

    ggplot(data=tdat, aes(x=time,y=value)) +
        geom_bar(stat="identity")+
        facet_grid(variable ~ B,
                   labeller=plot_labeller,
                   scales="free_y",
                   switch = "y")