2016-08-02 140 views
1

此处新建R用户。 我正在尝试向使用ggplot2创建的这个热图添加一个树形图。我怎样才能做到这一点?我已将我的代码添加到下面的热图中。将树形图添加到ggplot2热图

#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 

感谢您的帮助,

夏洛特

+1

也许'ggdendro'包会帮助你呢? – Warner

+0

有一个很好的例子[在这里](https://情节。ly/ggplot2/ggdendro-dendrograms /)使用'ggdendro'和'plotly' –

+0

@MattSandgren我鼓励你看看dendextend。它有一个用ggplot2创建树状图的叉子,它保存图形参数,例如树的颜色和线宽。看到这里:https://cran.r-project.org/web/packages/dendextend/vignettes/introduction.html#ggplot2-integration –

回答

0

使用heatmap.2功能在gplots包(https://cran.r-project.org/web/packages/gplots/gplots.pdf),它会自动添加一个树形图的热图。使用你的例子:

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) 
2

这是一个有点棘手,因为不是所有的作品都完全准备好,但它是我在heatmaply开始走到这一步工作的目的。如果您对此感兴趣,以便积极地使用树状图创建交互式热点图,则应该查看heatmaply vignette

如果您对静态热图感兴趣,我相信现有的软件包已经做得很好,因此重新开发这个软件可能不值得。 但是,如果这仍然是你想做的事,这里是它的主要步骤:

  1. 产生树状对象
  2. 情节GGPLOT2
  3. 树状对象创建的方式,将热图从树形尊重行(或列的顺序
  4. 合并的对象。

步骤1可以使用hclustas.dendrogram,步骤2需要吨他来自dendextend的[as.ggdend][2]函数。第3步可以使用heatmaply :: heatmapr + heatmaply ::: ggplot_heatmap(目前隐藏,但将来会公开这种类型的东西)。第4步是棘手的​​,我目前无法“足够好”地工作,因为这些元素的比例并不好。

我将其封装到一个新的ggheatmap函数中,并将其上传到heatmaply on github。但是这需要更多的工作,所以我愿意提出要求。在此期间,这里是如何做到这一点:

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) 

输出看起来是这样的:

enter image description here

由于我使用GGally::ggmatrix我似乎无法控制每个的比例目的。有可能是更多的在其他方面做的(就像对付标签的布局,添加的侧面颜色图例 - 等)

+0

我提交了一个问题:https://github.com/ggobi/ggally/issues/ 188 –

+0

'ggheatmap'不再是'heatmaply',对吗?它是在版本'0.8.3'中,但不是在当前的'0.11.1' – deeenes

+0

Hi @deeenes这是正确的。 ggheatmap函数被删除,因为它不够光滑。但是,您可以使用“文件”参数将热映射交互式输出保存到静态文件中。我还添加了一个问题,可能在将来添加ggheatmap ... https://github.com/talgalili/heatmaply/issues/108 –

0

或者尝试heatmap3功能:

library(heatmap3) 
Cars <- mtcars[c(1:7)] 
heatmap3(cor(Cars), scale = "none", sym = T) 

enter image description here

+0

heatmap3是伟大的 - 但它不是基于ggplot2 –

+0

是的,你是绝对正确的。也许他不想重新发明轮子。否则,你的方法似乎是一个解决方案。 – Jimbou

+0

同意。 :) (我也希望使用现有的解决方案之一) –