R Shiny + plotly:使用 javascript 更改轨迹颜色而不影响多个图中的标记和图例

标记

这是基于这篇文章的后续问题

这里的演示应用程序是我的我真正的更复杂的情况更紧密的表示shiny app,我试图通过更换代码,原因重新改善renderingplotly被物体javascript能够改变现有的代码plots

这个程序有:
- 4个地块具有独特的ID's
-套的2plots听同组的colourInputs每一个,1trace每个plot
-中legendmarker size所有plots链接到numericInputs

的修改javascript从该解决方案对前一个问题将需要:
-跟随size inputs
-跟随trace-colourInput连接
-目标跟踪n2plots基于colourInput n属于那些2 plots

编辑:稍微简化的场景让我们暂时放弃图例问题,因为 Stephane 的解决方案第 2 部分做了我想要的颜色。稍后我将处理图例尺寸。

修改后的版本可能会更清晰一些。javascript应:
如果情节ID为“ plot1”或“ plot2”听color-set1-1,直到-3
如果情节ID是“ plot3”或“ plot4”,利斯特到color-set2-1钱柜-3

我想我们需要一些来添加一些js类似的行:“

"var setnr = parseInt(id.split('-')[1]) ;",

查看我们正在查看哪一组按钮,然后是一个 if 语句,它实现了:

 if 'setnr'  == set1 , then var plots =  plot1, plot2
    else if 'setnr == set2, then var plots = plot3, plot4
and then update the trace in 'plots'

在新应用中,color-set1-1、color-set1-2、color-set1-3 仍然针对所有 4 个地块。

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

js <- c(
  "function(el,x){",
  "  $('[id^=Color]').on('change', function(){",
  "    var color = this.value;",
  "    var id = this.id;",
  "    var index = parseInt(id.split('-')[1]) - 1;",
  "    var data = el.data;",
  "    var marker = data[index].marker;",
  "    marker.color = color;",
  "    Plotly.restyle(el, {marker: marker}, [index]);",
  "  });",
  "}")

ui <- fluidPage(
  fluidRow(
    column(4,plotlyOutput("plot1")),
    column(4,plotlyOutput("plot2")),
    column(4,
    colourInput("Color-1", "Color item 1", value = "blue"),  # these buttons will become named Color-set1-1, Color-set1-2, Color-set1-3
    colourInput("Color-2", "Color item 2", value = "red"),  # but that requires an extra change to the js
    colourInput("Color-3", "Color item 3", value = "green")
  )
    ),
  fluidRow(
    column(4,plotlyOutput("plot3")),
    column(4,plotlyOutput("plot4")),
    column(4,
           colourInput("Color-set2-1", "Color item 1", value = "blue"),
           colourInput("Color-set2-2", "Color item 2", value = "red"),
           colourInput("Color-set2-3", "Color item 3", value = "green")
    )
  )

)

server <- function(input, output, session) {
  values <- reactiveValues(colors1 = c('red', 'blue', 'black'), colors2 = c('yellow', 'blue', 'green')  )

  myplotly <- function(THEPLOT, xvar, setnr) {
    markersize <- input[[paste('markersize', THEPLOT, sep = '_')]] 
    markerlegendsize <- input[[paste('legendsize', THEPLOT, sep = '_')]]
    colors <- isolate ({values[[paste('colors', setnr, sep = '')]]  })
    p <- plot_ly(source = paste('plotlyplot', THEPLOT, sep = '.'))
    p <-  add_trace(p, data = mtcars, x = mtcars[[xvar]], y = ~mpg, type = 'scatter', mode = 'markers', color = ~as.factor(cyl), colors = colors)
    p <- layout(p, title = 'mtcars group by cyl with switching colors')
    p <- plotly_build(p) 
    p  %>% onRender(js)
    } 

  output$plot1 <- renderPlotly({ myplotly('plot1', 'hp', 1) })
  output$plot2 <- renderPlotly({ myplotly('plot2', 'disp', 1)})
  output$plot3 <- renderPlotly({ myplotly('plot3','hp', 2)})
  output$plot4 <- renderPlotly({ myplotly('plot4', 'disp', 2)})

}

shinyApp(ui, server)

原版APP:

library(plotly)
library(shiny)
library(htmlwidgets)
library(colourpicker)
library(shinyjs)

## javascript from previous question's answer:
jsCode <- "shinyjs.changelegend = function(){
var paths = d3.select('#plot1').
select('.legend').
select('.scrollbox').
selectAll('.traces').
select('.scatterpts')
.attr('d','M8,0A8,8 0 1,1 0,-8A8,8 0 0,1 8,0Z');}"

ui <- fluidPage(
  tags$script(src = "https://d3js.org/d3.v4.min.js"),
  useShinyjs(),
  extendShinyjs(text = jsCode),
  fluidRow(
    column(2,numericInput(inputId = 'markersize_plot1', label = 'marker', min = 1, max = 40, value = 20)),
    column(2,numericInput(inputId = 'legendsize_plot1', label = 'legend', min = 1, max = 40, value = 10)),
    column(2,numericInput(inputId = 'markersize_plot2', label = 'marker', min = 1, max = 40, value = 4)),
    column(2,numericInput(inputId = 'legendsize_plot2', label = 'legend', min = 1, max = 40, value = 20))
  ),
  fluidRow(
    column(4,plotlyOutput("plot1")),
    column(4,plotlyOutput("plot2")),
    column(2,uiOutput('buttons_color_1'))
  ),
fluidRow(
  column(2,numericInput(inputId = 'markersize_plot3', label = 'marker', min = 1, max = 40, value = 10)),
  column(2,numericInput(inputId = 'legendsize_plot3', label = 'legend', min = 1, max = 40, value = 30)),
  column(2,numericInput(inputId = 'markersize_plot4', label = 'marker', min = 1, max = 40, value = 7)),
  column(2,numericInput(inputId = 'legendsize_plot4', label = 'legend', min = 1, max = 40, value = 40))
),
  fluidRow(
    column(4,plotlyOutput("plot3")),
    column(4,plotlyOutput("plot4")),
    column(2,uiOutput('buttons_color_2'))
    )
)


server <- function(input, output, session) {
  values <- reactiveValues(colors1 = c('red', 'blue', 'black'), colors2 = c('yellow', 'blue', 'green')  )


  lapply(c(1:2), function(i) {
  output[[paste('buttons_color_', i,sep = '')]] <- renderUI({
    isolate({ lapply(1:3, function(x) {  ## 3 in my app changes based on clustering output of my model
      Idname <- if(i == 1) { COLElement_1(x) } else {COLElement_2(x) }
      div(colourpicker::colourInput(inputId = Idname, label = NULL,
                                    palette = "limited", allowedCols = TheColors,
                                    value = values[[paste('colors', i, sep = '')]][x],
                                    showColour = "background", returnName = TRUE),
          style = " height: 30px; width: 30px; border-radius: 6px;  border-width: 2px; text-align:center; padding: 0px; display:block; margin: 10px")
    })
    })})

  outputOptions(output, paste('buttons_color_', i,sep = ''), suspendWhenHidden=FALSE)
  })


  COLElement_1 <-    function(idx){sprintf("COL_button_1-%d",idx)}
  lapply(1:3, function(ob) { 
  COLElement_1 <- COLElement_1(ob)
  observeEvent(input[[COLElement_1]], {
    values[[paste('colors', 1, sep = '')]][ob] <- input[[COLElement_1]]
    plotlyProxy("plot1", session) %>%
      plotlyProxyInvoke("restyle", list(marker = list(color = input[[COLElement_1]])), list(as.numeric(ob)-1))
    plotlyProxy("plot2", session) %>%
      plotlyProxyInvoke("restyle", list(marker = list(color = input[[COLElement_1]])), list(as.numeric(ob)-1))
  })  
  })

  COLElement_2 <-    function(idx){sprintf("COL_button_2-%d",idx)}
  lapply(1:3, function(ob) { 

  COLElement_2 <- COLElement_2(ob)
  observeEvent(input[[COLElement_2]], {
    values[[paste('colors', 2, sep = '')]][ob] <- input[[COLElement_2]]
    plotlyProxy("plot3", session) %>%
      plotlyProxyInvoke("restyle", list(marker = list(color = input[[COLElement_2]])), list(as.numeric(ob)-1))
    plotlyProxy("plot4", session) %>%
      plotlyProxyInvoke("restyle", list(marker = list(color = input[[COLElement_2]])), list(as.numeric(ob)-1))
  })
  })

  myplotly <- function(THEPLOT, xvar, setnr) {
    markersize <- input[[paste('markersize', THEPLOT, sep = '_')]] 
    markerlegendsize <- input[[paste('legendsize', THEPLOT, sep = '_')]]
    colors <- isolate ({values[[paste('colors', setnr, sep = '')]]  })
    p <- plot_ly(source = paste('plotlyplot', THEPLOT, sep = '.'))
    p <-  add_trace(p, data = mtcars, x = mtcars[[xvar]], y = ~mpg, type = 'scatter', mode = 'markers', color = ~as.factor(cyl), colors = colors)
    p <- layout(p, title = 'mtcars group by cyl with switching colors')
    p <- plotly_build(p) 


    # this is a bit of a hack to change the size of the legend markers to not be equal to the plot marker size.
    # it makes a list of 1 size value for each marker in de trace in the plot, and another half of with sizes that are a lot bigger.
    # the legend marker size is effectively the average size of all markers of a trace
    for(i in seq(1, length(sort(unique(mtcars$cyl) )))) {
      length.group <- nrow(mtcars[which(mtcars$cyl  == sort(unique(mtcars$cyl))[i]), ])
      p$x$data[[i]]$marker$size <- c(rep(markersize,length.group), rep(c(-markersize+2*markerlegendsize), length.group))
    }
    p
  } 



output$plot1 <- renderPlotly({ myplotly('plot1', 'hp', 1) })
output$plot2 <- renderPlotly({ myplotly('plot2', 'disp', 1)})
output$plot3 <- renderPlotly({ myplotly('plot3','hp', 2)})
output$plot4 <- renderPlotly({ myplotly('plot4', 'disp', 2)})
}

shinyApp(ui, server)
斯蒂芬·洛朗

我迷路了 :) 让我们开始吧。这是一个允许更改标记大小的应用程序:

library(plotly)
library(shiny)

js <- paste(c(
  "$(document).ready(function(){",
  "  $('#size').on('change', function(){",
  "    var size = Number(this.value);",
  "    var plot = document.getElementById('plot');",
  "    var data = plot.data;",
  "    $.each(data, function(index,value){",
  "      var marker = data[index].marker;",
  "      marker.size = size;",
  "      Plotly.restyle(plot, {marker: marker}, [index]);",
  "    });",
  "  });",
  "})"), sep = "\n")

ui <- fluidPage(
  tags$head(
    tags$script(HTML(js))
  ),
  plotlyOutput("plot"),
  numericInput("size", "Size", value = 5, min = 1, max = 15)
)

server <- function(input, output, session) {

  output$plot <- renderPlotly({
    p <- plot_ly()
    for(name in c("drat", "wt", "qsec"))
    {
      p <- add_markers(p, x = as.numeric(mtcars$cyl), y = as.numeric(mtcars[[name]]), name = name)
    }
    p 
  })

}

shinyApp(ui, server)

这是一个允许更改标记颜色的应用程序:

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

js <- c(
  "function(el,x){",
  "  $('[id^=Color]').on('change', function(){",
  "    var color = this.value;",
  "    var id = this.id;",
  "    var index = parseInt(id.split('-')[1]) - 1;",
  "    var data = el.data;",
  "    var marker = data[index].marker;",
  "    marker.color = color;",
  "    Plotly.restyle(el, {marker: marker}, [index]);",
  "  });",
  "}")

ui <- fluidPage(
  plotlyOutput("plot"),
  colourInput("Color-1", "Color item 1", value = "blue"),
  colourInput("Color-2", "Color item 2", value = "red"),
  colourInput("Color-3", "Color item 3", value = "green")
)

server <- function(input, output, session) {

  output$plot <- renderPlotly({
    p <- plot_ly()
    for(name in c("drat", "wt", "qsec"))
    {
      p <- add_markers(p, x = as.numeric(mtcars$cyl), y = as.numeric(mtcars[[name]]), name = name)
    }
    p %>% onRender(js)
  })

}

shinyApp(ui, server)

它有帮助吗?

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

在R Shiny中使用Plotly进行多级钻取

来自分类Dev

使用R的bsplus,Shiny和JavaScript停止轮播自动播放

来自分类Dev

Plotly R:使用颜色和线图变换

来自分类Dev

R和Shiny:使用反应函数的输出

来自分类Dev

R和Shiny:使用反应函数的输出

来自分类Dev

在 R plotly 散点图中发出更改标记颜色的问题

来自分类Dev

R:饼图中使用 Plotly 的下标

来自分类Dev

使用Plotly和R的悬停模式

来自分类Dev

如何使用R的plotly更改条形图中的配色方案?

来自分类Dev

如何在Shiny中使用Javascript更改音量?

来自分类Dev

使用If使用Shiny R处理输入和别名

来自分类Dev

R使用CSS和模式对话框使用Shiny

来自分类Dev

R / Shiny中的Plain Dygraphs JavaScript选项

来自分类Dev

R / Shiny中的Plain Dygraphs JavaScript选项

来自分类Dev

在R Shiny中的多个模块中使用reactValues

来自分类Dev

使用多个变量在R Shiny中子集数据

来自分类Dev

R Shiny:使用多个输入源进行更新

来自分类Dev

使用R Studio取消Shiny / Flexdashboard的空白元素和问题

来自分类Dev

使用Shiny R获取和显示文件名

来自分类Dev

图表未使用Shiny R和NVD3呈现

来自分类Dev

在 R 中使用 ggplot 和 Shiny 制作条形图

来自分类Dev

使用R plotly下拉菜单选择变量,并保持使用颜色变量作为轨迹

来自分类Dev

R Shiny:如何更改页眉的背景颜色?

来自分类Dev

R Shiny:如何更改表格的背景颜色

来自分类Dev

在R Shiny中更改通知的颜色

来自分类Dev

更改R Shiny中selectizeInput选项的颜色

来自分类Dev

在 R 和 plotly 中使用 plotly_click 更新多个信息框

来自分类Dev

R Shiny中的多个图

来自分类Dev

R Shiny renderTable-如何更改边框的宽度和颜色

Related 相关文章

热门标签

归档