Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the order of ggplot2 facets [duplicate]

Tags:

r

ggplot2

I have a data frame "pd.long" with following structure:

> str(pd.long)
'data.frame':   144 obs. of  3 variables:
$ Site   : Factor w/ 12 levels "BED","BEU","EB",..: 8 9 10 3 11 1 6 7 5 4 ...
$ Month  : Factor w/ 12 levels "Dec","Jan","Feb",..: 1 1 1 1 1 1 1 1 1 1 ...
$ Density: int  20 20 20 20 20 20 20 20 20 20 ...

I have constructed bar-plots with this piece of code:

ggplot(pd.long, aes(x=Month, y=Density, fill=Site))+
geom_bar(stat = "identity", position = "dodge", fill = "darkgray")+
xlab("Month") + ylab("Number")+
facet_wrap(~Site, nrow = 3, scales = "free")

and the graphs look like this:

Everything was fine until I noticed that the levels of variable "Site" are not in the order of my choice. ggplot orders them alphabetically, as follows:

pd.long$Site
Levels: BED BEU EB KAD KAU KB KER KOA KOB KOO PNS RO

However, I want them to be in the same order in which they appear in the variable column i.e.

KOA KOB KOO EB  PNS BED KB  KER KAU KAD RO  BEU

Any help will highly be appreciated. Thank you

like image 882
Muneer Avatar asked Apr 18 '18 12:04

Muneer


People also ask

How do you reorder facets?

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

How do I change the size of a facet label in ggplot2?

For that, we use theme() function, which is used to customize the appearance of plot. We can change size of facet labels, using strip. text it should passed with value to produce labels of desired size.


1 Answers

reorder the factors

pd.long$Site <- factor(pd.long$Site,levels=c("KOA","KOB","KOO","EB","PNS","BED","KB","KER","KAU","KAD","RO","BEU"))

or more general answer where the order is based on the first apperance in the Site column :

pd.long$Site <- factor(pd.long$Site,levels=unique(pd.long$Site))
like image 71
Nicolas Rosewick Avatar answered Oct 25 '22 09:10

Nicolas Rosewick