首页 > 解决方案 > 如何将类似样式的标签添加到 facet_grid

问题描述

这一定是一个简单的解决方案,但我无法理解它。我有两种方法“阶段”(1,2,3)和“状态”(pos,neg)和因素性别(女性,男性)。我为每种方法生成两个 box_plots,然后使用 ggarrange 组合这两个图。

首先,我想将每个图分别标记为“状态”和“阶段”。

我尝试使用 facet_grid 单独标记每个图,但它会拆分数据。

请找到附加虚拟数据来说明我的问题。

非常感谢您考虑我的要求。

library(ggplot2)


size<-runif(12, min=20, max=40)
stage<-sample(0:3, 12, replace=TRUE)
status<-sample(x = c("pos", "neg"),size = 12, replace = TRUE) 
sex<-sample(x = c("Female", "Male"),size = 12, replace = TRUE) 
    
df <- data.frame(sex,stage,status,size)

#######Graph A##################
graph_A <- ggplot(df, aes(status, size, fill=sex)) + 
  geom_boxplot()
 # facet_grid(rows = vars(status), scales = "free")

#######Graph B##################
graph_B <- ggplot(df, aes(stage, size, fill=sex)) + 
  geom_boxplot()

#facet_grid(rows = vars(status), scales = "free")
graph_B

#######Graph A&B##################
figure_AB<-ggarrange(graph_A, graph_B, ncol=1, nrow=2, 
                    labels=c("a", "b"), 
                    common.legend = TRUE, legend = "top")
figure_AB

[我想重新创建这种标签} 1

标签: rggplot2facetfacet-wrap

解决方案


尝试以下添加“标题”

size<-runif(12, min=20, max=40)
stage<-sample(0:3, 12, replace=TRUE)
status<-sample(x = c("pos", "neg"),size = 12, replace = TRUE) 
sex<-sample(x = c("Female", "Male"),size = 12, replace = TRUE) 

df <- data.frame(sex,stage,status,size)

#######Graph A##################
graph_A <- ggplot(df, aes(status, size, fill=sex)) + 
    geom_boxplot() +
#--------------- add a label layer, i.e. title here
    labs(title = "status method")

#######Graph B##################
graph_B <- ggplot(df, aes(stage, size, fill=sex)) + 
    geom_boxplot() +
    labs(title = "stage method")

#facet_grid(rows = vars(status), scales = "free")
graph_B

#######Graph A&B##################
figure_AB <- ggpubr::ggarrange(graph_A, graph_B, ncol=1, nrow=2, 
                     labels=c("a", "b"), 
                     common.legend = TRUE, legend = "top")
figure_AB

在此处输入图像描述


推荐阅读