R-plotly 是否可以更改渲染图中的颜色?

问题描述 投票:0回答:1

我有一个闪亮的应用程序,带有稍大的绘图图形。我想更改痕迹的颜色而不重新渲染绘图。有什么办法可以做到这一点吗?

没有闪亮应用程序的最小工作示例

library(plotly)

trace_0 <- rnorm(100, mean = 5)
trace_1 <- rnorm(100, mean = 0)
trace_2 <- rnorm(100, mean = -5)
x <- c(1:100)

data <- data.frame(x, trace_0, trace_1, trace_2)

fig <- plot_ly(data, x = ~x, y = ~trace_0, name = 'trace 0', type = 'scatter', mode = 'lines') 
fig <- fig %>% add_trace(y = ~trace_1, name = 'trace 1', mode = 'lines') 
fig
# update colors
layout(fig,  colorway = c("yellow","green"))

现在我在一个(最小的)闪亮应用程序中尝试了它

ui = fluidPage(
  fluidRow( 
    plotlyOutput("plot")
    ),
  fluidRow(
    actionButton("changeColor", "Change Color")
  )
)

server= function(input,output, session){
  output[["plot"]] = renderPlotly({
    trace_0 <- rnorm(100, mean = 5)
    trace_1 <- rnorm(100, mean = 0)
    trace_2 <- rnorm(100, mean = -5)
    x <- c(1:100)
    
    data <- data.frame(x, trace_0, trace_1, trace_2)
    
    fig <- plot_ly(data, x = ~x, y = ~trace_0, name = 'trace 0', type = 'scatter', mode = 'lines') 
    fig <- fig %>% add_trace(y = ~trace_1, name = 'trace 1', mode = 'lines') 
    fig
  })
  plotProxy <- plotlyProxy(outputId="plot")
  
  observeEvent(input[["changeColor"]],{
    print("Color should change now (but does not)")
    plotlyProxyInvoke(plotProxy, "relayout",
                     colorway = c("yellow","green"))
    
  })
}

shinyApp(ui, server)

也尝试过重新设计,或争论

list(colorway = c("yellow","green")),

但对我来说没有任何结果。 我想阻止重新渲染图形,因为它需要大约 4-5 秒

r shiny plotly
1个回答
0
投票

我将颜色定义为 reactivValues。这是服务器功能的代码

server= function(input,output, session){

plot_col <- reactiveValues()
plot_col$a <- 'red'
plot_col$b <- 'blue'

output[["plot"]] = renderPlotly({
trace_0 <- rnorm(100, mean = 5)
trace_1 <- rnorm(100, mean = 0)
trace_2 <- rnorm(100, mean = -5)
x <- c(1:100)

data <- data.frame(x, trace_0, trace_1, trace_2)

fig <- plot_ly(data, x = ~x, y = ~trace_0, name = 'trace 0', type = 'scatter', mode = 'lines', line = list(color = plot_col$a)) 
fig <- fig %>% add_trace(y = ~trace_1, name = 'trace 1', mode = 'lines', line = list(color = plot_col$b)) 
fig
})
plotProxy <- plotlyProxy(outputId="plot")

observeEvent(input[["changeColor"]],{

  plot_col$a <- 'green'
  plot_col$b <- 'yellow'

})
}
© www.soinside.com 2019 - 2024. All rights reserved.