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标签,所以我切换到facet_wrap
,并且丢失了space
参数(facets具有相同的宽度):
ggplot(df, aes(x = value, y = item)) +
geom_point() +
facet_wrap(~ label, scales = "free_y", ncol = 1) +
ylab("")
是否有可能获得两全其美?
提前感谢您的帮助。
答案 0 :(得分:3)
我不知道如何在ggplot
中执行此操作,但您可以使用latticeExtra
使用ggplot
oid样式实现类似的布局:
library(latticeExtra)
df$label <- factor(df$label, levels = unique(df$label))
dotplot(item ~ value | label, data = df,
layout = c(1, 3),
as.table = TRUE,
scales = list(y = list(relation = "free")),
par.settings = ggplot2like())
resizePanels()
答案 1 :(得分:3)
可以手动完成。所需图中三个面板的高度比约为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
的{{1}}个数设置它们。并借用@baptiste's answer here中的一些代码来从与面板对应的布局中选择项目:
df
答案 2 :(得分:3)
我认为该功能不存在,或计划在ggplot2
(see here for the closed issue discussing this feature)中实现
但是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))
由reprex package(v0.3.0)于2020-06-28创建