shiny随手日记1

2020-12-22 15:22:05 浏览数 (3)

  1. 问题描述:shiny在没有输入数据的数据下,也会生成空白图片,造成不美观。
代码语言:javascript复制
library(shiny)

ui <- fluidPage(
  
  fluidRow(
    column(width=1),
    column(  textInput(inputId = "test1", label = "", 
                       value = ""), width=2,style="background-color:lavender;border-radius: 10px")),
  
  hr(),
  
  
  fluidRow(
    column(width=1),
    column(  textInput(inputId = "test2", label = "", 
                       value = ""), width=2,style="background-color:lavender;border-radius: 10px")),
  
  hr(),
 
  
  actionButton("gobutton1","Start1"),
  
  actionButton("gobutton2","Start2"),
  
  fluidRow(
    mainPanel(
      plotOutput("distPlot1"))),
  
  hr(),

  
  fluidRow(
    mainPanel(
      plotOutput("distPlot2")))
  
  
)

server <- function(input,output){
  
  data1 <- eventReactive(input$gobutton1,{
    if(is.null(input$test1)){
      return()
    }
    
    num <- input$test1
    
    num <- as.numeric(num)
    
    num1 <-  num * 2;num2 <-  num * 3;num3 <-  num * 4;num4 <-  num * 5;num5 <-  num * 6
    
    dt <- data.frame(id=paste0('id',1:5), number = c(num1, num2, num3, num4, num5))
    
    dt
    
  })
  
  data2 <- eventReactive(input$gobutton2,{
    if(is.null(input$test2)){
      return()
    }
    
    num <- input$test2
    
    num <- as.numeric(num)
    
    num1 <-  num / 2 ;num2 <-  num / 3;num3 <-  num / 4;num4 <-  num /  5;num5 <-  num / 6
    
    dt <- data.frame(id=paste0('id',1:5), number = c(num1, num2, num3, num4, num5))
    
    dt
    
  })
  
  
  output$distPlot1 <- renderPlot({
    
    data <- data1()
    
    
    library(ggplot2)
    
    
    ggplot(data = data, mapping = aes(x = factor(id), 
                                         y = number, group = 1))   geom_point()  
      geom_line()   
      xlab('')  ylab('Probility') 
      theme(axis.text.x = element_text(vjust = 0.5,
                                       hjust = 0.5, 
                                       angle = 45))
    
  })
  
  output$distPlot2 <- renderPlot({
    
    data <- data2()
    
    
    library(ggplot2)
    
    
    ggplot(data = data, mapping = aes(x = factor(id), 
                                      y = number, group = 1))   geom_point()  
      geom_line()   
      xlab('')  ylab('Probility') 
      theme(axis.text.x = element_text(vjust = 0.5,
                                       hjust = 0.5, 
                                       angle = 45))
    
  })
  
}

shinyApp(ui=ui, server=server)

解决问题的关键是:

代码语言:javascript复制
  data1 <- eventReactive(input$gobutton1,{
    if(is.null(input$test1)){
      return()
    }
    
    num <- input$test1
    
    num <- as.numeric(num)
    
    num1 <-  num * 2;num2 <-  num * 3;num3 <-  num * 4;num4 <-  num * 5;num5 <-  num * 6
    
    dt <- data.frame(id=paste0('id',1:5), number = c(num1, num2, num3, num4, num5))
    
    dt
    
  })

该函数在默认不输入的情况下,会生成null,而导致后续的ggplot2不会生成空白图片,解决了我们的问题。

0 人点赞