繁体   English   中英

ggvis图消失与工具提示和checkBoxInput闪亮

[英]ggvis plot disappears with tooltip and checkBoxInput Shiny

我在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应用程序中的复选框按钮时,问题开始,即当我取消所有按钮时,出现错误:

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

我知道这是因为我的过滤条件排除了所有数据。 但是在那种情况下,当我取消所有复选框选项时,我想看到一个空图(如下面的“线图”所示)。 怎么做?

用户界面

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

服务器

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

})

全球

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)

您的错误实际上是来自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")

暂无
暂无

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

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