facet_grid允许我根据y轴上的项目数量(space参数)调整每个构面宽度的大小:
df <- data.frame(label = c("Variable one", rep("Variable two", 2), rep("Variable three", 3)), item = c("A", "B", "C", "D", "E", "F"), value = rnorm(6))
ggplot(df, aes(x = value, y = item)) +
geom_point() +
facet_grid(label ~ ., scales = "free_y", space = "free_y") +
ylab("") +
theme(strip.text.y = element_text(angle=0))
Run Code Online (Sandbox Code Playgroud)

但是我想在顶部标注facet标签,所以我切换到facet_wrap,并且丢失了space参数(facets具有相同的宽度):
ggplot(df, aes(x = value, y = item)) +
geom_point() +
facet_wrap(~ label, scales = "free_y", ncol = 1) +
ylab("")
Run Code Online (Sandbox Code Playgroud)

是否有可能获得两全其美?
预先感谢您的帮助.
它可以手动完成。所需图中三个面板的高度比约为 1:3:2。三个面板的高度可以通过改变grob来调整:
library(ggplot2)
library(grid)
df <- data.frame(label = c("Variable one", rep("Variable two", 2), rep("Variable three", 3)), item = c("A", "B", "C", "D", "E", "F"), value = rnorm(6))
p1 = ggplot(df, aes(x = value, y = item)) +
geom_point() +
facet_wrap(~ label, scales = "free_y", ncol = 1) +
ylab("")
g1 = ggplotGrob(p1)
g1$heights[[7]] = unit(1, "null")
g1$heights[[12]] = unit(3, "null")
g1$heights[[17]] = unit(2, "null")
grid.newpage()
grid.draw(g1)
Run Code Online (Sandbox Code Playgroud)
或者,可以将高度设置为与原始图中的高度相同:
p2 = ggplot(df, aes(x = value, y = item)) +
geom_point() +
facet_grid(label ~ ., scales = "free_y", space = "free_y") +
ylab("") +
theme(strip.text.y = element_text(angle=0))
g2 = ggplotGrob(p2)
g1$heights[[7]] = g2$heights[[6]]
g1$heights[[12]] = g2$heights[[8]]
g1$heights[[17]] = g2$heights[[10]]
grid.newpage()
grid.draw(g1)
Run Code Online (Sandbox Code Playgroud)
或者,可以在不参考原始图的情况下设置高度。它们可以根据items每个labelin的数量进行设置df。并从@baptiste 的回答中借用一些代码,从与面板对应的布局中选择项目:
# From 'df', get the number of 'items' for each 'label'.
# That is, the number y-breaks in each panel.
library(plyr)
N = dlply(df, .(label), function(x) length(row.names(x)))
# Get the items in the g1 layout corresponding to the panels.
panels1 <- g1$layout$t[grepl("panel", g1$layout$name)]
# Replace the default panel heights with relative heights
g1$heights[panels1] <- unit(N, "null")
## Draw g1
grid.newpage()
grid.draw(g1)
Run Code Online (Sandbox Code Playgroud)

我认为此功能不存在或计划在ggplot2(有关讨论此功能的已关闭问题请参见此处)中实施
但是,该ggforce软件包支持您正在寻找的内容
library(ggplot2)
library(ggforce)
df <- data.frame(label = c("Variable one", rep("Variable two", 2), rep("Variable three", 3)), item = c("A", "B", "C", "D", "E", "F"), value = rnorm(6))
ggplot(df, aes(x = value, y = item)) +
geom_point() +
ggforce::facet_col(facets = vars(label),
scales = "free_y",
space = "free") +
ylab("") +
theme(strip.text.y = element_text(angle=0))
Run Code Online (Sandbox Code Playgroud)

由reprex 包(v0.3.0)于 2020 年 6 月 28 日创建
| 归档时间: |
|
| 查看次数: |
1643 次 |
| 最近记录: |