将两个边距添加到 facet_grid 但不是组合
Add both margins to facet_grid but not the combination
我想同时显示右侧和底部边距,但不想同时显示两者。 facet_grid 这可能吗?
library(ggplot2)
ggplot(mtcars, aes(x = hp, group = vs)) +
geom_density() +
facet_grid(am ~ vs, switch = "y", margins = TRUE)
我试图通过手动向 margin
参数提供因数来修复它,但这没有帮助。此外,R 文档对我没有帮助。
当前结果
期望的结果
这样的事情对我来说是一个错误,因为我没有看到更大的图片 gt
中的条目如何与最终形式相关:
library(ggplot2)
p<-
ggplot(mtcars, aes(x = hp, group = vs)) +
geom_density() +
facet_grid(am ~ vs, switch = "y", margins = TRUE)
gt = ggplotGrob(p)
keep <- !grepl("[3br]-3$",gt$layout$name)
gt$layout <- gt$layout[keep,]
gt$grobs <- gt$grobs[keep]
plot(gt)
ggplot2 使用固定习语来命名关键绘图元素,因此我们可以使用该确定性条件来查找元素:
library(ggplot2)
ggplot(mtcars, aes(x = hp, group = vs)) +
geom_density() +
facet_grid(am ~ vs, switch = "y", margins = TRUE) -> gg
将绘图构建到 gtable
对象中:
gt <- ggplot_gtable(ggplot_build(gg))
获取 table 个单元格名称:
cells <- gt$layout$name
找出哪个是底角面板和轴:
apply(
apply(
do.call(rbind, strsplit(grep("panel", cells, value=TRUE), "-"))[,2:3],
2, as.integer),
2, max
) -> max_col_row
bottom_right_panel <- paste0(c("panel", max_col_row), collapse="-")
bottom_axis <- sprintf("axis-b-%s", max_col_row[2])
找出哪些不是底角面板:
paste0(
grep(sprintf("^%s|%s$", bottom_corner, bottom_axis), cells, value=TRUE, invert = TRUE),
collapse = "|"
) -> not_bottom_corner_panel
只画那些:
grid::grid.draw(
gtable::gtable_filter(gt, sprintf("^(%s)$", not_bottom_corner_panel))
)
我想同时显示右侧和底部边距,但不想同时显示两者。 facet_grid 这可能吗?
library(ggplot2)
ggplot(mtcars, aes(x = hp, group = vs)) +
geom_density() +
facet_grid(am ~ vs, switch = "y", margins = TRUE)
我试图通过手动向 margin
参数提供因数来修复它,但这没有帮助。此外,R 文档对我没有帮助。
当前结果
期望的结果
这样的事情对我来说是一个错误,因为我没有看到更大的图片 gt
中的条目如何与最终形式相关:
library(ggplot2)
p<-
ggplot(mtcars, aes(x = hp, group = vs)) +
geom_density() +
facet_grid(am ~ vs, switch = "y", margins = TRUE)
gt = ggplotGrob(p)
keep <- !grepl("[3br]-3$",gt$layout$name)
gt$layout <- gt$layout[keep,]
gt$grobs <- gt$grobs[keep]
plot(gt)
ggplot2 使用固定习语来命名关键绘图元素,因此我们可以使用该确定性条件来查找元素:
library(ggplot2)
ggplot(mtcars, aes(x = hp, group = vs)) +
geom_density() +
facet_grid(am ~ vs, switch = "y", margins = TRUE) -> gg
将绘图构建到 gtable
对象中:
gt <- ggplot_gtable(ggplot_build(gg))
获取 table 个单元格名称:
cells <- gt$layout$name
找出哪个是底角面板和轴:
apply(
apply(
do.call(rbind, strsplit(grep("panel", cells, value=TRUE), "-"))[,2:3],
2, as.integer),
2, max
) -> max_col_row
bottom_right_panel <- paste0(c("panel", max_col_row), collapse="-")
bottom_axis <- sprintf("axis-b-%s", max_col_row[2])
找出哪些不是底角面板:
paste0(
grep(sprintf("^%s|%s$", bottom_corner, bottom_axis), cells, value=TRUE, invert = TRUE),
collapse = "|"
) -> not_bottom_corner_panel
只画那些:
grid::grid.draw(
gtable::gtable_filter(gt, sprintf("^(%s)$", not_bottom_corner_panel))
)