1

My dataframe:

Variable <- sample(-9:10)
Levels<-rep(c("N", "A", "L","B", "O", "C", "U", "R", "E", "Y" ),times=2)
ID<-rep(c("WT", "KO"), each=10)
df <- data.frame(Variable, Levels, ID)

I run ggplot and I get this:

enter image description here

If I had these two lines

df$ID=factor(df$ID, c("WT","KO"))
df$Levels=factor(df$Levels, c("N", "A", "L","B", "O", "C", "U", "R", "E", "Y" ))

I can get this

enter image description here

But there must be a way to do this without entering manually the levels

csgillespie
  • 59,189
  • 14
  • 150
  • 185
Al14
  • 1,734
  • 6
  • 32
  • 55

1 Answers1

3

Just create your initial data frame with the correct factor, i.e.

df = data.frame(Variable, factor(Levels, levels=unique(Levels)), ID)

The unique function helpfully maintains the correct order. Alternatively,

levels = c("N", "A", "L","B", "O", "C", "U", "R", "E", "Y" )
Levels = factor(rep(levels, each=2), levels)
csgillespie
  • 59,189
  • 14
  • 150
  • 185