这最后是this post。
我有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
:
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")
所以我的问题是如何在不影响多边形的情况下编辑图例的标题?