以绘图方式将多边形添加到散点图 [英] Adding a polygon to a scatter plotly

查看:69
本文介绍了以绘图方式将多边形添加到散点图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Rplotly绘制了5个x,y数据簇.

I have 5 clusters of x,y data I'm plotting using R's plotly.

以下是数据:

set.seed(1)
df <- do.call(rbind,lapply(seq(1,20,4),function(i) data.frame(x=rnorm(50,mean=i,sd=1),y=rnorm(50,mean=i,sd=1),cluster=i)))

这是情节:

library(plotly)
clusters.plot <- plot_ly(marker=list(size=10),type='scatter',mode="markers",x=~df$x,y=~df$y,color=~df$cluster,data=df) %>% hide_colorbar() %>% layout(xaxis=list(title="X",zeroline=F),yaxis=list(title="Y",zeroline=F))

clusters.plot

现在,我在每个群集周围创建多边形:

Now I'm creating polygons around each cluster:

#helper functions:
library(data.table)
library(grDevices)

splinesPolygon <- function(xy,vertices,k=3, ...)
{
  # Assert: xy is an n by 2 matrix with n >= k.
  # Wrap k vertices around each end.
  n <- dim(xy)[1]
  if (k >= 1) {
    data <- rbind(xy[(n-k+1):n,], xy, xy[1:k, ])
  } else {
    data <- xy
  }
  # Spline the x and y coordinates.
  data.spline <- spline(1:(n+2*k), data[,1], n=vertices, ...)
  x <- data.spline$x
  x1 <- data.spline$y
  x2 <- spline(1:(n+2*k), data[,2], n=vertices, ...)$y
  # Retain only the middle part.
  cbind(x1, x2)[k < x & x <= n+k, ]
}

clustersPolygon <- function(df)
{
  dt <- data.table::data.table(df)
  hull <- dt[,.SD[chull(x,y)]]
  spline.hull <- splinesPolygon(cbind(hull$x,hull$y),100)
  return(data.frame(x=spline.hull[,1],y=spline.hull[,2],stringsAsFactors=F))
}

library(dplyr)
polygons.df <- do.call(rbind,lapply(unique(df$cluster),function(l) clustersPolygon(df=dplyr::filter(df,cluster == l)) %>% dplyr::rename(polygon.x=x,polygon.y=y) %>% dplyr::mutate(cluster=l)))

现在我想将它们添加到clusters.plot.

And now I want to add them to clusters.plot.

我认为这样做可以:

clusters <- unique(df$cluster)
for(l in clusters) clusters.plot <- clusters.plot %>% add_polygons(x=dplyr::filter(polygons.df,cluster == l)$polygon.x,y=dplyr::filter(polygons.df,cluster == l)$polygon.y,line=list(width=2,color="black"),fillcolor='transparent')

但是我遇到了这个错误:

But I'm getting this error:

Error: Columns `x`, `y` must be length 1 or 250, not 54, 54

250nrow(df)54nrow(dplyr::filter(polygonss.df,cluster == 1))

有什么主意吗?

推荐答案

尝试一下:

for(l in clusters) clusters.plot <- clusters.plot %>% 
 add_polygons(x=dplyr::filter(polygons.df,cluster == l)$polygon.x,
              y=dplyr::filter(polygons.df,cluster == l)$polygon.y,
              line=list(width=2,color="black"),
              fillcolor='transparent', inherit = FALSE)

这篇关于以绘图方式将多边形添加到散点图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆