change levels of column names of a matrix for plotting heatmap

983 Views Asked by At

I have my matrix and I'm ready to plot a heatmap using the pheatmap package in R.

My matrix is like:

Name A B C
Apple 1 2 3
Banana 4 5 6
Pear 7 8 9

If I don't cluster the column, the heatmap will order the columns as A, B and C. What if I want to set the order as B, C, A?

I tried:

colnames(matrix)<-factor(colnames(matrix),levels = c("B","C","A"))

but it doesn't work.

1

There are 1 best solutions below

2
On BEST ANSWER

Just re-order the columns of your matrix manually.

mat <- as.matrix(data.frame(df[, -1], row.names = df[, 1]))

library(pheatmap)
pheatmap(mat[, c("B", "C", "A")], cluster_rows = F, cluster_cols = F)

enter image description here


Sample data

df <- read.table(text =
    "Name A B C
Apple 1 2 3
Banana 4 5 6
Pear 7 8 9", header = T)