我有一个闪亮的应用程序,其中用户可以使用 Plotly “框选择”图标在 Plotly 散点图中选择黑点。用户选择的点将以红色突出显示。我在下面有这个应用程序的 MWE:
library(plotly)
library(htmlwidgets)
library(shiny)
ui <- shinyUI(fluidPage(
plotlyOutput("myPlot")
))
server <- shinyServer(function(input, output) {
p <- ggplot(mtcars, aes(x = wt, y = mpg)) + xlim(10,40) +ylim(0,10)
ggPS <- ggplotly(p)
output$myPlot <- renderPlotly(ggPS %>%
onRender("
function(el, x, data) {
var xArr = [];
var yArr = [];
for (a=0; a<data.wt.length; a++){
xArr.push(data.wt[a])
yArr.push(data.mpg[a])
}
Traces=[]
var tracePoints = {
x: yArr,
y: xArr,
hoverinfo: 'none',
mode: 'markers',
marker: {
color: 'black',
size: 4
}
};
Traces.push(tracePoints);
Plotly.addTraces(el.id, Traces);
el.on('plotly_selected', function(e) {
var numSel = e.points.length
var xSel = [];
var ySel = [];
for (a=0; a<numSel; a++){
xSel.push(e.points[a].x)
ySel.push(e.points[a].y)
}
var trace = {
x: xSel,
y: ySel,
mode: 'markers',
marker: {
color: 'red',
size: 4
},
hoverinfo: 'none'
};
Traces.push(trace);
Plotly.addTraces(el.id, Traces);
})
}
", data = list(dat= mtcars, wt=mtcars$wt, mpg=mtcars$mpg)))})
shinyApp(ui, server)
我现在正在尝试更新这个闪亮的应用程序,以便选定的黑点不会自动变成红色。相反,在用户选择黑点后,他们可以单击带有“突出显示选定点”标签的操作按钮。如果用户单击该操作按钮,则所选点变为红色。下面是我试图让它发挥作用的尝试。不幸的是,此应用程序无法正常工作,实际上失去了绘制原始黑点和首先提供框选择图标的功能。
library(plotly)
library(Shiny)
library(htmlwidgets)
ui <- shinyUI(fluidPage(
plotlyOutput("myPlot"),
actionButton("highlight", "Highlight selected points")
))
server <- shinyServer(function(input, output) {
highlight <- reactive(input$highlight)
p <- ggplot(mtcars, aes(x = wt, y = mpg)) + xlim(10,40) +ylim(0,10)
ggPS <- ggplotly(p)
output$myPlot <- renderPlotly(ggPS %>%
onRender("
function(el, x, data) {
var xArr = [];
var yArr = [];
for (a=0; a<data.wt.length; a++){
xArr.push(data.wt[a])
yArr.push(data.mpg[a])
}
Traces=[]
var tracePoints = {
x: yArr,
y: xArr,
hoverinfo: 'none',
mode: 'markers',
marker: {
color: 'black',
size: 4
}
};
Traces.push(tracePoints);
Plotly.addTraces(el.id, Traces);
el.on('plotly_selected', function(e) {
observeEvent(data.highlightS, {
var numSel = e.points.length
var xSel = [];
var ySel = [];
for (a=0; a<numSel; a++){
xSel.push(e.points[a].x)
ySel.push(e.points[a].y)
}
var trace = {
x: xSel,
y: ySel,
mode: 'markers',
marker: {
color: 'red',
size: 4
},
hoverinfo: 'none'
};
Traces.push(trace);
Plotly.addTraces(el.id, Traces);
})
})
}
", data = list(dat= mtcars, wt=mtcars$wt, mpg=mtcars$mpg, highlightS=highlight())))})
shinyApp(ui, server)
编辑:
我想包括一张图片来展示我的目标。基本上,如果用户选择下面显示的 15 个点,它们将保持黑色:
但是,如果用户选择“突出显示所选点”闪亮按钮,则 15 个点将变为红色,如下所示: