0

I have a data set (called X3.scaled) containing chemical data that I want to plot in histograms that has the following basic characteristics:

> dim(X3.scaled)
[1] 28 40
> class(X3.scaled)
[1] "matrix"

By using gather and facet_wrap i get the plots I wanted but the problem is that they are displayed by alphabetical order instead of the order I want:

dim(X3.scaled)
[1] 28 40

key.X3<-colnames(X3.scaled)
X3.df<-as.data.frame(X3.scaled)
gather(X3.df, key = key.X3, value, )

ggplot(gather(X3.df), aes(value)) +  geom_histogram(bins = 10) +           
facet_wrap(~key, scales = 'free_x')

The order I want is the same order as in the matrix/data frame, which is the same as the order of the column names and the key. I have tried the factor_key=TRUE in gather(), setting factor levels on the key-vector and on the data frame is self but that does not work:

key.X3=factor(key.X3, levels = key.X3)
X3.df=factor(X3.df, levels=key.X3)
gather(X3.df, key = key.X3, value, , factor_key = TRUE)

str(key.X3)
Factor w/ 40 levels "TIC","TOC","TC",..: 1 2 3 4 5 6 7 8 9 10 ...

str(X3.df)
Factor w/ 40 levels "TIC","TOC","TC",..: NA NA NA NA NA NA NA NA NA NA ...
- attr(*, "names")= chr [1:40] "TIC" "TOC" "TC" "TS" ...

I thought of using this example: controlling order of facet_grid/facet_wrap in ggplot2? and How to change the order of facet labels in ggplot (custom facet wrap labels) but they do not use gather() and I do not know how to do it without gather (and do not have the google fu required to find the solution). I also took a look at Separate ordering in ggplot facets but I do not think that this will be a good solution as I am only concerned with the order of the panels and not the labeling.

I think the best solution is something like Use forcat::fct_reorder to sort plots within facet_wrap but I am just not skilled and clever enough to rewrite the code used in the example where they plot panels by Country=rows (as I understand it) to plot panels by columns that I want. I am really sorry for the stupid question and I am sure there is a really simple solution but I just can not seem to find it on my own.

Nanna
  • 73
  • 8

1 Answers1

1

Try reordering the levels of the factor you use for facetting:

df$key <- factor(df$key, levels=c("first facet", "second facet", (in the order you want the facets))

Note that this will be cleaner if you assign your gathered data frame to a variable, then reorder the facets, then call ggplot.

Luke Hayden
  • 692
  • 4
  • 8