【发布时间】:2018-06-14 17:48:20
【问题描述】:
我正在使用R 的plotly 绘制5 个x,y 数据集群。
以下是数据:
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)))
这是他们的plotly 散点图:
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))
然后,按照@Marco Sandri 的answer,我使用以下代码添加包围这些集群的多边形:
多边形代码:
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 <- 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', inherit = FALSE)
这给出了:
虽然这很好用,但不幸的是它消除了添加多边形之前存在的hoverinfo,现在只是每个多边形的痕迹。
将inherit 从FALSE 更改为TRUE 会导致我写的关于in that post 的错误。所以我的问题是如何在不改变原始图的hoverinfo 的情况下添加多边形。
【问题讨论】:
-
多边形隐藏了下面的信息。也许您可以重新绘制标记: clusters.plot %>% add_markers(x=~df$x,y=~df$y, showlegend = FALSE)
-
hoverinfo 已恢复,但现在除了多边形之外,所有点都由线连接。
-
尝试将
hoverinfo="none"设置为add_polygon调用 -
这只是消除了“trace #of cluster”悬停信息,但没有恢复点的悬停信息。
-
为什么不在标记之前绘制多边形?
polygons.df也没有正确定义,你错过了一些代码行。