簡體   English   中英

如何將數據從反應性Shiny表達式傳遞到ggvis圖?

[英]How is data passed from reactive Shiny expression to ggvis plot?

我正在熟悉ggvis,我正試圖在閃亮中使用它。 我無法理解ggvis如何從反應性Shiny表達式中獲取數據。 這是ggvis GitHub存儲庫的基本應用程序:

ui.R:

shinyUI(pageWithSidebar(
  div(),
  sidebarPanel(
    sliderInput("n", "Number of points", min = 1, max = nrow(mtcars),
                value = 10, step = 1),
    uiOutput("plot_ui")
  ),
  mainPanel(
    ggvisOutput("plot"),
    tableOutput("mtc_table")
  )
))

server.R:

library(ggvis)

shinyServer(function(input, output, session) {
  # A reactive subset of mtcars
  mtc <- reactive({ mtcars[1:input$n, ] })

  # A simple visualisation. In shiny apps, need to register observers
  # and tell shiny where to put the controls
  mtc %>%
    ggvis(~wt, ~mpg) %>%
    layer_points() %>%
    bind_shiny("plot", "plot_ui")

  output$mtc_table <- renderTable({
    mtc()[, c("wt", "mpg")]
  })
})

現在mtc是反應式表達式,它實際上是一個函數(或者是它?),它的結果是一個data.frame。 然而,它作為一個功能用管道傳輸給ggvis。 如果您嘗試傳遞結果data.frame之類的

mtc() %>%  ggvis(~wt, ~mpg) %>%
layer_points() %>%
        bind_shiny("plot", "plot_ui")

Shiny會開始抱怨“沒有活躍的反應環境就不允許操作”。 那么究竟發生了什么?

我問的原因是我想返回我想在ggvis中使用的其他對象。 更確切地說,我想要更改x和y軸標簽,其中標簽是在反應式表達式中計算的,如下所示:

mtc <- reactive({ list(data=mtcars[1:input$n, ],
labx = "Computed x axis label",
laby = "Computed y axis label")
   })

mtc %>% ggvis(data=data,~wt,~mpg) %>% 
    layer_points() %>%
    add_axis("x",title=labx) %>%
    add_axis("y",title=laby) %>%
    bind_shiny("plot", "plot_ui")

是否有可能以某種方式利用ggvis調用中的mtc()輸出結構? 或者只能傳遞data.frame,然后將數據放入data.frame中?

或者是否有另一種注冊ggvis對象的方法? 在這個問題中 ,ggvis輸出使用observe_ggvis函數注冊,但似乎它在當前的ggvis版本(0.3)中不存在。

我在R 3.1.1上使用ggvis版本0.3.0.1和閃亮0.10.0

ggvis可以傳遞給數據集的“裸反應”。 當你這樣做時,ggvis會在數據發生變化時自動重新繪制數據,但不需要重新繪制整個圖:

get_rct_df = reactive({  #code to change dataset from shiny input  )}
get_rct_df %>% ggvis() #rest of plotting code %>% bind_shiny("plot")

每次get_rct_df中的數據發生變化時,這將更新繪圖中的數據點(但不會重繪整個繪圖)。 這也意味着如果不重新繪制整個繪圖(繪圖標簽,layer_model_predictions的等式),某些內容無法更新。

您可以執行其他建議並將整個圖表包含在被動反應中:

reactive({
   get_rct_df %>% 
      ggvis() #rest of plotting code %>% 
      add_axis("x", title = input$title)
}) %>% bind_shiny("plot")

這將允許您更新繪圖標題和繪圖的其他部分。 但它也迫使ggvis在發生變化時重新繪制整個繪圖,而不僅僅是重新繪制數據。 如果你測試兩種方法,方法1看起來會“更平滑”; 當數據發生變化時,ggvis內置了過渡動畫。

好的,我在這個答案中找到了解決方案。

mtc <- reactive({ list(data=mtcars[1:input$n, ],
    labx = "Computed x axis label",
    laby = "Computed y axis label")
})

reactive({
    dl <- mtc()
    dl$data %>% ggvis(data=data,~wt,~mpg) %>% 
    layer_points() %>%
    add_axis("x",title=dl$labx) %>%
    add_axis("y",title=dl$laby) 
 }) %>% bind_shiny("plot", "plot_ui")

訣竅在於評估對被動的調用,因此您可以分離ggvis和實際ggvis繪圖的計算數據的過程。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM