[英]'Labels on top' with facet_grid, or 'space option' with facet_wrap
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
参数(facet 具有相同的宽度):
ggplot(df, aes(x = value, y = item)) +
geom_point() +
facet_wrap(~ label, scales = "free_y", ncol = 1) +
ylab("")
是否有可能获得两全其美?
预先感谢您的帮助。
它可以手动完成。 所需图中三个面板的高度比约为 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)
或者,可以将高度设置为与原始图中的高度相同:
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)
或者,可以在不参考原始图的情况下设置高度。 它们可以根据df
每个label
的items
数进行设置。 并从@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)
我认为此功能不存在或计划在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))
由reprex 包(v0.3.0) 于 2020 年 6 月 28 日创建
我不知道该怎么做,在ggplot
,但你可以实现类似的布局与ggplot
使用OID风格latticeExtra
:
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.