在兩列 facet_wrap 圖形中,為了有一個緊湊的情節,在左列的左側和右側的列中,將小平面的名稱和軸放在一起會更方便和更好。緊靠在一起。
ggplot(economics_long, aes(date, value))
geom_line()
labs(y="")
facet_wrap(~variable, scales = "free_y", ncol = 2, strip.position = "left")
theme(strip.background = element_blank(), strip.placement = "outside")


uj5u.com熱心網友回復:
據我所知,在 vanilla ggplot2 中沒有辦法做到這一點。如果您對 gtables 感到滿意,您可能會發現以下可行。
library(ggplot2)
# Base plot
p <- ggplot(economics_long, aes(date, value))
geom_line()
labs(y="")
theme(strip.background = element_blank(), strip.placement = "outside")
# Left aligned strips/axes
left <- p
facet_wrap(~variable, scales = "free_y", ncol = 2, strip.position = "left")
# Right aligned strips/axes
right <- p
facet_wrap(~variable, scales = "free_y", ncol = 2, strip.position = "right")
scale_y_continuous(position = "right")
# Convert to gtables
left <- ggplotGrob(left)
right <- ggplotGrob(right)
# Combine parts of left and right
# Column numbers found by browsing through layout
gt <- cbind(left[, 1:7], right[, 9:ncol(right)])
# Render
grid::grid.newpage(); grid::grid.draw(gt)

由reprex 包(v2.0.1)于 2021 年 10 月 20 日創建
要以編程方式找到面板位置而不是手動判斷表格布局,我最好的猜測是這樣做:
panels_left <- panel_cols(left)$l
panels_right <- panel_cols(right)$l
# The -2 is to include the left axis space (zero width because of absence)
# and the panel spacing
gt <- cbind(left[, 1:panels_left[1]],
right[, (panels_right[2]-2):ncol(right)])
grid::grid.newpage(); grid::grid.draw(gt)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/329915.html
