这跟进了这篇文章。
我有 xy 数据,我想生成散点图以供使用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),z=rnorm(50,mean=i,sd=1),cluster=i)))
data.frame
使用多边形的坐标创建 a :
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)))
我想在我用df$z
值着色点的地方绘制它,但我还想修改colorbar
.
这就是我正在尝试的
df$cluster <- ordered(as.factor(df$cluster))
clusters <- unique(df$cluster)
clusters.plot <- plot_ly()
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,
name = paste0("Cluster ",l),
colors=grDevices::colorRamp(c("darkblue","white","darkred")),
line=list(width=2,color="black"),
fillcolor='transparent',
hoverinfo = "none",
showlegend = FALSE,
inherit = FALSE)
clusters.plot <- clusters.plot %>%
add_trace(data=df, x= ~x,y= ~y,color= ~z, colors=grDevices::colorRamp(c("darkblue","white","darkred")),
type='scatter',mode="markers",
marker=list(size=10)) %>%
layout(xaxis=list(title="X",
zeroline=F),
yaxis=list(title="Y",
zeroline=F)) %>% colorbar(limits=c(min(df$z),max(df$z)),len=0.4,title="my legend")
问题是多边形变成点而不是线,因为clusters.plot
在添加点之前,跟踪是:
这只发生在
colorbar(limits=c(min(df$z),max(df$z)),len=0.4,title="my legend")
所以我的问题是如何在不影响多边形的情况下编辑图例的标题?