简体   繁体   English

使ggvis图表反应闪亮

[英]Making ggvis plots reactive with shiny

I have the following plot and I wish to make it interactive. 我有以下情节,我希望它具有互动性。 More specifically, I'd like a slider for maximum supply to range between 60 and 120. I've read through the shiny and ggvis documentation and I can't get it to work. 更具体地说,我想要一个最大供应量的滑块,范围在60到120之间。我已经阅读了闪亮的ggvis文档,我无法让它工作。 I've included an attempt below. 我在下面列出了一个尝试。

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 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 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")
    )
  )
))

Making the data that you pass to ggvis reactive is the key here, since you want to be able to subset it in response to user input. 使传递给ggvis reactive的数据成为关键,因为您希望能够根据用户输入对其进行子集化。 Also, the maximum_supply is part of input and can be accessed via input$maximum_supply in the supply function and the reactive data. 此外, 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")
    })
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM