R ggplot在多个层面上进行分面绘制

R ggplot在多个层面上进行分面绘制,r,ggplot2,R,Ggplot2,我使用刻面网格根据分类变量(刻面的4个级别)划分散点图 请有人演示如何标记每个面板(例如,a=1),以使绘图具有自信息性 建议进一步改进,以提高其可出版质量 我附上了一个样本代码 library(tidyverse) # continuous variables x <- runif(160) y <- runif(160) # categorical variables a <- c(rep(0, 80), rep(1, 80)) b <- c(rep(0, 40)

我使用刻面网格根据分类变量(刻面的4个级别)划分散点图

  • 请有人演示如何标记每个面板(例如,
    a=1
    ),以使绘图具有自信息性
  • 建议进一步改进,以提高其可出版质量
  • 我附上了一个样本代码

    library(tidyverse)
    
    # continuous variables
    x <- runif(160)
    y <- runif(160)
    
    # categorical variables
    a <- c(rep(0, 80), rep(1, 80))
    b <- c(rep(0, 40), rep(1, 40), rep(0, 40), rep(1, 40))
    c <- c(rep(0, 20), rep(1, 20), rep(0, 20), rep(1, 20), 
           rep(0, 20), rep(1, 20), rep(0, 20), rep(1, 20))
    d <- c(rep(0, 10), rep(1, 10), rep(0, 10), rep(1, 10),
           rep(0, 10), rep(1, 10), rep(0, 10), rep(1, 10),
           rep(0, 10), rep(1, 10), rep(0, 10), rep(1, 10),
           rep(0, 10), rep(1, 10), rep(0, 10), rep(1, 10))
    
    # tibble
    tbl <- tibble(x, y, a, b, c, d)
    
    # ggplot
    ggplot(data = tbl,
           aes(x = x,
               y = y)) + 
      geom_point() + 
      facet_grid(a + d ~ b + c) +
      theme_bw() +
      theme(aspect.ratio = 1)
    
    库(tidyverse)
    #连续变量
    
    x这里有一个解决方案,它具有
    交互
    ,然后是

    tbl %>%
      mutate(A = interaction(a, d, sep = "_"),
             B = interaction(b, c, sep = "_"),
             A = sub("(.)_", "a = \\1, d = ", A),
             B = sub("(.)_", "b = \\1, c = ", B)) %>%
      # ggplot
      ggplot(
        aes(x = x,
            y = y)) + 
      geom_point() + 
      facet_grid(A ~ B) +
      theme_bw() +
      theme(aspect.ratio = 1,
            axis.text.x = element_text(angle =60, vjust = 1, hjust=1))
    

    这里有一个解决方案,它具有
    交互
    ,然后是

    tbl %>%
      mutate(A = interaction(a, d, sep = "_"),
             B = interaction(b, c, sep = "_"),
             A = sub("(.)_", "a = \\1, d = ", A),
             B = sub("(.)_", "b = \\1, c = ", B)) %>%
      # ggplot
      ggplot(
        aes(x = x,
            y = y)) + 
      geom_point() + 
      facet_grid(A ~ B) +
      theme_bw() +
      theme(aspect.ratio = 1,
            axis.text.x = element_text(angle =60, vjust = 1, hjust=1))
    

    另一个选项是
    glue
    tbl%>%mutate(A=glue('A={A},d={d}'),B=glue('B={B},c={c}'))
    另一个选项是
    glue
    tbl%>%mutate(A=glue('A={A},d={d}'),B=glue('B={B},c}'))