2

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 Answer 1

4

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")) 
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a lot, this works for the example above, however, it doesn't work for my entire datasets. By the way, do you know why aes(x=factor(variable, level = c("chr","lab1","lab3","lab10"))) doesn't work in my case?
I don't know why changing the levels inside ggplot doesn't work, but it's normally good to modify the dataset anyway. Post your dataset (paste the output from dput(data.df)) and i'll have a look at it.
Thanks. I find a way to fix the problem by add + scale_x_discrete(limits = c("chr",paste0("lab",c(1:4,6:7,9:14))))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.