0

I'm reading up on using proxies to add new series to existing charts. For a specific graph, instead of adding brand new series, I'd like to emphasize a certain point on existing one, namely by changing color, let's say to red. I didn't manage to figure out how to do it. How can I change a chart's options in such a way?

Skeleton code:

library(shiny)
library(echarts4r)


df <- data.frame(
  x = 1:5,
  y = runif(n = 1:5, min = 50, max = 200)
)

ui <- fluidPage(
  echarts4rOutput("chart"),
  actionButton("changecolor", "Change color of third bar"),
  actionButton("removecolor", "Remove color of third bar")
)

server <- function(input, output){
  
  output$chart <- renderEcharts4r({
    e_charts(df, x) |> 
      e_bar(y)
  })
  
  observeEvent(input$changecolor, {
    echarts4rProxy("chart") # What now?
      
  })
  
}

shinyApp(ui, server)
stefan
  • 90,330
  • 6
  • 25
  • 51
mkranj
  • 144
  • 8
  • If you could give a piece of code that makes an `echarts` with the different color on the third bar, I could try to make it dependant on those buttons. – David Jorquera Jun 01 '23 at 14:42
  • This answer helped me a lot, the last example: https://stackoverflow.com/a/69936523/21445669 – mkranj Jun 05 '23 at 11:49

1 Answers1

1

Here is a working example that does what you want:

library(shiny)
library(echarts4r)


df <- data.frame(
  x = 1:5,
  y = runif(n = 1:5, min = 50, max = 200)
)

ui <- fluidPage(
  echarts4rOutput("chart"),
  actionButton("changecolor", "Change color of third bar"),
  actionButton("removecolor", "Remove color of third bar")
  
)

server <- function(input, output){
  
  color <- reactiveVal("'blue'")
  observeEvent(input$changecolor, {
    color("'red'")
  }) 
  observeEvent(input$removecolor, {
    color("'blue'")
  }) 
  
  output$chart <- renderEcharts4r({
    e_charts(df, x) |> 
      e_bar(y,
            itemStyle = list(color = htmlwidgets::JS(paste0("
          function(params) {
                                var colorList = ['blue', 'blue',", 
                                color(), ", 'blue', 'blue']; return colorList[params.dataIndex]
                                }")))) |>
      e_legend(FALSE)
  })
  
}

shinyApp(ui, server)
David Jorquera
  • 2,046
  • 12
  • 35