Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

ggplot2

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.

like image 349
radek Avatar asked Aug 21 '13 20:08

radek


People also ask

How do I change a facet label in R?

Facet labels can be modified using the option labeller , which should be a function. In the following R code, facets are labelled by combining the name of the grouping variable with group levels. The labeller function label_both is used.

How do I change the color of a border in R?

To change the plot border color of a ggplot2 graph in R, we can use theme function with panel. background argument where we can set the border of the plot panel using element_rect to desired color.

What is facet wrap in ggplot2?

facet_wrap() makes a long ribbon of panels (generated by any number of variables) and wraps it into 2d. This is useful if you have a single variable with many levels and want to arrange the plots in a more space efficient manner. You can control how the ribbon is wrapped into a grid with ncol , nrow , as.

What is the function of Facet_grid () in Ggplot ()?

facet_grid() forms a matrix of panels defined by row and column faceting variables. It is most useful when you have two discrete variables, and all combinations of the variables exist in the data. If you have only one variable with many levels, try facet_wrap() .


1 Answers

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

like image 186
Arun Avatar answered Oct 10 '22 11:10

Arun