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

ggplot2-如何将标签添加到多个图中?

  •  0
  • aaaaa  · 技术社区  · 6 年前

    我需要添加一个x标签和一个y标签到下面的多个图使用 cowplot

    library(ggplot2
    set.seed(99)
    
    x_1 = data.frame(z = rnorm(100))
    x_2 = data.frame(z = rnorm(100))
    x_3 = data.frame(z = rnorm(100))
    
    lst = list(x_1, x_2, x_3)
    
    lst_p = list()
    
    for (i in 1:length(lst)) {
        lst_p[[i]] = ggplot(data=lst[[i]], aes(lst[[i]]$z)) + 
        geom_histogram() +
            xlab("X LAB") +
            ylab("Y LAB") 
    }
    
    p_no_labels = lapply(lst_p, function(x) x + xlab("") + ylab(""))
    
    title = cowplot::ggdraw() + cowplot::draw_label("test", size = 20)
    
    p_grid = cowplot::plot_grid(plotlist = p_no_labels, ncol = 1)
    
    print(cowplot::plot_grid(title, p_grid, 
                             ncol = 1, rel_heights = c(0.05, 1, 0.05)))
    

    enter image description here

    x标签应在底部,y标签应在左侧。

    有什么快速的方法吗? 谢谢

    1 回复  |  直到 6 年前
        1
  •  3
  •   C. Braun    6 年前

    如果你没有 需要 使用 cowplot (它解决的大多数缺陷现在都是 ggplot2 ),这里有一个解决方案:

    df <- cbind(fct = rep(c('z1', 'z2', 'z3'), each = 100),
                val = rbind(x_1, z2 = x_2, z3 = x_3))
    ggplot(df) +
        geom_histogram(aes(x = val)) +
        facet_wrap(vars(fct), nrow = 3) +
        labs(x = "X LAB", y = "Y LAB", title = "test") +
        theme(strip.background = element_blank(),
              strip.text = element_blank(),
              plot.title = element_text(hjust = 0.5))