Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 facet_grid arrange panels

Tags:

r

layout

ggplot2

the following example creates a ggplot with the 4 panels "A", "B", "C", "D" in one row.

I figured out how to plot these 4 panels in one column. However, what still remains a mystery is how to arrange the 4 panels so that "A" and "B" are in the first row and "C" and "D" are put in a separate (second) row?

Here's my code:

df <- data.frame(
x = rep(rep(1:10, each=10), 2),
y = rep(rep(1:10, 20), 2),
grid = rep(LETTERS[1:4], each=100)
)

ggplot(df, aes(x = x, y = y)) +
geom_point() +
facet_grid(. ~ grid, scales = "free")
like image 337
user969113 Avatar asked Aug 30 '12 12:08

user969113


People also ask

How do I rearrange facets in ggplot2?

To reorder the facets accordingly of the given ggplot2 plot, the user needs to reorder the levels of our grouping variable accordingly with the help of the levels function and required parameter passed into it, further it will lead to the reordering of the facets accordingly in the R programming language.

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

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.

How does facet wrap work R?

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

Use facet_wrap instead of facet_grid:

library(ggplot2)
ggplot(df, aes(x = x, y = y)) +
  geom_point(aes(colour=grid)) +
  facet_wrap(~ grid, scales = "free")

enter image description here

like image 97
Andrie Avatar answered Oct 14 '22 16:10

Andrie