1

code of plot:

library(tidyverse)

mtcars %>% 
  ggplot(aes(factor(cyl), disp)) +
  geom_col() +
  facet_grid(. ~ gear, switch = "x") +
  theme(
    strip.placement = "outside",
    strip.background = element_rect(fill = "white", color = "red")
  )

enter image description here

I'm trying to modify the color of certain borders: Expected output:

enter image description here

I tried to change it using grobs but it seems that specific borders cannot be changed.

p <- mtcars %>% 
  ggplot(aes(factor(cyl), disp)) +
  geom_col() +
  facet_grid(. ~ gear, switch = "x") +
  theme(
    strip.placement = "outside",
    strip.background = element_rect(fill = "white", color = "red")
  )

g <- ggplotGrob(p)
g$grobs[[13]]$grobs[[1]]$children$strip.background.x..rect.33641$gp$col
Alvaro Morales
  • 1,845
  • 3
  • 12
  • 21

1 Answers1

1

Based on this answer, you can change the border with linesGrob. In your case you will need polylineGrob because you need two unconnected lines (one on each side of the grids).

Code

p <- mtcars %>% 
  ggplot(aes(factor(cyl), disp)) +
  geom_col() +
  facet_grid(. ~ gear, switch = "x") +
  theme(
    strip.placement = "outside",
    strip.background = element_rect(color = NA)
  )

library(grid)
q <- ggplotGrob(p)

lr2 <-  polylineGrob(x=c(0,0,1,1),
                      y=c(0,1,0,1),
                      id=c(1,1,2,2),
                      gp=gpar(col="blue", lwd=3))

for (k in grep("strip-b",q$layout$name)) {
  q$grobs[[k]]$grobs[[1]]$children[[1]] <- lr2
}

grid.draw(q)

Plot

enter image description here

tamtam
  • 3,541
  • 1
  • 7
  • 21