我正在尝试使用 ggplot2 创建一个热图,但我注意到当我绘制它时它似乎将矩阵向左旋转 90 度。这很奇怪,使用coord_flip()
和t()
不工作,因为他们将其旋转到左边,而不是右边(所以他们没有纠正,而是创建了一个旋转 180 度的热图)。是否有任何选项或技巧可以防止这种情况发生?以下是相关代码:
#this is needed to run custHeat
zeroInterval <- function(mat, colors){
#modified version of findInterval such that zero is given its own category
#This function takes intervals as left exclusive, right inclusive.
#This is mostly so that intervals consisting of a single value will still be represented.
intervalMat <- matrix(0, nrow=nrow(mat), ncol=ncol(mat))
j <- 1
for(i in 1:(length(colors) - 1)){
if(colors[i] != colors[i+1]){
intervalMat[mat>colors[i] & mat<=colors[i+1]] <- j
j <- j + 1
} else {
intervalMat[mat==colors[i]] <- j
j <- j + 1
}
}
return(intervalMat)
}
#this actually plots the heatmap
custHeat <- function(M){
#create color bins/ranges for skewed matrix
color_bins <- c(-5, -4, -3, -2, -1, 0, 0, 1)
colors <- c('#67001F', '#B2182B', '#D6604D', '#F4A582', '#FDDBC7', "#FFFFFF", '#C6DBEF')
#create complete color palette
color_palette <- colorRampPalette(colors)(length(color_bins) - 1)
#This function assigns a number to each matrix value, so that it is colored correctly
mod_mat <- zeroInterval(random_matrix, color_bins)
## remove background and axis from plot
theme_change <- theme(
plot.background = element_blank(),
panel.grid.minor = element_blank(),
panel.grid.major = element_blank(),
panel.background = element_blank(),
panel.border = element_blank(),
axis.line = element_blank(),
axis.ticks = element_blank(),
axis.text.x = element_blank(),
axis.text.y = element_blank(),
axis.title.x = element_blank(),
axis.title.y = element_blank()
)
## output the graphics
ggplot(melt(mod_mat), aes(x = X1, y = X2, fill = factor(value))) +
geom_tile(color = "black") +
scale_fill_manual(values = color_palette, name = "") +
theme_change
}
##create random matrix, skewed toward negative values
random_matrix <- matrix(runif(100, min = -5, max = 1), nrow = 10)
random_matrix[1,] <- 0 #zeros should be at the top row of the heatmap
custHeat(random_matrix)