Variables order for ggplot

2019-08-10 11:19发布

问题:

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:

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

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

回答1:

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)


标签: r ggplot2