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

但是我想将刻面标签放在顶部,因此我切换到facet_wrap,并且丢失了space参数(刻面具有相同的宽度):
ggplot(df, aes(x = value, y = item)) +
geom_point() +
facet_wrap(~ label, scales = "free_y", ncol = 1) +
ylab("")

是否有可能获得两全其美?

预先感谢您的帮助。

最佳答案

可以手动完成。所需图中三个面板的高度之比约为1:3:2。可以通过更改大小来调整三个面板的高度:

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)

或者,可以将高度设置为与原始图中的高度相同:
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)

或者,可以在不引用原始图的情况下设置高度。可以根据items中每个labeldf数目来设置它们。并从@baptiste's answer here借用一些代码以从与面板相对应的布局中选择项目:
# 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)

10-08 15:49