我正在尝试使用plotly创建图形。当用户使用R Shiny单击图中的任何geom_point时,它应该更改颜色并保持不变。
当前,我的代码运行正常。当用户单击图中的任何geom_point时,它将改变颜色。但是,当我点击另一个geom_point,这是强调前一点回到它原来的颜色。
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)
我希望当用户单击任何geom_point时,它应该更改颜色,并且该颜色应保持不变,直到他关闭闪亮的应用程序为止。颜色不应恢复为其原始颜色。可能需要对Javascript函数进行较小的更改。谢谢!
答案 0 :(得分:1)
问题在于,您始终将所有点设置为基色,而不是检查实际点具有的颜色。我不是javascript专家,但这对我有用:
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)