by Rtist
Last Updated January 04, 2018 08:26 AM

I have a data frame with 5 groups. I want to facet my data by group using ggplot. I need the panels to be ordered from right to left, and not from left to right (the default).

```
df <- data.frame(group=letters[1:5],
x=1:5,
y=1:5)
ggplot(df, aes(x,y)) +
geom_point(size=3) +
facet_wrap(~group)
```

By default the panels are ordered from left to right, so that group 'a' appears at the top-left of the graph. The panel at the bottom-right is empty (as there are only 5 groups). I want the panels to appear from right to left. That is, 'a' should appear at the top-right and the panel at the left-bottom should be empty. Any ideas?

Note: the question is not about the labels of the panels. It is also not about re-ordering the group with factor(). I looked at the facet_wrap() help, but the only options are the 'switch' and 'strip.position' arguments that deal with labels. The 'dir' argument allows vertical or horizontal position, which is not what I am looking for.

Thanks in advance

Here's a solution that's somewhat hacky, because it requires manual positioning. We create a plotting function and then plot the first row of plots (rows 1 to 3 of `df`

and the second row of plots (rows 4 and 5 of `df`

) separately. We lay them out using `grid.arrange`

, but we add a blank grob (`nullGrob()`

) in the second row to create the blank space. The manual adjustment of the `widths`

argument is necessary to get the `nullGrob()`

to take up just the right amount of space so that the plot line up vertically.

```
library(gridExtra)
library(grid)
pf = function(data, xrng, yrng) {
ggplot(data, aes(x,y)) +
geom_point(size=3) +
facet_wrap(~ group) +
scale_y_continuous(limits=yrng) +
scale_x_continuous(limits=xrng)
}
grid.arrange(pf(df[1:3,], xrng=range(df$x), yrng=range(df$y)),
arrangeGrob(nullGrob(), pf(df[4:5,], xrng=range(df$x), yrng=range(df$y)),
widths=c(1,2.22)),
ncol=1)
```

- ServerfaultXchanger
- SuperuserXchanger
- UbuntuXchanger
- WebappsXchanger
- WebmastersXchanger
- ProgrammersXchanger
- DbaXchanger
- DrupalXchanger
- WordpressXchanger
- MagentoXchanger
- JoomlaXchanger
- AndroidXchanger
- AppleXchanger
- GameXchanger
- GamingXchanger
- BlenderXchanger
- UxXchanger
- CookingXchanger
- PhotoXchanger
- StatsXchanger
- MathXchanger
- DiyXchanger
- GisXchanger
- TexXchanger
- MetaXchanger
- ElectronicsXchanger
- StackoverflowXchanger
- BitcoinXchanger
- EthereumXcanger