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
每个label
在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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句