Reputation: 57
I am trying to work on creating the graph using plotly. When the user clicks on any geom_point in the plot using R shiny, it should change the color and keep it unchanged.
Currently, my code is working fine. When the user clicks on any geom_point in the plot, it is changing the color. But when I click on another geom_point, the previous point which was highlighted goes back to its original color.
library(shiny)
library(plotly)
library(htmlwidgets)
ui <- fluidPage(
plotlyOutput("plot")
)
javascript <- "
function(el, x){
el.on('plotly_click', function(data) {
colors = [];
var base_color = document.getElementsByClassName('legendpoints')[data.points[0].curveNumber].getElementsByTagName('path')[0].style['stroke']
for (var i = 0; i < data.points[0].data.x.length; i += 1) {
colors.push(base_color)
};
colors[data.points[0].pointNumber] = '#FF00FF';
Plotly.restyle(el,
{'marker':{color: colors}},
[data.points[0].curveNumber]
);
});
}"
server <- function(input, output, session) {
nms <- row.names(mtcars)
output$plot <- renderPlotly({
p <- ggplot(mtcars, aes(x = mpg, y = wt, col = as.factor(cyl), key = nms)) +
geom_point()
ggplotly(p) %>% onRender(javascript)
})
}
shinyApp(ui, server)
I expect when the user clicks on any geom_point, it should change the color and that color should remain until he closes the shiny app. the color should not return to its original color. Maybe there is a minor change to be made to the Javascript function. Thanks!
Upvotes: 3
Views: 1121
Reputation: 466
The problem is that you always set all point to the base color instead of check which color actual points have. I am no javascript expert but this works for me:
library(shiny)
library(plotly)
library(htmlwidgets)
ui <- fluidPage(
plotlyOutput("plot")
)
javascript <- "
function(el, x){
el.on('plotly_click', function(data) {
var colors = [];
// check if color is a string or array
if(typeof data.points[0].data.marker.color == 'string'){
for (var i = 0; i < data.points[0].data.marker.color.length; i++) {
colors.push(data.points[0].data.marker.color);
}
} else {
colors = data.points[0].data.marker.color;
}
// some debugging
//console.log(data.points[0].data.marker.color)
//console.log(colors)
// set color of selected point
colors[data.points[0].pointNumber] = '#FF00FF';
Plotly.restyle(el,
{'marker':{color: colors}},
[data.points[0].curveNumber]
);
});
}
"
server <- function(input, output, session) {
nms <- row.names(mtcars)
output$plot <- renderPlotly({
p <- ggplot(mtcars, aes(x = mpg, y = wt, col = as.factor(cyl), key = nms)) +
geom_point()
ggplotly(p) %>% onRender(javascript)
})
}
shinyApp(ui, server)
Upvotes: 2