简体   繁体   中英

ggplot2 heatmap : how to preserve the label order?

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

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.

如果您想直接从 csv 文件中保留订单:

foomelt$COG <- factor(foomelt$COG, levels = unique(as.character(foo[[1]])))

Did you try reordering factor levels before plotting? eg

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM