使ggvis图表反应闪亮

时间:2015-10-19 22:06:53

标签: r shiny ggvis

我有以下情节,我希望让它具有互动性。更具体地说,我喜欢最大供应量的滑块,范围在60到120之间。我已经阅读了闪亮的ggvis文档,但我无法使用它。我在下面进行了一次尝试。

library(ggvis)
library(dplyr)
library(tidyr)

maximum_supply = input$maximum_supply

supply.function = function(supply)
  60 - 60/maximum_supply * supply

data_frame(quantity = 0:maximum_supply) %>%
  mutate(price = supply.function(quantity)) %>%
  ggvis(~quantity, ~price) %>%
  layer_lines()

shiny.R

library(shiny)
library(ggvis)
library(dplyr)

shinyServer(function(input, output) {

  reactive({ 
    maximum_supply = 120

    supply.function = function(supply)
      60 - 60/maximum_supply * supply

    data_frame(quantity = 0:maximum_supply) %>%
      mutate(price = supply.function(quantity)) %>%
      ggvis(~quantity, ~price) %>%
      layer_lines() %>%
      bind_shiny("ggvis", "ggvis_ui")
  })
})

ui.R

library(shiny)
library(ggvis)
library(dplyr)

shinyUI(fluidPage(

  titlePanel("Example"),

  sidebarLayout(
    sidebarPanel(
      sliderInput("maximum_supply",
                  "Maximum Supply",
                  min = 60,
                  max = 120,
                  value = 90),
    ),

    mainPanel(
      uiOutput("ggvis_ui"),
      ggvisOutput("ggvis")
    )
  )
))

1 个答案:

答案 0 :(得分:2)

将传递给ggvis被动的数据作为关键,因为您希望能够根据用户输入对其进行子集化。此外,maximum_supplyinput的一部分,可以通过供应函数中的input$maximum_supply和被动数据进行访问。

library(ggvis)
library(shiny)
library(dplyr)

shinyApp(
    shinyUI(fluidPage(
        titlePanel("Example"),
        sidebarLayout(
            sidebarPanel(
                sliderInput("maximum_supply",
                            "Maximum Supply",
                            min = 60,
                            max = 120,
                            value = 90),
                uiOutput("ggvis_ui")
            ),
            mainPanel(
                ggvisOutput("ggvis")
            )
        )
    )),
    shinyServer(function(input, output) {
        supply.function <- function(supply) {
            60 - 60/input$maximum_supply* supply
        }

        dat <- reactive({ data.frame( quantity = 0:input$maximum_supply ) })

        dat %>%
          mutate(price = supply.function(quantity)) %>%
          ggvis(~quantity, ~price) %>%
          layer_lines() %>%
          bind_shiny("ggvis", "ggvis_ui")
    })
)