ggplot2-如何向多个图添加标签? [英] ggplot2 - How to add labels to multiple plots figure?

查看:963
本文介绍了ggplot2-如何向多个图添加标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用cowplot在以下多个图上添加一个x标签和一个y标签:

I need to add one x label and one y label to the following multiple plots figure using 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)))

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

The x label should be at the bottom and the y label on the left.

有什么快速的方法可以做到这一点吗? 谢谢

Is there any quick way of doing this? Thanks

推荐答案

如果您不需要使用cowplot(它解决的大多数缺陷现在是ggplot2的一部分) ,这是一个解决方案:

If you do not need to use cowplot (most of the deficiencies it addressed are now a part of ggplot2), here is a solution:

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))

这篇关于ggplot2-如何向多个图添加标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆