如图,当我不保存输出结果为PDF时,输出的图像正常:
在R中执行层次聚类的常用步骤如下:
library(cluster) # 用于聚类分析
library(ggplot2) # 用于作图
library(gplots) # 用于热图绘制
data <- read.csv("yourdata.csv")
str(data) # 查看数据结构
distance <- dist(data, method = "euclidean") # 欧式距离
hc <- hclust(distance, method = "ward.D2") # Ward法聚类
plot(hc) # 绘制树形图
k <- 3 # 选择3个聚类中心
kmeans <- kmeans(data, k)
# 热图
heatmap(data, kmeans$cluster, col = rainbow(k),
margins = c(10, 10), main = "Heatmap of Clustering")
# Scatter plot
ggplot(data, aes(x, y, color = factor(kmeans$cluster))) +
geom_point()
# 保存PDF
pdf("hc_kmeans_result.pdf")
plot(hc)
heatmap(data, kmeans$cluster, col = rainbow(k), margins = c(10, 10))
ggplot(data, aes(x, y, color = factor(kmeans$cluster))) + geom_point()
dev.off()
在最后一步保存结果为PDF时,如果出现错误,请检查: