我正在按照此示例创建要绘制的多边形,ggplot
如果我的数据被子集化,我可以按照该示例创建单独的凸包;但是,当我尝试申请时ddply
,因为我有一个分组变量,我无法申请。这是示例中的代码,其中添加了分组变量:
library(grDevices) # load grDevices package
df <- data.frame(X = c(-62, -40, 9, 13, 26, 27, 27),
Y = c( 7, -14, 10, 9, -8, -16, 12), id = c(1, 1, 1, 2, 2, 3, 3))
con.hull.pos <- ddply(df, .(id), summarize, hullpos = chull(X, Y)) # get convex hull positions by each ID
现在,要为每个 ID 获取完整的多边形,我们需要按照给出的每个 ID 获取所有行,con.hull.pos
但我们还需要添加每个组的第一行。
df[ddply(con.hull.pos, .(id), function(x) x[1, ])$hullpos, ] # first row of position
df[con.hull.pos$hullpos ,] ## all rows of position
rbind(df[con.hull.pos$hullpos ,] , df[ddply(con.hull.pos, .(id), function(x) x[1, ])$hullpos, ])
在这里我的代码失败,因为使用 ddply 的第一行与 ID 的凸包的第一行不同。因此,多边形是不完整的。任何人都可以通过按变量分组来帮助我应用给定的示例。
手动设置子集时,此代码会创建三个单独的多边形,覆盖三个 id 区域
id1_df <- subset(df, id==1)
id1_con.hull.pos <- chull(id1_df$X, id1_df$Y)
id2_df <- subset(df, id==2)
id2_con.hull.pos <- chull(id2_df$X, id2_df$Y)
id3_df <- subset(df, id==3)
id3_con.hull.pos <- chull(id3_df$X, id3_df$Y)
id1_con.hull <- rbind(id1_df[id1_con.hull.pos,], id1_df [id1_con.hull.pos[1],])
id2_con.hull <- rbind(id2_df [id2_con.hull.pos ,], id2_df [id2_con.hull.pos [1],])
id3_con.hull <- rbind(id3_df [id3_con.hull.pos,], id3_df [id3_con.hull.pos[1],])
poly_borders <- rbind(id1_con.hull, id2_con.hull, id3_con.hull)
plot(Y ~ X, data = df) # plot data
lines(poly_borders) # add lines for convex hull