R Shiny:重新布局图注解

时间:2018-08-01 19:08:04

标签: r shiny annotations plotly

如果用户单击闪亮的应用程序中的按钮,我希望绘制一个情节以更改注释。 我不知道为什么这行不通:

library(shiny)
library(plotly)

d <- data.frame(x = c(1,2,3), y = c(9,99,999))


ui <- fluidPage(
  plotlyOutput("plot"),

actionButton("button", "toggle visibility"))

server <- function(input, output) {

output$plot <- renderPlotly({

plot_ly(d)%>%
  add_lines(y=d$y, x= d$x)%>%
  layout(annotations = list(x = 2, y= 99 , text = "hi"))})

  observeEvent(input$button, {
    plotlyProxy("plot", session= shiny::getDefaultReactiveDomain()) %>%
      plotlyProxyInvoke("relayout", list(annotations= list(x = 2, y= 99 , 
text = "ho")))})}

shinyApp(ui, server)

1 个答案:

答案 0 :(得分:1)

这不是在relayout中使用plotly的方式。请参阅以下使用relayout的示例。

我更喜欢为此使用本机闪亮按钮,因为它提供了更大的灵活性。这是实现踩toggle切换的方式。

shiny方式

library(shiny)
library(plotly)

d <- data.frame(x = c(1,2,3), y = c(9,99,999))


ui <- fluidPage(
  plotlyOutput("plot"),

  actionButton("button", "toggle visibility"))

server <- function(input, output) {

  output$plot <- renderPlotly({
    p <- plot_ly(d)%>%
      add_lines(y=d$y, x= d$x)
    if (is.null(input$button) | (input$button%%2 == 0)) {
      p <- p %>% layout(annotations = list(x = 2, y= 99 , text = "hi"))
    } else {
      p <- p %>% layout(annotations = list(x = 2, y= 99 , text = "ho"))
    }
    p
  })
}

shinyApp(ui, server)

尽管在这种情况下,relayout功能很简单,但确实需要一个额外的按钮。

plotly relayout方式

library(shiny)
library(plotly)

d <- data.frame(x = c(1,2,3), y = c(9,99,999))


ui <- fluidPage(
  plotlyOutput("plot")
)

server <- function(input, output) {
  output$plot <- renderPlotly({
    updatemenus <- list(
      list(
        active = -1,
        type = 'buttons',
        buttons = list(
          list(
            label = "hi",
            method = "relayout",
            args = list(list(annotations = list(list(x = 2, y= 99 , text = "hi"))))), 
          list(
            label = "ho",
            method = "relayout",
            args = list(list(annotations = list(list(x = 2, y= 99 , text = "ho")))))
          )
      )
    )
    p <- plot_ly(d) %>%
      add_lines(y=d$y, x= d$x) %>% 
      layout(updatemenus = updatemenus)
    p
  })
}

shinyApp(ui, server)