最全的R语言聚类树形图画法

本文详细介绍如何使用R语言进行聚类分析,并展示了多种树状图的绘制方法,包括使用不同R包如cluster、ape及sparcl等进行的高级定制。

因为在写论文的时候用到,所以和大家分享。原地址为

http://rstudio-pubs-static.s3.amazonaws.com/1876_df0bf890dd54461f98719b461d987c3d.html

考虑到原地址可能失效,这里做简单的翻译和备份,有关聚类的R包可以参考cluster包和ape包


以下是正文:


The most basic dendrogram

Let's start with the most basic type of dendrogram. For that purpose we'll use themtcars dataset and we'll calculate a hierarchical clustering with the functionhclust (with the default options).

让我们从最基本聚类树状图开始。为此目的,我们将使用mtcars数据集和我们计算的层次聚类hclust函数(与默认选项

# prepare hierarchical cluster 生成层次聚类 
hc = hclust(dist(mtcars))
# very simple dendrogram     默认画法
plot(hc)


We can put the labels of the leafs at the same level like this 

我们可以将样本定义在同一水平 (实在不明白help一下plot函数)

A less basic dendrogram

In order to add more format to the dendrograms, we need to tweek the right parameters. For instance, we could get the following graphic (just for illustration purposes!)

一个基本的树状图

为了增加更多格式的图,我们需要修改正确的参数。例如我们可以得到下面的图形(仅作说明用途

par(op)

##这里强调一下,par()是对图进行自动调整,貌似功能还挺强大的。新浪有位哥们儿总结得特别好,附赠地址:

http://blog.sina.com.cn/s/blog_8f5b2a2e0102v0tf.html

貌似可以靠par()函数调整图的坐标轴什么的,我没试过哦~~

Alternative dendrograms

An alternative way to produce dendrograms is to specifically convert  hclust  objects into dendrograms  objects

另类聚类图

将hclude生成的对象转换为另类的聚类图

# using dendrogram objects
hcd = as.dendrogram(hc)
# alternative way to get a dendrogram
plot(hcd)

Having an object of class dendrogram, we can also plot the branches in a triangular form

画完这个画三角形的

Zooming-in on dendrograms

Another very useful option is the ability to inspect selected parts of a given tree. For instance, if we wanted to examine the top partitions of the dendrogram, we could cut it at a height of 75

放大在树状图

另一个非常有用的功能是选择树的一部分。例如如果我们要研究的树状图的分区我们可以把它在一个高度75

# plot dendrogram with some cuts
op = par(mfrow = c(2, 1))
plot(cut(hcd, h = 75)$upper, main = "Upper tree of cut at h=75")
plot(cut(hcd, h = 75)$lower[[2]], main = "Second branch of lower tree with cut at h=75")

par(op)

Customized dendrograms

In order to get more customized graphics we need a little bit of more code. A very useful resource is the functiondendrapply that can be used to apply a function to all nodes of a dendrgoram. This comes very handy if we want to add some color to the labels.

为了获得更多的定制的图形,我们需要更多的代码。一个非常有用的功能dendrapply可以应用一个函数的一dendrgoram所有节点。如果我们要添加一些色彩的标签这是非常方便的


# vector of colors labelColors = c('red', 'blue', 'darkgreen', 'darkgrey',
# 'purple')
labelColors = c("#CDB380", "#036564", "#EB6841", "#EDC951")
# cut dendrogram in 4 clusters
clusMember = cutree(hc, 4)
# function to get color labels
colLab <- function(n) {
    if (is.leaf(n)) {
        a <- attributes(n)
        labCol <- labelColors[clusMember[which(names(clusMember) == a$label)]]
        attr(n, "nodePar") <- c(a$nodePar, lab.col = labCol)
    }
    n
}
# using dendrapply
clusDendro = dendrapply(hcd, colLab)
# make plot
plot(clusDendro, main = "Cool Dendrogram", type = "triangle")

Phylogenetic trees

A very nice tool for displaying more appealing trees is provided by the R packageape. In this case, what we need is to convert thehclust objects intophylo pbjects with the funtions as.phylo

系统进化树

由R包ape提供更具吸引力的树非常好的工具我们利用as.phylo功能将hclust objects转换成phylo对象

# load package ape; remember to install it: install.packages('ape')
library(ape)
# plot basic tree
plot(as.phylo(hc), cex = 0.9, label.offset = 1)


The plot.phylo function has four more different types for plotting a dendrogram. Here they are:

plot.phylo函数的4种不同类型的聚类树形图

# cladogram
plot(as.phylo(hc), type = "cladogram", cex = 0.9, label.offset = 1)

# unrooted
plot(as.phylo(hc), type = "unrooted")

下面是我最喜欢的圆形树形图

# fan    
plot(as.phylo(hc), type = "fan")

# radial
plot(as.phylo(hc), type = "radial")

Customizing phylogenetic trees

What I really like about the ape package is that we have more control on the appearance of the dendrograms, being able to customize them in different ways. For example:

自定义的系统进化树

ape 包对树的性状有着很多控制,能够定制他们以不同的方式。例如

# add colors randomly
plot(as.phylo(hc), type = "fan", tip.color = hsv(runif(15, 0.65, 
    0.95), 1, 1, 0.7), edge.color = hsv(runif(10, 0.65, 0.75), 1, 1, 0.7), edge.width = runif(20, 
    0.5, 3), use.edge.length = TRUE, col = "gray80")


Again, we can tweek some parameters according to our needs

我们可以根据需求修改一些参数

# vector of colors
mypal = c("#556270", "#4ECDC4", "#1B676B", "#FF6B6B", "#C44D58")
# cutting dendrogram in 5 clusters
clus5 = cutree(hc, 5)
# plot
op = par(bg = "#E8DDCB")
# Size reflects miles per gallon
plot(as.phylo(hc), type = "fan", tip.color = mypal[clus5], label.offset = 1, 
    cex = log(mtcars$mpg, 10), col = "red")

par(op)

Color in leaves

彩色叶子节点

The R package sparcl provides the ColorDendrogram function that allows to add some color. For example, we can add color to the leaves

R包还提供ColorDendrogram功能来让我们给聚类树点颜色看看。比如我们可以给叶子节点来点颜色

# install.packages('sparcl')
library(sparcl)
# colors the leaves of a dendrogram
y = cutree(hc, 3)
ColorDendrogram(hc, y = y, labels = names(y), main = "My Simulated Data", 
    branchlength = 80)

ggdendro

For reasons that are unknown to me, the The R package ggplot2 have no functions to plot dendrograms. However, the ad-hoc packageggdendro offers a decent solution. You would expect to have more customization options, but so far they are rather limited. Anyway, for those of us who are ggploters this is another tool in our toolkit.

R包ggplot2没有功能绘制树状图的原因我不知道。然而,包ggdendro提供一个像样的解决方案。你希望有更多的自定义选项,但到目前为止他们相当有限。不管怎样对于我们这些谁是ggploters这是我们工具的另一个工具


# install.packages('ggdendro')
library(ggdendro)
# basic option
ggdendrogram(hc)

# another option
ggdendrogram(hc, rotate = TRUE, size = 4, theme_dendro = FALSE, color = "tomato")

# Triangular lines
ddata <- dendro_data(as.dendrogram(hc), type = "triangle")
ggplot(segment(ddata)) + geom_segment(aes(x = x, y = y, xend = xend, 
    yend = yend)) + ylim(-10, 150) + geom_text(data = label(ddata), aes(x = x, 
    y = y, label = label), angle = 90, lineheight = 0)


Colored dendrogram

Last but not least, there's one more resource available from Romain Francois'saddicted to Rgraph gallery which I find really interesting. The code in R for generating colored dendrograms, which you can download and modify if wanted so, is availablehere

最后,你可以到罗曼弗朗索瓦的图形库里面进一步学习~~~

你甚至可以修改他的代码

地址是:

http://gallery.r-enthusiasts.com/RGraphGallery.php?graph=79 (貌似要翻墙)

http://addictedtor.free.fr/packages/A2R/lastVersion/R/code.R

# load code of A2R function
source("http://addictedtor.free.fr/packages/A2R/lastVersion/R/code.R")
# colored dendrogram
op = par(bg = "#EFEFEF")
A2Rplot(hc, k = 3, boxes = FALSE, col.up = "gray50", col.down = c("#FF6B6B", 
    "#4ECDC4", "#556270"))

par(op)

# another colored dendrogram
op = par(bg = "gray15")
cols = hsv(c(0.2, 0.57, 0.95), 1, 1, 0.8)
A2Rplot(hc, k = 3, boxes = FALSE, col.up = "gray50", col.down = cols)


par(op)





转载自:http://blog.youkuaiyun.com/u010157382/article/details/45562435



<think>首先,用户的问题是关于如何实现圆形聚类树形图(Circular Dendrogram),这是一种用于层次聚类的可视化方法,特别适合样本数较多时避免矩形树状图过长的问题。 根据系统级指令: - 所有行内数学表达式必须使用$...$格式。 - 独立公式必须使用$$...$$格式并单独成段。 - LaTeX语法正确。 - 使用中文回答。 - 生成相关问题。 - 回答中引用的段落末尾自然地添加引用标识。 用户意图:用户想了解如何实现圆形聚类树形图,用于数据可视化中的层次聚类展示。参考了引用[1]、[2]、[3],其中[2]提到使用R语言ggtree包绘制圆形树状图。 我的回答结构: 1. 解释什么是圆形聚类树形图及其优势。 2. 提供实现方法,包括代码示例(R语言,使用ggtree包)。 3. 确保代码正确,并解释关键部分。 4. 生成相关问题。 回答步骤: - 开头简要介绍圆形聚类树形图。 - 然后分步骤说明实现方法,包括代码。 - 最后生成相关问题。 引用处理: - 在回答中引用相关段落时添加引用标识,例如:[^1]。 - 参考引用[1]:聚类树(Dendrogram)的定义。 - 引用[2]:使用ggtree绘制圆形树状图。 - 引用[3]:R语言绘制聚类树的方法。 代码示例: - 基于引用[2],使用R语言ggtree包。 - 示例代码:加载数据、层次聚类、绘制圆形树状图。 完整回答框架: 1. **引言**:解释圆形聚类树形图及其应用。 2. **实现方法**: - 步骤1:准备数据。 - 步骤2:进行层次聚类。 - 步骤3:使用ggtree绘制圆形树状图。 - 提供完整代码示例。 3. **解释**:简要说明代码关键点。 4. **相关问题**:生成3-5个相关问题。 确保语言:中文。 生成相关问题: - 如指令所示,在最后添加"§§相关问题§§"部分。 - 问题应与主题相关,例如:如何定制圆形树状图?其他可视化方法?等。 最终输出: - 回答部分。 - 相关问题部分。</think>### 圆形聚类树形图的实现方法 圆形聚类树形图(Circular Dendrogram)是一种层次聚类的可视化形式,通过将传统的矩形树状图转换为环形布局,有效解决样本数量较多时图形过长的问题。这种方法在数据可视化中尤其适用于展示层次聚类结果,使高维数据的聚类关系更易解读[^2]。以下我将基于R语言(使用ggtree包)逐步说明实现方法。ggtree包专为树形结构可视化设计,支持圆形布局,代码简洁高效。 #### 步骤1: 安装和加载必要的包 首先,确保安装了R语言环境。然后安装并加载所需包: - `ggtree`:用于绘制树状图。 - `ape`:处理树形数据结构。 - `dplyr`:数据操作。 - `ggplot2`:基础绘图。 ```r # 安装包(如果未安装) install.packages("BiocManager") BiocManager::install("ggtree") install.packages(c("ape", "dplyr", "ggplot2")) # 加载包 library(ggtree) library(ape) library(dplyr) library(ggplot2) ``` #### 步骤2: 准备数据和层次聚类 层次聚类需要先计算距离矩阵和聚类树。这里使用示例数据演示: - **数据准备**:假设有一个包含160个样本的数据集(样本数多时圆形布局优势明显)。 - **聚类过程**:使用`hclust`函数进行层次聚类,生成树状结构。 ```r # 生成示例数据(160个样本,5个特征) set.seed(123) # 确保可重现性 data <- matrix(rnorm(160 * 5), nrow=160, ncol=5) rownames(data) <- paste0("Sample", 1:160) # 样本命名 # 计算距离矩阵和层次聚类 dist_matrix <- dist(data) # 欧氏距离 hc <- hclust(dist_matrix, method="ward.D2") # Ward方法聚类 tree <- as.phylo(hc) # 转换为phylo对象(ggtree所需格式) ``` #### 步骤3: 绘制圆形聚类树形图 使用`ggtree`绘制圆形布局,核心函数为`ggtree()`,通过`layout="circular"`参数实现环形可视化。添加标签和美化图形: - **关键参数**:`layout="circular"`指定环形布局,`branch.length="none"`可隐藏分支长度以简化图形。 - **优化**:添加颜色、标签和标题,使图形更直观。 ```r # 绘制圆形树状图 p <- ggtree(tree, layout="circular", branch.length="none") + geom_tiplab(size=2, color="blue", offset=0.1) + # 样本标签(蓝色,小字号避免重叠) theme(plot.margin = unit(c(1,1,1,1), "cm")) + # 调整边距 labs(title="圆形聚类树形图(160个样本)", caption="基于层次聚类结果") # 显示图形 print(p) ``` #### 步骤4: 结果解释 - **输出**:运行代码后,生成一个环形树状图。样本分布在圆周上,聚类分支以弧线连接,距离表示聚类相似度(距离越短,样本越相似)。 - **优势**:相比矩形树状图,圆形布局节省空间,尤其适合大样本集(如>100个样本),避免图形横向拉伸[^2]。 - **定制**:可通过`ggtree`参数调整颜色、标签大小或添加聚类切分线(如`geom_hline()`)。 #### 注意事项 - **数据量**:圆形布局在样本数超过50时效果更佳。样本过少(如<30)可能使图形稀疏。 - **性能**:`ggtree`处理160个样本的图形渲染通常在几秒内完成。 - **备选方法**:如果使用Python,可参考`dendrogram`结合`matplotlib`的极坐标变换,但R语言ggtree更简洁[^1][^3]。 此方法已广泛应用于生物信息学、市场细分等领域,帮助用户直观探索聚类结构[^2][^3]。
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值