Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 heatmap : how to preserve the label order?

Tags:

r

ggplot2

heatmap

I'm trying to plot heatmap in ggplot2 using csv data following casbon's solution in

http://biostar.stackexchange.com/questions/921/how-to-draw-a-csv-data-file-as-a-heatmap-using-numpy-and-matplotlib

the problem is x-label try to re-sort itself. For example, if I swap label COG0002 and COG0001 in that example data, the x-label still come out in sort order (cog0001, cog0002, cog0003.... cog0008).

Is there anyway to prevent this ? I want to it to be ordered as in csv file

thanks

pp

like image 484
Tg. Avatar asked Jun 07 '10 13:06

Tg.


3 Answers

If I recall, when calling factor(x) with the default levels argument, the levels are set as levels = sort(unique(x)).

You can override this action by setting levels = unique(x).

For example:

set.seed(1)
x = sample(letters, 100, replace = TRUE)
head(x, 5)

[1] "g" "j" "o" "x" "f"

levels(factor(x))

[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s"

[20] "t" "u" "v" "w" "x" "y" "z"

levels(factor(x, levels = unique(x)))

[1] "g" "j" "o" "x" "f" "y" "r" "q" "b" "e" "u" "m" "s" "z" "d" "k" "a" "w" "i"

[20] "p" "v" "c" "n" "t" "l" "h"

You can see that setting levels = unique(x) preserves the order of occurrence in the data.

like image 107
Greg Avatar answered Oct 21 '22 18:10

Greg


If you want to keep the order directly from the csv file :

foomelt$COG <- factor(foomelt$COG, levels = unique(as.character(foo[[1]])))
like image 6
Etienne Racine Avatar answered Oct 21 '22 17:10

Etienne Racine


Did you try reordering factor levels before plotting? e.g.

foomelt$COG = factor(foomelt$COG,levels(foomelt$COG)[c(2,1,3:8)])

(I can't try it right now, so I can't be sure that it works)

like image 2
George Dontas Avatar answered Oct 21 '22 18:10

George Dontas