New R user here. I am trying to add a dendrogram to this heatmap that I created using ggplot2. How can I do that? I have added my code to the heat map below.
#Mtcars using ggplots and reshape2
install.packages("ggplot2")
library(ggplot2)
intall.packages("reshape2")
library(reshape2)
data(mtcars)
Cars <- mtcars[c(1:7)] #subset to 6 genres
cor(Cars) # 6x6 cor matrix
#ggplot likes the data 'melted' one value per row
m <-melt(cor(Cars))
p <- ggplot(data=m, aes(x=Var1, y=Var2, fill=value)) + geom_tile()
p
#set up a coloring scheme using colorRampPalette
red=rgb(1,0,0); green=rgb(0,1,0); blue=rgb(0,0,1); black=rgb(0,0,0)
RtoBrange<-colorRampPalette(c(red, black ) )
BtoGrange<-colorRampPalette(c(black, green) )
p <- p + scale_fill_gradient2(low=RtoBrange(100), mid="black", high=BtoGrange(100))
p
Thanks for your help,
Charlotte
This is a bit tricky since not all the pieces are fully ready, but it is the aim of the work I started in heatmaply to get to this point. If you are interested in this in order to work with plotly to create interactive heatmaps with dendrogram, than you should look at the heatmaply vignette .
If you are interested in a static heatmap I believe that existing packages are already doing a great job, so it is probably not worth it to reinvent this wheel. But if this is still what you want to do, here are the main steps for it:
Step 1 can use hclust
and as.dendrogram
, step 2 requires the [as.ggdend][2]
function from dendextend. Step 3 can be done using heatmaply::heatmapr + heatmaply:::ggplot_heatmap (which is currently hidden, but will be exposed in the future for this type of thing). Step 4 is tricky, I couldn't get it to work "well enough" so far in that the proportions of the elements are not good.
I wrapped this into a new ggheatmap function and just uploaded it to heatmaply on github . But this needs more work, so I'm open to pull requests. In the meantime, here is how to do it:
devtools::install_github("ropensci/plotly") # you will probably benefit from the latest version of plotly
devtools::install_github('talgalili/heatmaply')
library(heatmaply)
x <- heatmapr(iris[,-5], scale = "column", colors = "Blues")
ggheatmap(x)
The output looks like this:
Since I'm using GGally::ggmatrix
I can't seem to control the proportions of each object. There is probably more to do in other regards (like dealing with the layout of the labels, adding color legend on the side - etc.)
Use the heatmap.2
function in the gplots
package ( https://cran.r-project.org/web/packages/gplots/gplots.pdf ), which automatically adds a dendrogram to your heatmap. Using your example:
install.packages("gplots")
library(gplots)
data(mtcars)
Cars <- mtcars[c(1:7)]
mycolors <- colorRampPalette(c("red", "black", "green"))
heatmap.2(cor(Cars), trace = "none", col = mycolors)
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.