Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
851 views
in Technique[技术] by (71.8m points)

r - Using Proxy Interface in Plotly/Shiny to dynamically change data

I want to update the data present in a plot (displayed in plotlyOutput in a Shiny app) using Proxy Interface. Here is a minimal App.R code :

library(shiny)
library(plotly)

ui <- fluidPage(
    actionButton("update", "Test"),
    plotlyOutput("graphe")
)

server <- function(input, output, session) {
    output$graphe <- renderPlotly({
        p <- plot_ly(type="scatter",mode="markers")
        p <- layout(p,title="test")
        p <- add_trace(p, x=0,y=0,name="ABC_test",mode="lines+markers")
    })

    observeEvent(input$update, {
        proxy <- plotlyProxy("graphe", session) %>%
            plotlyProxyInvoke("restyle", list(x=0,y=1),0)
    })
}

shinyApp(ui, server)

When I run it, the plot is displayed with a dot at (0,0) (as wanted) but when I click of the button "Test", the dot does not move to (0,1). How can I achieve this ?

Thank you for any answer.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Strangely enough addTracesdoes not work with only one point but works with two points. To make it work you could add the same point twice. So you could try this:

ui <- fluidPage(
  actionButton("update", "Test"),
  plotlyOutput("graphe")
)

server <- function(input, output, session) {
  output$graphe <- renderPlotly({
    p <- plot_ly(type="scatter",mode="markers")
    p <- layout(p,title="test")
    p <- add_trace(p, x=0,y=0,name="ABC_test",mode="lines+markers")
  })

  observeEvent(input$update, {
    plotlyProxy("graphe", session) %>%
    plotlyProxyInvoke("deleteTraces", list(as.integer(1))) %>%
    plotlyProxyInvoke("addTraces", list(x=c(0, 0),y=c(1, 1),
                        type = 'scatter',
                        mode = 'markers'))
  })
}

shinyApp(ui, server)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...