Variables order for ggplot

2019-08-10 11:24发布

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

标签: r ggplot2
1条回答
时光不老,我们不散
2楼-- · 2019-08-10 12:05

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)
查看更多
登录 后发表回答