首页 > 解决方案 > R 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({

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)

标签: rshinyannotationsplotly

解决方案


这不是relayoutplotly. 请参阅下面的示例,使用relayout.

我更喜欢为此目的使用本机闪亮按钮,因为它提供了更大的灵活性。以下是实现高音切换的方法。

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)

推荐阅读