ggplot2: reorder x axis label by factor of levels doesn't work

Viewed 843

I want to draw a plot with x-axis labels equal to c("chr","lab1","lab3","lab10") But when I set up the level of x-axis, it seems the reorder of x-axis doesn't work.
Can anyone help me solve the problem? I don't know why I cannot change the order of x-axis labels.

enter image description here

library(ggplot2)
library(viridis)

set.seed(123)
data.df=data.frame(gene=c("APC","NF2","APC","NF2","APC","NF2","APC","NF2"),
                   variable=c("lab1","lab1","lab3","lab3","lab10","lab10","chr","chr"),
                   value=c(sample.int(100, 6),5,22))

ggplot(data.df, aes(x=factor(variable, level = c("chr",paste0("lab",c(1,3,10)))),
                    y=factor(gene, level = c("NF2","APC")))) + 
  geom_tile(data=filter(data.df,variable != 'chr'), 
            aes(fill= value),colour='white') +  
  geom_point(data = filter(data.df,variable=="chr"),
             aes(col=as.factor(value)))+ 
  scale_fill_viridis_b()

===============

An update about the dataset, my entire dataset includes 1254 obs. of 3 variables.

To set up the level of variable seems work for this example, but it doesn't work for my entire dataset.

> str(melt.df)
'data.frame':   1254 obs. of  3 variables:
 $ gene    : Factor w/ 57 levels "NF2","TNNI3",..: 29 16 39 49 18 31 9 20 52 46 ...
 $ variable: Factor w/ 22 levels "chromosome_name",..: 2 2 2 2 2 2 2 2 2 2 ...
 $ value   : num  100 100 99.8 100 100 ...

Final update, I find a way to solve my problem by add + scale_x_discrete(limits = c("chr",paste0("lab",c(1,3,10))))

Thank Ricardo Semião e Castro and TarJae for your help!

1 Answers

ggplot2 plots any factor variable in the order of their levels, and by default, R sets the levels of a factor alphabetically, such that "lab10" (which starts with a 1) is before "lab3". To correct this, reorder the levels of your variable:

factor(data.df$variable, c("chr","lab1","lab3","lab10")) 
Related