如何为已设置列网格的facet_grid()添加多行分面?
ggplot分面布局调整:替换facet_grid为facet_wrap实现指定行数
问题背景
给定如下R数据集:
set.seed(7736) categories <- rep(LETTERS[1:11], each = 30) values <- sample(50:200, 330, replace = T) df <- data.frame(category = categories, values = values)
使用以下函数绘制分面图表:
graph_builder <- function(data_set, y_axis_parameter, category, attribute_name) { data_set <- data_set |> mutate(x = row_number(), .by = {{ category }}) graph <- ggplot(data_set, aes( x = x, y = {{ y_axis_parameter }}, colour = {{ category }}, group = 1 )) + geom_line() + geom_point() + facet_grid(cols = vars({{ category }}), scales = "free_x") + ylab(paste0(attribute_name, " Measured Values")) + xlab("Data Points") + labs(title = paste0(attribute_name)) + theme(plot.title = element_text(hjust = 0.5)) + theme(legend.position = "none") graph }
当前图表将11个category全部显示在同一行,尝试向facet_grid()传入nrows=2时触发错误:行数必须为NULL,需要实现将分面拆分为2行或3行的布局。
解决方案
facet_grid()的设计逻辑是基于行列变量的交叉分面,无法直接指定行数/列数——它要求行列参数必须对应数据中的变量,因此不能使用nrows或ncols参数。要实现自动按指定行数/列数换行的分面,需要替换为**facet_wrap()**。
facet_wrap()专门用于将单个变量的水平拆分为多行多列的布局,支持通过nrow或ncol参数指定行数/列数,自动调整每个行/列的分面数量:
- 设置
nrow=2时,11个category会自动分成6个+5个的两行布局 - 设置
nrow=3时,会分成4个+4个+3个的三行布局
修改后的graph_builder函数如下:
graph_builder <- function(data_set, y_axis_parameter, category, attribute_name) { data_set <- data_set |> mutate(x = row_number(), .by = {{ category }}) graph <- ggplot(data_set, aes( x = x, y = {{ y_axis_parameter }}, colour = {{ category }}, group = 1 )) + geom_line() + geom_point() + # 替换facet_grid为facet_wrap,指定行数 facet_wrap(vars({{ category }}), nrow = 2, scales = "free_x") + ylab(paste0(attribute_name, " Measured Values")) + xlab("Data Points") + labs(title = paste0(attribute_name)) + theme(plot.title = element_text(hjust = 0.5)) + theme(legend.position = "none") graph }
如果需要3行布局,只需将nrow = 2改为nrow = 3即可。
内容的提问来源于stack exchange,提问作者Joe the Second
相关产品推荐
相关产品推荐

