This follows up to this post.
I have xy data I'd like to generate a scatter plot for using plotly
. I want to have polygons surrounding clusters of the points.
Data:
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)))
Creating a data.frame
with the coordinates of the polygons:
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)))
I want to plot it all where I color the points by the df$z
values but I'd also like to modify the title of the colorbar
.
Here's what I'm trying
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")
The problem is that the polygons become points rather than lines, as clusters.plot
before adding the points trace is:
This happens only when the
colorbar(limits=c(min(df$z),max(df$z)),len=0.4,title="my legend")
So my question is how can I edit the legend's title without affecting the polygons?