Skip to content Skip to sidebar Skip to footer

R Shiny + Plotly : Change Color Of A Trace With Javascript Without Affecting Markers And Legend In Multiple Plots

This is a follow up question based on THIS post. The demo app here is a closer representation of my more complex situation of my real shiny app that I'm trying to improve by repl

Solution 1:

I'm lost :) Let's start. Here is an app allowing to change the marker size:

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)

And here is an app allowing to change the marker color:

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)

Does it help?

Solution 2:

With shiny, you can use color=~get(input$XXX). Here's an example with my own code:

fig = plot_mapbox()# POLYGONS
fig = fig %>% add_sf(
  data=districts,
  split=~DISTRICT,
  color=~log10(get(input$multi_indicator_districts.selectors.colorBy)))# POINTS
fig = fig %>% add_trace(
  type='scatter',
  data=facilities,
  x=~longitude,
  y=~latitude,
  split=~tier)
fig = fig %>% layout(
  mapbox=list(
    zoom=4,
    style='open-street-map'))

enter image description here

Post a Comment for "R Shiny + Plotly : Change Color Of A Trace With Javascript Without Affecting Markers And Legend In Multiple Plots"