【问题标题】:Multidimensional scaling plot in RR中的多维缩放图
【发布时间】:2015-09-11 21:43:20
【问题描述】:

我有一个如下所示的数据集(“数据”)

   PatientID Visit  Var1  Var2  Var3  Var4 Var5
1        ID1     0 44.28  4.57 23.56  4.36 8.87
2        ID1     1 58.60  5.34  4.74  3.76 6.96
3        ID1     2 72.44 11.18 21.22  2.15 8.34
4        ID2     0 65.98  6.91  8.57  1.19 7.39
5        ID2     1 10.33 38.27  0.48 14.41   NA
6        ID2     2 69.45 11.18 20.69  2.15 8.34
7        ID3     0 69.16  6.17  10.98  1.91 6.12
8        ID3     1 86.02  3.28  16.29  4.28 5.74
9        ID3     2 69.45 NA 20.69  2.15 8.34
10       ID4     0 98.55 26.75  2.89  3.92 2.19
11       ID4     1 32.66 14.38  4.96  1.13 4.78
12       ID4     2 70.45 11.42 21.78  2.15 8.34

我需要生成包含所有数据点的 MDS 图。我还需要将访问点通过一条线连接起来,访问 1 的颜色为绿色,访问 2 的颜色为红色,访问 3 的颜色为黑色(所有个人的颜色一致)。

我的代码看起来像这样(很长,但它不起作用):

data.cor <- cor(t(data[,3:7]), use = "pairwise.complete.obs", method  = "spearman")

dim(data.cor)

dim(data)

rownames(data.cor) <- paste0(data$PatientID, "V", data$Visit)

colnames(data.cor) <- paste0(data$PatientID, "V", data$Visit)

c <- dist(data.cor)

fit <- cmdscale(c,eig=TRUE, k=2)

ff <- fit$points

ff <- as.data.frame(ff)

ff$pair <- paste0(substr(rownames(ff),1,6))

ff$pair <- factor(ff$pair)

pc.pair.distances <- matrix(nrow = nlevels(ff$pair), ncol = 1)

for(i in 1:nlevels(ff$pair)){

  pair2 <- ff[ff$pair %in% levels(ff$pair)[i] , ]

  pc.pair.distances[i,1] <- sqrt(

    ((pair2[1,1] - pair2[2,1]) * (pair2[1,1] - pair2[2,1])) 
+ ((pair2[1,2] - pair2[2,2]) * (pair2[1,2] - pair2[2,2]))
  )

  rm(pair2)

}

plot(ff[,1], ff[,2], xlab="Principal 1", ylab="Principal 2", type = "n", las = 1)

for(i in 1:nlevels(ff$pair)){

lines(ff[ff$pair == levels(ff$pair)[i],1], ff[ff$pair == levels(ff$pair)[i],2], col = "grey")

}

points(ff[,1], ff[,2], xlab="Coordinate 1", ylab="Coordinate 2", type = "p",
   pch = ifelse(grepl(x = substr(rownames(ff), 7,8), "V1"), 20, 18),
   cex = 1.3)
)

非常感谢您的帮助。

【问题讨论】:

  • 你能告诉我们你的问题到底出在哪里吗?你有错误吗?
  • @maeVeyable:我不确定我的代码是否有意义。我没有收到错误,但我的数字与我预期的不一样。我只得到 8 个数据点而不是 12 个,所以我认为有问题。似乎不包括第三次访问......而且我希望每个访问点的颜色不同(但在所有个体中保持一致)。我还希望将每个人的三个访问点通过一条线连接起来。
  • 其实所有的点都画好了。只是有些点坐标相同。

标签: r multi-dimensional-scaling


【解决方案1】:

我建议您修改您的 data.frame,以便使用 sapply 函数为 visit numberindiv id 添加一列.

ff$visit <- sapply(ff$pair,function(x){substr(x,5,5)})
ff$indiv <- sapply(ff$pair,function(x){substr(x,3,3)})

然后库 ggplot2 对绘制数据非常有用。首先,你画点:

g <- ggplot(ff,aes(V1,V2))+geom_point(aes(color=visit)) 

然后为每个人添加行:

for (i in unique(ff$indiv)){
 g <- g+geom_line(data=ff[ff$indiv==i,],aes(V1,V2))
}

【讨论】:

  • 非常感谢所有有用的建议!
猜你喜欢
  • 1970-01-01
  • 2012-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多