[英]'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.