ggvis plot随工具提示和checkBoxInput Shiny消失

时间:2015-02-23 11:49:44

标签: r shiny ggvis

我在我的Shiny应用程序中使用ggvis中的工具提示时遇到问题。我想在ggvis中使用关于点点的其他信息,这就是我创建需要id变量的函数的原因:

add_info <- function(x) {
  if(is.null(x)) return(NULL)
  if (is.null(x$id)) return(NULL)
  df2<- isolate(data)
  df <- df2[df2$id == x$id, ]
  paste0(df$info,
         df$number)
}

当我在Shiny应用程序中使用checkBox按钮时,问题就开始了,即当我取消所有按钮时,出现错误:

Error in eval(substitute(expr), envir, enclos) : 
  wrong result size (2), expected 0 or 1 

我知道这是因为我的过滤条件排除了所有数据。但是在那种情况下,当我取消所有checkBox选项时(例如下面的Line plot中),我希望看到一个空图。怎么做?

ui.R

library(shiny)

shinyUI(fluidPage(

  titlePanel(""),

  sidebarLayout(
    sidebarPanel(
      wellPanel(checkboxGroupInput("variable",label = "",
                         choices = list("a","b","c","d"),
                         selected = c("a"))),
      br(),br(),br(),br(),br(),br(),br(),br(),

      wellPanel(checkboxGroupInput("variable2",label = "",
                         choices = list("a","b","c","d"),
                         selected = c("a")))      
    ),

    mainPanel(
      ggvisOutput("scatter_plot"),
      ggvisOutput("line_plot")
    )
  )
))

server.R

library(shiny)

shinyServer(function(input, output) {

  dataset <- reactive({
    df <- df1 %>%
      filter(name %in% input$variable)
    df
  })

    data <- reactive({
      dataset() %>%
        mutate(id = 1:n())
    })

  vis2 <- reactive({
    add_info <- function(x) {
      if(is.null(x)) return(NULL)
      if (is.null(x$id)) return(NULL)
      df2 <- isolate(data())
      df <- df2[df2$id == x$id, ]
      paste0(df$info,"<br>",
             df$number)
    }
    data() %>%
      ggvis(~number2, ~number, fill = ~name) %>%
      layer_points(size := 100,
                   size.hover := 240,
                   key := ~id) %>%
      add_tooltip(add_info,"hover")
  })
  vis2 %>% bind_shiny("scatter_plot")

  # LinePlot  
dataset_line <- reactive({
  df_line <- df1 %>%
    filter(name %in% input$variable2)
})

    vis <- reactive({

      dataset_line() %>%
        ggvis(~number2, ~number, stroke = ~name) %>%
        layer_lines()

    })
    vis %>% bind_shiny("line_plot")

})

global.R

df1 <- data.frame(name = rep(letters[1:4],each = 5), number = df1_number, number2 = df1_number2,
                  info = "info")

df1_number <-sample(seq(1,20,0.01),20,replace = T)
df1_number2 <-sample(seq(1,5,0.01),20,replace = T)

1 个答案:

答案 0 :(得分:2)

您的错误实际上来自dplyr mutate来电。当没有行(即空数据集)时,如果尝试使用n()计数,则会返回该错误。这可以防止它创建id变量并导致ggvis的下游问题。要解决此问题,您需要做的就是将1:n()更改为row_number()(感谢@docendodiscimus提供的建议)。要合并,请删除dataset语句,然后使用以下内容:

data <- reactive({
          df1 %>%
            filter(name %in% input$variable) %>%
            mutate(id = row_number())
      })

应该解决你的问题。

这是一个工作要点作为例子。

runGist("https://gist.github.com/cdeterman/806f51c254c523f88f01")
相关问题