Jeff238
Jeff238

Reputation: 428

Add only one panel border line between facets in ggplot

For the following sample df

df = data.frame(x = c(2,3,4),y = c(4,5,6),group.a= c("1","1","2"),group.b = c("a","b","b"))

I want to just add a horizontal line in-between the y axis facet grids and after browsing different posts here I have tried using the panel.border = element_rect() argument however that gives me all four borders (top, right, bottom, left)

ggplot(df,aes(x=x,y=y)) + facet_grid(group.a~group.b) + theme_minimal() +
    theme(legend.position = "bottom",
          legend.title = element_blank(),
          legend.direction = "horizontal",
          legend.margin = margin(-20,0,0,0),
          panel.grid = element_blank(),
          panel.border = element_rect(color = "black", fill = NA, size = .5)
          axis.text.x = element_blank(),
          axis.line.y = element_line(size = .5),
          axis.line.x = element_line(size = .5),
          strip.placement = "outside")

enter image description here

Is there a way to just have the bottom and left border of the panel borders? Thanks!

Upvotes: 1

Views: 1248

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 174536

There aren't any theme elements that fit the bill here; you would need custom annotations. Fortunately, annotation_custom applies to each panel, so this can be done with a couple of lines of code

library(ggplot2)

df = data.frame(x = c(2,3,4),y = c(4,5,6),
                group.a= c("1","1","2"),group.b = c("a","b","b"))

ggplot(df,aes(x=x,y=y)) + 
  facet_grid(group.a~group.b) + 
  geom_point(col = "white") +
  theme_minimal() +
  annotation_custom(grid::linesGrob(y = c(0, 0), gp = grid::gpar(lwd = 3))) +
  annotation_custom(grid::linesGrob(x = c(0, 0), gp = grid::gpar(lwd = 3))) +
  theme(panel.grid = element_blank(),
        strip.placement = "outside",
        axis.text.x = element_blank())

enter image description here

Upvotes: 5

Related Questions