Black Lives Matter. Please consider donating to Black Girls Code today.
Learn how to use COVID-19 data in open source Dash apps. Register for the Sept 23rd webinar with IQT!

Plotly.addTraces() works but then erases when user clicks on Plotly menu icons

I am working on creating a Plotly image in the onRender() function of the htmlwidgets R package. I have a matrix of plots. I use Plotly.addTraces() to add points to the subplots in the lower-left diagonal of the matrix. My MWE appears to be working below - except that when the user selects some of the Plotly icons in the top-right of the Plotly output (such as Box Select, Lasso Select, Home Icon, etc), it seems to delete the traces in the lower-left diagonal of the matrix.

Any ideas on what might be causing this and/or how I can attempt to solve it? Thank you!

library(plotly)
library(GGally)
library(htmlwidgets)

set.seed(1)
dat <- data.frame(ID = paste0(“ID”,1:10), A=rnorm(10), B=rnorm(10), C=rnorm(10), D=rnorm(10))
dat$ID <- as.character(dat$ID)

minVal = min(dat[,-1])
maxVal = max(dat[,-1])

my_fn <- function(data, mapping, …){
x = data[,c(as.character(mapping$x))]
y = data[,c(as.character(mapping$y))]
p <- ggplot(data = dat, aes(x=x, y=y)) + coord_cartesian(xlim = c(minVal, maxVal), ylim = c(minVal, maxVal))
p
}

p <- ggpairs(dat[,-1], lower = list(continuous = my_fn))

ggPS <- ggplotly§

myLength <- length(ggPS[[“x”]][[“data”]])
for (i in 1:myLength){
item =ggPS[[“x”]][[“data”]][[i]]$text[1]
if (!is.null(item))
if (!startsWith(item, “co”)){
ggPS[[“x”]][[“data”]][[i]]$hoverinfo <- “none”
}
}

ggplotly(ggPS) %>%
onRender(“
function(el, x, data) {
len = Math.sqrt(document.getElementsByClassName(‘cartesianlayer’)[0].childNodes.length);
AxisNames = [];
for (i = 1; i < (len+1); i++) {
AxisNames.push(document.getElementsByClassName(‘infolayer’)[0].childNodes[i].textContent);
}
noPoint = x.data.length;
var Traces = [];
var i=0;
var k=1;
while ((ilen+k)<=Math.pow((len-1),2)) {
while ((i+k)<len){
var selRows = [];
data.forEach(function(row){
if(Math.abs(row[AxisNames[i]]-row[AxisNames[(len-k)]]) > 1.4) selRows.push(row);});
var xArr = [];
for (a=0; a<selRows.length; a++){
xArr.push(selRows[a][AxisNames[i]])
}
var yArr = [];
for (a=0; a<selRows.length; a++){
yArr.push(selRows[a][AxisNames[(len-k)]])
}
var tracePoints = {
x: xArr,
y: yArr,
hoverinfo: ‘none’,
mode: ‘markers’,
marker: {
color: ‘black’,
size: 4
},
xaxis: ‘x’ + (i+1),
yaxis: ‘y’ + (i
len+k)
};
Traces.push(tracePoints);
k++;
}
i++;
k=1;
}
Plotly.addTraces(el.id, Traces);
}
”, data = dat)

Hmm strange.

If you could try to replicate the problem in plain JS this would help us help you immensely. Thanks.

Thanks for the comment. I believe everything in the onRender() function is plain JS, but perhaps I am wrong about that? I am uncertain how to approach recreating the ggPS object in plain JS. The ggPS object is constructed using R packages with some pretty long functionality.