简体   繁体   English

更改 facet_wrap() 条带位置以将 facet 条带放置在 plot 内

[英]Change facet_wrap() strip positions to place facet strips inside plot

How can I change the facet_wrap() strip position as it has shown in below picture?如何更改facet_wrap() strip position 如下图所示?
The data frames is from this question.数据框来自这个问题。
enter image description here在此处输入图像描述

One option to achieve your desired result would be via the gggrid package. Similar to ggplot2::annotation_custom it allows to add grobs to a ggplot but offers much more flexibility, eg you could place different grobs to each facet panel.实现所需结果的一种选择是通过gggrid package。与ggplot2::annotation_custom类似,它允许将 grob 添加到 ggplot,但提供了更大的灵活性,例如,您可以将不同的 grob 放置到每个方面面板。 Moreover it allows to access the data and coords objects created by ggplot2 under the hood and allows to pass additional aesthetics.此外,它允许在后台访问由 ggplot2 创建的datacoords对象,并允许传递额外的美学。

Basically it requires a function which creates the grob which are then added to the ggplot via gggrid::grid_panel .基本上它需要一个 function 来创建 grob,然后通过gggrid::grid_panel For the grob I use gridtext::richtext_grob which makes it easy to add a strip text like text box to each panel.对于 grob,我使用gridtext::richtext_grob ,它可以很容易地向每个面板添加像文本框这样的条形文本。

library(ggplot2)
library(gggrid)
#> Loading required package: grid
library(gridtext)

set.seed(123)

ID <- rep(c("ABC123", "DEF456", "GHI789", "JKL012"), each = 10)
Vref <- c((runif(10, 1, 2)), (runif(10, 3, 5)), (runif(10, 6, 9)), (runif(10, 0, 2)))
Time <- rep(c(1:10), 4)
df <- data.frame(ID, Vref, Time)

tg <- function(data, coords) {
  y_label <- max(coords$y) 
  gridtext::richtext_grob(data$label[which.max(coords$y)],
    x = unit(0, "npc")  + unit(.045, "npc"),
    y = unit(y_label, "npc") + unit(2, "mm"),
    hjust = 0,
    vjust = 0,
    valign = .5,
    padding = unit(rep(4.4, 4), "pt"),
    gp = grid::gpar(fontsize = 8, fill = "grey85"),
    box_gp = grid::gpar(col = "grey85")
  )
}

ggplot(df, aes(x = Time, y = Vref)) +
  geom_col() +
  scale_y_continuous(expand = expansion(mult = c(.05, .2))) +
  facet_wrap(~ID, nrow = 2) +
  gggrid::grid_panel(mapping = aes(label = ID), tg) +
  theme(strip.text = element_blank())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM