Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2: Add name of variable used for facet_grid

require(ggplot2)
ggplot(mtcars, aes(mpg, wt)) + geom_point() + facet_grid(vs+gear ~ cyl+am) 

enter image description here

I would like to add the name of the 4 variables used for facet_grid on this graph. I suppose the best way to do so would be to add the name of the variables in the corners with a small arrow pointing to the row or column. I was thinking to use annotation_custom and textGrob for this purpose but failed to get anything printed on the graph.

like image 522
Remi.b Avatar asked Sep 16 '16 18:09

Remi.b


People also ask

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() .

How do you rename a facet grid label?

Change the text of facet labels 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.

What is the difference between Facet_wrap and Facet_grid?

The facet_grid() function will produce a grid of plots for each combination of variables that you specify, even if some plots are empty. The facet_wrap() function will only produce plots for the combinations of variables that have values, which means it won't produce any empty plots.

What does Facet_wrap () help us do when added to a Ggplot?

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.


1 Answers

Something like this?

ggplot(mtcars, aes(mpg, wt)) + geom_point() + facet_grid(vs+gear ~ cyl+am,labeller = labeller(.rows = label_both, .cols = label_both))

You can also use syntax like so:

labeller = label_bquote("Gear"==.(gear))
like image 69
Dan Slone Avatar answered Sep 19 '22 01:09

Dan Slone