如何通过R Shining中的JavaScript通过通用按钮+ selectInput更改迹线n的图例状态

时间:2019-03-08 18:11:27

标签: javascript r shiny plotly r-plotly

感谢this上一个问题的答案,我开发了一个plotly plot并将其与buttons链接的legend,在其中单击{{1 }}更改每个包含legend状态的reactive variable的状态,从而重新呈现链接到每个T/F(数据组)的actionbuttons。另一个trace在相反的方向上执行相同的操作,单击javascript隐藏/显示button中的trace + legend项。

现在我希望通过新按钮+ selectinput添加另一个交互

简短的问题:
如何使您单击“一般”按钮(#0),
plot之间更改图例状态开关
对于情节j(#1)的迹线n,
其中TRUE/'legendonly'(#2)
通过在该n = input$SelectTrace上使用javascript + onclick自变量

0 actionButton在这里被称为“ SwitchExt”
1因为我有多个
,它需要定位到特定的actionButton 2 a plotly plot,将迹线作为选择

详细说明:

现在我有以下小问题: 在我的应用程序的另一个条件面板中,向用户显示了具有相同数据的一组不同的图:  -用户可以选择要突出显示的迹线,其旁边的按钮将根据T / F状态列表显示第一幅图中该迹线是否打开/关闭,然后该按钮将显示蓝色/红色,并且链接到选定的轨迹。

场景: 用户选择了第n组, 点击新的selectInput 这会触发actionButton 'SwitchExt', actionButton flipYNb_FP1(n)

YNbuttons... YNb <- YNElement(n) ....

将使按钮n更改状态。

我可以使它也更改if(values$dYNbs_cyl_el[[YNb]] == TRUE) { ,但是在我的绘图代码中,values$legenditems[n]被包装在values$legenditems中,以防止在链接isolate({ })时重新渲染绘图javascript进行更改。

解决方案的概念: 基本上,我认为我需要而不是直接更改legend列表,而是让另一values$legenditems通过{{1}链接到javascript actionButton },并以'switchExt'作为输入,然后类似于'onclick'那样更改input$SelectTrace,但随后使用legendstatus来获取javascript js1的值,将其转换为document.getElementById,然后更新input$SelectTrace

应用程序:

numeric

解决方案: 经过一些意想不到的行为的挣扎之后,我发现我需要删除switchExt-plot1的观察者,以防止按钮两次翻转。

legendstatus

可运行的应用程序是这样的:

 library(plotly)
library(shiny)
library(htmlwidgets)

## js to link buttons to legend
js1 <- c(
  "function toggleLegend(id){",
  "  var ids = id.split('-');",
  "  var plotid = ids[1];",
  "  var plot = document.getElementById(plotid);",
  "  var data = plot.data;",
  "  var v0 = data[index].visible || true;",
  "  var v = v0 == true ? 'legendonly' : true;",
  "  Plotly.restyle(plot, {visible: v}, [index]);",
  "}")

## js code to link legend to buttons
js2 <- c(
  "function(el, x, inputName){",
  "  var id = el.getAttribute('id');",
  "  var d3 = Plotly.d3;",
  "  el.on('plotly_restyle', function(evtData) {",
  "    var out = {};",
  "    d3.select('#' + id + ' g.legend').selectAll('.traces').each(function(){",
  "      var trace = d3.select(this)[0][0].__data__[0].trace;",
  "      out[trace.name] = trace.visible;",
  "    });",
  "    Shiny.setInputValue(inputName, out);",
  "  });",
  "}")



YNElement <-    function(idx){sprintf("YesNo-plot1-%d", idx)}


ui <- fluidPage(
  tags$head(
    tags$script(HTML(js1))
  ),
  fluidRow(
    column(2,
           h5("Keep/Drop choices linked to colorscheme 1"),
           uiOutput('YNbuttons')
    ),
    column(8,
           plotlyOutput("plot1")
    ),
    column(2,
           h5('Switch plot ID and shows the plot remembers the show/hide'),
           actionButton(inputId = 'Switch', label = icon('refresh'), style = "color: #f7ad6e;   background-color: white;  border-color: #f7ad6e;
                        height: 40px; width: 40px; border-radius: 6px;  border-width: 2px; text-align: center;  line-height: 50%; padding: 0px; display:block; margin: 2px"),
           br(),
           h5('New Button that does not work on legend.', style = 'font-weight:bold'),
            uiOutput('newswitch'),
           br(),
           selectInput(inputId = 'SelectTrace', label = 'Select Trace', choices = 1:3, selected = 1)
           ), style = "margin-top:150px"
    )

  )

server <- function(input, output, session) {
  values <- reactiveValues(Linked_FP1 = T, NrOfTraces = length(unique(mtcars$cyl)))

  observeEvent(input$SwitchExt, { 
    ## trying to make the user be able to switch the buttons linked to the legend on/off through another button that is in another page. 
    flipYNb_FP1(as.numeric(input$SelectTrace)) 
    req(values$legenditems)  ## don't run if legend items does not exist yet. 
    if(values$dYNbs_cyl_el[as.numeric(input$SelectTrace)]) { values$legenditems[[as.numeric(input$SelectTrace)]] <- T } else {   values$legenditems[[as.numeric(input$SelectTrace)]] <- 'legendonly' } ## problem line is here...... since I need to isolate values$legenditems in the plot code
    ## this does not actually cause the legend to change. If I don't isolate, the plot would re-render due to the change in values$legenditems, which is not what we want
  })




  output$plot1 <- renderPlotly({

    if(values$Linked_FP1) {colors <- c('red', 'blue', 'black') } else {colors <- c('black', 'orange', 'gray')}
    p1 <- plot_ly()
    p1 <-  add_trace(p1, data = mtcars, x = ~disp, y = ~mpg, type = 'scatter', mode = 'markers', color = ~as.factor(cyl), colors = colors)
    p1 <- layout(p1, title = 'mtcars group by cyl with switching colors')
    p1 <- plotly_build(p1)

   isolate({ if(values$Linked_FP1) { for(i in seq_along(p1$x$data)){   ## causes the plot to render with previous hide/show selection 
      p1$x$data[[i]]$visible <- values$legenditems[[p1$x$data[[i]]$name]]}  
    } }) ##This block is isolated because otherwise the plot will re-render when the user clicks 1 of the three buttons

    p1 %>% onRender(js2, data = "tracesPlot1")  ## add the javacode to extract the legend status
    })


  observeEvent(input$Switch, { values$Linked_FP1 <- !values$Linked_FP1    })  ## disable the link in my real app, in this dummy app it switches to plot with different id and colors that is not interactive

  observeEvent(values$NrOfTraces, { 
    values$dYNbs_cyl_el <- rep(T,values$NrOfTraces) ## the list of Yes/No status of groups, from which the 3 buttons on the left are build blue or red
    names(values$dYNbs_cyl_el) <- sapply(1:values$NrOfTraces, function(x) {YNElement(x)}) ## add names to that list
    values$legenditems <- rep(T, values$NrOfTraces)  ## make the legenditem list so that the app doesn't crash when user clicks switchExt without first clicking on legend items
    names(values$legenditems) <- sort(unique(mtcars$cyl)) ## add names to that list

  })


    output$newswitch <- renderUI({ 
    req(input$SelectTrace)
      print(input$SelectTrace)
      if(values$dYNbs_cyl_el[as.numeric(input$SelectTrace)]) { 
    actionButton(inputId = 'SwitchExt', label = icon('refresh'), style = "color: #339fff;   background-color: white;  border-color: #339fff;
                        height: 40px; width: 40px; border-radius: 6px;  border-width: 2px; text-align: center;  line-height: 50%; padding: 0px; display:block; margin: 2px", 
                 onclick = "toggleLegend(this.id);"
                 )}
    else { actionButton(inputId = 'SwitchExt', label = icon('refresh'), style = "color: #f7ad6e;   background-color: white;  border-color: #f7ad6e;
                        height: 40px; width: 40px; border-radius: 6px;  border-width: 2px; text-align: center;  line-height: 50%; padding: 0px; display:block; margin: 2px", 
                   onclick = "toggleLegend(this.id);"
                   )}
    })


  observeEvent(input$tracesPlot1, {
    if(values$Linked_FP1) {
    listTraces <- input$tracesPlot1
    values$legenditems <- listTraces  ## store the list of show/hide for when the plot re-renders here
    listTracesTF <- gsub('legendonly', FALSE, listTraces)
    listTracesTF <- as.logical(listTracesTF)
    lapply(1:values$NrOfTraces, function(el) {
      if(el <= length(listTracesTF)) {
        YNb <- YNElement(el)
        if(values$dYNbs_cyl_el[[YNb]] != listTracesTF[el]) {
          values$dYNbs_cyl_el[[YNb]] <- listTracesTF[el]
        }
      }
    })
    }
  })

  output$YNbuttons <- renderUI({
    req(values$NrOfTraces)
    lapply(1:values$NrOfTraces, function(el) {
      YNb <- YNElement(el)
      if(values$Linked_FP1) {
        if(values$dYNbs_cyl_el[[YNb]] == TRUE) {
        div(actionButton(inputId = YNb, label = icon("check"), 
                         style = "color: #339FFF;   background-color: white;  border-color: #339FFF;height: 34px; width: 34px; border-radius: 6px;  border-width: 2px; text-align: center;  line-height: 50%; padding: 0px; display:block; margin: 2px", 
                         onclick = "toggleLegend(this.id);"))
      } else {
        div(actionButton(inputId = YNb, label = icon("times"), 
                         style = "color: #ff4d4d;   background-color: white;  border-color: #ff4d4d;height: 34px; width: 34px; border-radius: 6px;  border-width: 2px; text-align: center;  line-height: 50%; padding: 0px; display:block; margin: 2px", 
                         onclick = "toggleLegend(this.id);"))
      }
      } 
    })
  }) 


  flipYNb_FP1 <- function(idx){
    YNb <- YNElement(idx)
    values$dYNbs_cyl_el[[YNb]] <- !values$dYNbs_cyl_el[[YNb]]
  }

  observe({
    lapply(1:values$NrOfTraces, function(ob) {
      YNElement <- YNElement(ob)
      observeEvent(input[[YNElement]], {
        if(!values$Linked_FP1) { flipYNb_FP1(ob) }
        }, ignoreInit = T)
    })
  })

}
shinyApp(ui, server)

图片以支持评论: enter image description here

1 个答案:

答案 0 :(得分:1)

我不确定我是否理解,但让我们从一些事情开始。

js1 <- c(
  "function toggleLegend(id){",
  "  var ids = id.split('-');",
  "  var plotid = ids[1];",
  "  var index = parseInt(ids[2])-1;",
  "  var plot = document.getElementById(plotid);",
  "  var data = plot.data;",
  "  var v0 = data[index].visible || true;",
  "  var v = v0 == true ? 'legendonly' : true;",
  "  Plotly.restyle(plot, {visible: v}, [index]);",
  "}",
  "function toggleLegend2(){",
  "  var index = parseInt($('#SelectTrace').val())-1;",
  "  var plot = document.getElementById('plot1');",
  "  var data = plot.data;",
  "  var v0 = data[index].visible || true;",
  "  var v = v0 == true ? 'legendonly' : true;",
  "  Plotly.restyle(plot, {visible: v}, [index]);",
  "}")

actionButton(inputId = 'SwitchExt', ......, onclick = "toggleLegend2()")

是您想要的吗?