I am trying to construct a heatmap in R using a correlation matrix and a p value matrix.
I use this tutorial to build the heatmap without problems. It works perfectly. I can even introduce some values from a second matrix (the p value matrix) in the right cells.
But when I try to highlight the corresponding cells it doesn't work. I use this code to generate the borders.
I use RStudio v0.97 with the packages gplots, RColorBrewer.
The code is :
library(gplots)
library(RColorBrewer)
my_palette <- colorRampPalette(c("red", "yellow", "green"))(n = 299)
nx = 5
ny = 10
mat1 <- matrix(rnorm(nx*ny,100,50),nx,ny)
mat2 <- mat1>150 #matrix used for the example instead of the p value matrix
makeRects <- function(tfMat,border){
cAbove = expand.grid(1:nx,1:ny)[tfMat,]
xl=cAbove[,1]-0.49
yb=cAbove[,2]-0.49
xr=cAbove[,1]+0.49
yt=cAbove[,2]+0.49
rect(xl,yb,xr,yt,border=border,lwd=3)
} #this is the function to make the rectangles/borders
heatmap.2(mat1,
Rowv = FALSE, # don't reorganize columns
cellnote = mat2, # check correspondance between rectangles and mat2 values
main = "Correlation", # heat map title
notecol="black", # change font color of cell labels to black
notecex=0.5, # change the scaling of the cell labels
density.info="none", # turns off density plot inside color legend
trace="none", # turns off trace lines inside the heat map
margins =c(12,9), # widens margins around plot
col=my_palette, # use on color palette defined earlier
dendrogram="row", # don't draw a row dendrogram
Colv="NA", # turn off column clustering
add.expr = {makeRects(mat2,"black")}) #add the borders
I think something is wrong either with the makeRects function, or with the re-ordering of the rows via the heatmap.2 function. The rectangles appear in the heatmap, but they are not at the right positions. I have been scratching my head all day without finding what is wrong.
Any suggestions?
Related
My problem is related to car package.
I create Kernal plot. However, since legend is too big, I would like to move legend outside the plot are, upper or lower?
Otherwise, I tried with cowplot::get_legend( ), but it did not work properly.
library(car)
mtcars$g <- as.factor(mtcars$vs)
densityPlot(mpg,mtcars$g,show.bw=T, kernel=depan,legend=list(location="topleft",title=NULL))
Probably the easiest thing is to not plot the legend using the densityPlot() function but rather add it separately using legend(). The following code is an example of how this can be done. The resulting figure look like this:
library(car)
mtcars$g <- as.factor(mtcars$vs)
par(mar=c(4,4,4,2))
# obtaining results from kernel density and saving results
# need saved values for bandwidth in legend
# also plots the kernel densities
d <- densityPlot(mtcars$mpg,mtcars$g
,show.bw=T
,kernel=depan
,legend=F # no default legend
,col = c('black','blue')
,lty=c(1,2))
# allows legend outside of plot area to be displayed
par(xpd=T)
# defining location based on the plot coordinates from par('usr')
legend(x=mean(par('usr')[c(1,2)]) # average of range of x-axis
,y=par('usr')[4]+0.015 # top of the y axis with additional shift
,legend = c(paste('0 (bw = ',round(d$`0`['bw'][[1]],4),')',sep='') # extract bw values from saved output and
,paste('1 (bw = ',round(d$`1`['bw'][[1]],4),')',sep='')) # formatting similar to default, except with rounding bw value
,ncol=1 # change to 2 if you want entries beside each other
,lty=c(1,2) # line types, same as above
,col=c('black','blue') # colors, same as above
,lwd=1
,xjust = 0.5 # centers legend at x coordinate
,yjust = 0.5 # centers legend at y coordinate
)
par(xpd=F)
I have a problem, might be a bug in heatmaply or plotly. Colors in the sidebar of a heatmap are not showing the colors I specified. See the code example below, At the end of the code in part # 6) the first plot, plotted using the plot function (simple plot showing the colors), shows the colors correctly (yellow and blue):
The second plot using these colors in a heatmaply side bar (heatmamply side bar with wrong color):
fails to show them correctly and instead what appears to show random colors. In a similar plot with real data there are even red and orange colors in the sidebar (heatmaply sidebar shows red and orange while color range is blue-yellow):
while all codes are generated using a blue yellow color range. Any ideas what might cause this bug and how to show colors in the sidebar consistent with their color code a?
Compare cophenetic similarity between leaves in two trees build on full data and subsample of the data
# 1 ) Generate random data to build trees
set.seed(2015-04-26)
dat <- matrix(rnorm(100), 10, 50) # Dataframe with 50 columns
datSubSample <- dat[, sample(ncol(dat), 30)] #Dataframe with 30 columns sampled from the dataframe with 50
dat_dist1 <- dist(datSubSample)
dat_dist2 <- dist(dat)
hc1 <- hclust(dat_dist1)
hc2 <- hclust(dat_dist2)
# 2) Build two dendrograms, one based on all data, second based a sample of the data (30 out of 50 columns)
dendrogram1 <- as.dendrogram(hc1)
dendrogram2 <- as.dendrogram(hc2)
# 3) For each leave in a tree get cophenetic distance matrix,
# each column represent distance of that leave to all others in the same tree
cophDistanceMatrix1 <- as.data.frame(as.matrix(cophenetic(dendrogram1)))
cophDistanceMatrix2 <- as.data.frame(as.matrix(cophenetic(dendrogram2)))
# 4) Calculate correlation between cophenetic distance of a leave to all other leaves, between two trees
corPerLeave <- NULL # Vector to store correlations for each leave in two trees
for (leave in colnames(cophDistanceMatrix1)){
cor <- cor(cophDistanceMatrix2[leave], cophDistanceMatrix1[leave])
corPerLeave <- c(corPerLeave, unname(cor))
}
# 5) Convert cophenetic correlation to color to show in side bar of a heatmap
corPerLeave <- corPerLeave / max(corPerLeave) #Scale 0 to 1 correlation
byPal <- colorRampPalette(c('yellow', 'blue')) #blue yellow color palette, low correlation = yellow
colCopheneticCor <- byPal(20)[as.numeric(cut(corPerLeave, breaks =20))]
# 6) Plot heatmap with dendrogram with side bar that shows cophenetic correlation for each leave
row_dend <- dendrogram2
x <- as.matrix(dat_dist2)
#### Plot belows use the same color code, normal plot works, however heatmaply shows wrong colors
plot(x = 1:length(colCopheneticCor), y = 1:length(colCopheneticCor), col = colCopheneticCor)
heatmaply(x, colD = row_dend, row_side_colors = colCopheneticCor)
Found the solution, you can use a function for the color with the heatmaply build in row_side_palette parameter. Minimal example code, that can be combined with the code in the question itself to show heatmap with cophenetic distance per leave/species in the sidebar represented by a different color:
ByPal <- colorRampPalette(c('red','blue')) # Bi color palette function to be used in sidebar
heatmaply(m,colD = row_dend, file=fileName1, plot_method= "plotly",colorscale='Viridis',row_side_palette= byPal ,
row_side_colors=data.frame("Correlation cophenetic distances" = corPerLeave, check.names=FALSE))
One problem I did not solve yet is how to show a continuous colorbar in the legend, any suggestions?
With the below code I can generate a nice correlation plot.
library(corrplot)
df <- data.frame(A=1:10,B=rnorm(10)*(1:10),C=1:10,D=runif(10)*1:10)
df
corrplot(cor(df))
Adding the parameter of bg="black" will change the colour inside the graph to black.
df <- data.frame(A=1:10,B=rnorm(10)*(1:10),C=1:10,D=runif(10)*1:10)
df
corrplot(cor(df),bg="black")
Now If I would like to set the whole graph window to black this should work:
par(bg="black")
df <- data.frame(A=1:10,B=rnorm(10)*(1:10),C=1:10,D=runif(10)*1:10)
df
corrplot(cor(df),bg="black")
But it does not. How to get the whole plotting window to black?
Here is a 2-step way:
# First, we need to plot once, to get the extremes of
# the user coordinates of the plotting region, as set
# by the corrplot function
corrplot(cor(df))
# The extremes are stored
usr <- par("usr")
# New empty plotting window
plot.new()
# Set the new extremes
par(usr=usr)
# Plot a rectangle filled in black, covering the whole plotting window
rect(par("usr")[1],par("usr")[3],par("usr")[2],par("usr")[4],col = "black")
# Finally, plot the corrplot
corrplot(cor(df), bg="black", add = TRUE)
I would like to plot a raster containing 4 different values (1) with a categorical text legend describing the categories such as 2 but with colour boxes:
I've tried using legend such as :
legend( 1,-20,legend = c("land","ocean/lake", "rivers","water bodies"))
but I don't know how to associate one value to the displayed color. Is there a way to retrieve the colour displayed with 'plot' and to use it in the legend?
The rasterVis package includes a Raster method for levelplot(), which plots categorical variables and produces an appropriate legend:
library(raster)
library(rasterVis)
## Example data
r <- raster(ncol=4, nrow=2)
r[] <- sample(1:4, size=ncell(r), replace=TRUE)
r <- as.factor(r)
## Add a landcover column to the Raster Attribute Table
rat <- levels(r)[[1]]
rat[["landcover"]] <- c("land","ocean/lake", "rivers","water bodies")
levels(r) <- rat
## Plot
levelplot(r, col.regions=rev(terrain.colors(4)), xlab="", ylab="")
By default, the colours used in a raster-plot are generated by rev(terrain.colors()) (see ?raster::plot). You can use this to re-create that sequence of 4 colours for your legend - or choose a random sequence of colours:
my_col = rev(terrain.colors(n = 4))
# my_col = c('beige','red','green','blue')
First plot the map using the colour sequence. legend = FALSE gets rid of the standard colour bar:
plot(my_raster, legend = FALSE, col = my_col)
Add a custom legend to the bottom left. Use the fill argument to generate coloured boxes:
legend(x='bottomleft', legend = c("land", "ocean/lake", "rivers", "water bodies"), fill = my_col)
By using the command:
heatmap.2(exp, col = greenred(100), scale="none", ColSideColors = Carcolors,
# dendrogram = "row",
key=T, symkey=FALSE, density.info="none", trace="none", cexRow=1, cexCol=0.9)
The heatmap2 plots "samples" as columns and variables as rows. How can I rotate the heatmap counterclock wise 90 degree so the sample names are listed on the right and variables are listed on the top (with RowSideColors on the right also)? Thanks!
I am not sure if I understand you right, but does a tranpose of your matrix do the job?
Here is an example:
require(gplots)
data(mtcars)
x <- as.matrix(mtcars)
heatmap.2(x)
# transpose the matrix
heatmap.2(t(x))