This is a slightly different approach (with the same goal) as a post I added four days ago (Possible to shade between 4 line traces that form a box?).
Basically, I am trying to create an application where if a user uses Box Select tool in Plotly, then a filled rectangle will appear alongside the Box Select. In the previous post, I attempted to accomplish this by calling Plotly.addTrace() four times to create the four edges of the rectangle. However, I am now trying to call Plotly.addTrace() once to create a rectangle object (type: rect).
I based some of the syntax off a post about Python Plotly (https://plot.ly/python/shapes/). However, I am working with Plotly in R. Is there any similar rectangle object that I could use in Plotly R?
Below is MWE showing my code.
library(ggplot2)
library(shiny)
library(plotly)
library(htmlwidgets)
ui <- basicPage(
plotlyOutput(“plot1”)
)
server <- function(input, output) {
p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point(alpha=0) + xlim(0,5) +ylim(-3,3)
gp <- ggplotly§
set.seed(3)
pcpDat <- data.frame(ID = paste0(“ID”,1:10), A=rnorm(10,-1), B=rnorm(10,-1), C=rnorm(10,-1), D=rnorm(10,1), E=rnorm(10,1), F=rnorm(10,1))
pcpDat$ID <- as.character(pcpDat$ID)
colNms <- colnames(pcpDat[, c(2:(ncol(pcpDat)))])
nVar <- length(colNms)
output$plot1 <- renderPlotly({
gp %>% onRender("
function(el, x, data) {
var pcpDat = data.pcpDat
function range(start, stop, step){
var a=[start], b=start;
while(b<stop){b+=step;a.push(b)}
return a;
};
var Traces = [];
var dLength = pcpDat.length
var vLength = data.nVar
var cNames = data.colNms
for (a=0; a<dLength; a++){
xArr = [];
yArr = [];
for (b=0; b<vLength; b++){
xArr.push(b)
yArr.push(pcpDat[a][cNames[b]]);
}
var pcpLine = {
x: xArr,
y: yArr,
mode: 'lines',
line: {
color: 'orange',
width: 1
},
opacity: 0.9,
}
Traces.push(pcpLine);
}
Plotly.addTraces(el.id, Traces);
el.on('plotly_selected', function(e) {
var dLength = pcpDat.length
var selectedPCP = []
var xMin = e.range.x[0]
var xMax = e.range.x[1]
var yMin = e.range.y[0]
var yMax = e.range.y[1]
console.log([xMin, xMax, yMin, yMax])
var Traces = []
var drawRect = {
type: 'rect',
x0: xMin,
y0: yMin,
x1: xMax,
y1: yMax,
line: {
color: 'green',
width: 1
},
fillcolor: 'green'
}
Traces.push(drawRect);
Plotly.addTraces(el.id, Traces);
})
}", data = list(pcpDat = pcpDat, nVar = nVar, colNms = colNms))})
}
shinyApp(ui, server)