'facet_grid上面的'标签',或者带有facet_wrap的'空格选项'

时间:2015-01-22 16:08:27

标签: r ggplot2 facet

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

enter image description here

但是我想在上面加上facet标签,所以我切换到facet_wrap,并且丢失了space参数(facets具有相同的宽度):

ggplot(df, aes(x = value, y = item)) + 
geom_point() + 
facet_wrap(~ label, scales = "free_y", ncol = 1) + 
ylab("")

enter image description here

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

提前感谢您的帮助。

3 个答案:

答案 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()

enter image description here

答案 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

enter image description here

答案 2 :(得分:3)

我认为该功能不存在,或计划在ggplot2see 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创建