該
在此示例中,構面行的數量是兩個,因為df$group2有兩個不同的值。對于我的實際用例,根據使用的 facet 變數可能有兩行以上;y 軸標題應該位于每個構面行的中間。
迄今為止最好的解決方案是
uj5u.com熱心網友回復:
在不使用其他包的情況下,我認為最好的方法是建立在您在原始問題中鏈接的空間解決方案的基礎上。所以我寫了一個函式來讓標簽間距更健壯一點。
ylabel <- function(label1,label2){
L1 <- nchar(label1)
L2 <- nchar(label2)
scaler <- ifelse(L1 L2 > 8, 4, 0)
space1 = paste0(rep("",27 - (L1/2)),collapse = " ")
space2 = paste0(rep("",44 - (L1/2 L2/2) - scaler), collapse = " ")
space3 = paste0(rep("",22 - (L2/2)), collapse = " ")
paste0(space1,label1,space2,label2,space3)
}
應用:
test <- ylabel("automobiles", "trucks")
ggplot(df, aes(x, y))
geom_point()
facet_grid(group1 ~ group2)
ylab(test)

仍在玩弄scaler引數,它并不完美:
test2 <- ylabel("super long label", "a")
ggplot(df, aes(x, y))
geom_point()
facet_grid(group1 ~ group2)
ylab(test2)

將繼續改進功能/引數,但我認為這會讓您接近您正在尋找的東西。
uj5u.com熱心網友回復:
您可以將軸標簽復制到 gtable 中的新 grob 中。請注意,盡管這使用了grid和gtable包,但它們已經由 匯入ggplot2,因此這不會添加任何尚不可用且由 ggplot 內部使用的新依賴項。
library(grid)
library(gtable)
g = ggplot(df, aes(x, y))
geom_point()
facet_grid(group1 ~ group2)
gt = ggplot_gtable(ggplot_build(g))
which.ylab = grep('ylab-l', gt$layout$name)
gt = gtable_add_grob(gt, gt$grobs[which.ylab], 8, 3)
gt = gtable_add_grob(gt, gt$grobs[which.ylab], 10, 3)
gt = gtable_filter(gt, 'ylab-l', invert = TRUE) # remove the original axis title
grid.draw(gt)

以上僅適用于只有兩個方面的 OP 示例。如果我們想將其推廣到任意數量的面,我們可以通過搜索 gtable 來查看哪些行包含 y 軸來簡單地做到這一點:
gt = ggplot_gtable(ggplot_build(g))
which.ylab = grep('ylab-l', gt$layout$name)
which.axes = grep('axis-l', gt$layout$name)
axis.rows = gt$layout$t[which.axes]
label.col = gt$layout$l[which.ylab]
for (row in axis.rows) {
gt = gtable_add_grob(gt, gt$grobs[which.ylab], row, label.col)
}
gt = gtable_filter(gt, 'ylab-l', invert = TRUE)
grid.draw(gt)
我們可以用另一個四行的例子來演示:
df <- data.frame(x= rnorm(100), y= rnorm(100),
group1= rep(1:4, 25), group2= rep(1:2, each= 50))

uj5u.com熱心網友回復:
這是一個帶注釋的版本,僅使用 ggplot2。它應該是可擴展的。
沒有搞亂grobs。缺點是 x 定位和繪圖邊距需要半手動定義,這可能不是很健壯。
library(ggplot2)
df <- data.frame(x= rnorm(100), y= rnorm(100),
group1= rep(0:1, 50), group2= rep(2:3, each= 50))
## convert to factor for absolute control
df$group2 <- as.factor(df$group2)
## if you define by groups in your data frame, this is scalable
## define which are the first levels for each factor,
## so you know which facets will be on the left side
y_tit <- "y"
y_df <- data.frame(group1= unique(df$group1),
group2= levels(df$group2)[1],
x = min(df$x)- abs(1/3*min(df$x)),
label = y_tit, y = mean(df$y))
ggplot(df, aes(x, y))
geom_point()
geom_text(data = y_df, aes(x, y, label = label), angle = 90)
facet_grid(group1 ~ group2)
coord_cartesian(xlim = range(df$x), clip = "off")
theme(axis.title.y = element_blank(),
plot.margin = margin(5, 5, 5, 20))

由reprex 包(v2.0.1)于 2021 年 11 月 23 日創建
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/364237.html
