In ggplot2, how can I change the border of selected facets?
Asked Answered
I

3

10

Taking the graph from ggplot2 help pages:

ggplot(mtcars, aes(factor(cyl))) + geom_bar() + facet_grid(. ~ vs)

Is it possible to change the border (colour and/or thickness) of only selected panels? I'd like to, for instance, change the border of the facet of '1' of faceting variable vs.

I tried adding

theme(panel.border = element_rect(size = 3, colour = "red", fill = NA))

but that solution changes all borders.

I was also thinking about using geom_rect or geom_polygon but am not sure how to limit it to one plot either.

I stumbled upon this thread on R help list, but the solutions didn't work for me

Any suggestions on how to move forward will be much appreciated.

Indecisive answered 21/8, 2013 at 20:55 Comment(1)
Might be also possible with solution from #6751164Indecisive
C
10

How about filling it with a colour like this?

dd <- data.frame(vs = c(0,1), ff = factor(0:1))
ggplot() + geom_rect(data=dd, aes(fill=ff), 
    xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf, alpha=0.15) + 
    geom_bar(data = mtcars, aes(factor(cyl))) + facet_grid(. ~ vs) + 
    scale_fill_manual(values=c(NA, "red"), breaks=NULL)

enter image description here

Conjunctiva answered 21/8, 2013 at 21:32 Comment(0)
G
7

I was trying to implement a facet border as well. I did just a little tweaking of the answer supplied by Hadley in the thread mentioned in the question as follows:

 # Outline colours 
outline <- data.frame( 
  cyl = c(4, 6, 8), 
  outline_color = c('green', 'orange', 'red') 
) 

# Points defining square region for background 
square <- with(mtcars, data.frame( 
  x = c(-Inf, Inf, Inf, -Inf), 
  y = c(-Inf, -Inf, Inf, Inf)
  ))

ggplot(mtcars, aes(x = mpg, y = wt)) + 
  geom_polygon(aes(x = x,y = y, color = outline_color, fill = NA), data = merge(outline, square)) + 
  geom_point() + 
  scale_fill_identity() + 
  facet_grid(. ~ cyl) 

Produces the following graph with differing facet borders: enter image description here

Gracchus answered 6/1, 2016 at 23:27 Comment(0)
F
0

in the code provided by Seth, the colors of the outlines don't match those entered in outline_color. If you want colors to correspond to your facet labels you could make some adjustments.

outline <- data.frame(cyl = c(4, 6, 8))
# Points defining square region for background
square <- with(mtcars, data.frame(
  x = c(-Inf, Inf, Inf, -Inf),
  y = c(-Inf, -Inf, Inf, Inf)
))

ggplot(mtcars, aes(x = mpg, y = wt)) +
  geom_polygon(aes(x = x,y = y, color = as.factor(cyl), fill = NA,linewidth=3), data = merge(outline, square)) +
  scale_color_manual(values=c("4"= "maroon2","6"= "mediumpurple1","8" ="lightseagreen")) +
  geom_point() +
  scale_fill_identity() +
  facet_grid(. ~ cyl)
Friar answered 26/8 at 15:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.