组中的每个成员连接到中心和r中的所有集群大中心的结构图

SHR*_*ram 12 structure r scatter-plot ggplot2

我正在尝试从以下数据创建结构图:

mydf <- data.frame ( group = rep (1:5, each = 20), z = rnorm (20, 10, 1),
                  x = c(rnorm (20, 2, 0.5), rnorm (20, 2, 0.5),
          rnorm (20, 9, 0.5), rnorm (20, 9, 0.5),rnorm (20, 5, 0.5)),
       y = c(rnorm (20, 2, 0.5), rnorm (20, 9, 0.5), rnorm (20, 2, 0.5),
      rnorm (20, 9, 0.5), rnorm (20, 2, 0.5)))

means <- aggregate(. ~ group, data = mydf, mean)
gmx <-mean (mydf$x)
gmy <- mean (mydf$y)

library(ggplot2)
ggplot(mydf, aes(x, y)) +
geom_point(aes(colour= factor (group), size=z)) + theme_bw()
Run Code Online (Sandbox Code Playgroud)

我希望将每个群集中的每个点连接到其中心,然后将群集中心连接到grad.这将产生如下的情节(只是粗略的草图,其中两个集群连接到中心,实际上所有集群都具有相同的):.........

(如果可能的话,我想使用相同颜色的线段)

在此输入图像描述

koh*_*ske 14

这是一个例子:

library(plyr)
ms <- ddply(mydf, .(group), colwise(mean))
mydf2ms <- merge(mydf, ms, by = "group")
gm <- ddply(mydf, NULL, colwise(mean))
ms2gm <- data.frame(ms, gm)

ci <- expand.grid(1:3*2, seq(0, 2*pi, length = 180))
ci <- transform(ci, x = cos(Var2) * Var1 + gm$x, y = sin(Var2) * Var1 + gm$y)

library(ggplot2)
ggplot(mydf, aes(x, y)) +
  geom_point(aes(colour= factor (group), size=z)) +
  geom_segment(data = mydf2ms, mapping = aes(x = x.x, y = y.x, xend = x.y, yend = y.y, colour = factor(group))) +
  geom_segment(data = ms2gm, mapping = aes(x = x, y = y, xend = x.1, yend = y.1)) +
  geom_point(data = ms, colour = "black", size = 10, shape = 4) +
  geom_point(data = gm, colour = "red", size = 10, shape = 4) +
  geom_path(data = ci, mapping = aes(group = Var1), colour = "pink")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 更新.你是这个意思吗? (3认同)