首页 > 解决方案 > 在 Shiny 中,如何在给定复选框输入的情况下为绘图记录转换变量(x 和或 y)?

问题描述

在 Shiny 中,如何在给定复选框输入的情况下记录转换变量(x 和或 y)?如果输入变量是数字,我希望在给定复选框输入的情况下记录转换变量。

library(shiny)
library(ggplot2)

ui <- fluidPage(
  selectInput(inputId = "xvariable",
              label = "X Variable",
              choices = colnames(mtcars)),
  checkboxInput("LogX", "Log Transform", FALSE),
  selectInput(inputId = "yvariable",
              label = "Y Variable",
              choices = colnames(mtcars)),
  checkboxInput("LogY", "Log Transform", FALSE),
  
  h3(""),
  plotOutput("plot")
)

server <- function(input, output, session) {
  output$plot <- renderPlot({
    req(input$xvariable)
    req(input$yvariable)
    g <- ggplot(mtcars, aes(x = !!as.symbol(input$xvariable), y = !!as.symbol(input$yvariable)))
    if (input$xvariable %in% c("mpg", "disp", "hp", "drat", "wt", "qsec")) {
      # numeric
      g <- g + geom_point()
    } else {
      # categorical
      g <- g + geom_bar()
    }
    g
  })
}

shinyApp(ui, server)

标签: rshinyshiny-server

解决方案


这应该有效。根据所选变量,您创建一个新的 X 和 Y 列。如果日志转换已打开,则转换该列。也使 ggplot 调用更容易一些。

library(shiny)
library(ggplot2)

ui <- fluidPage(
  selectInput(inputId = "xvariable",
              label = "X Variable",
              choices = colnames(mtcars)),
  checkboxInput("LogX", "Log Transform", FALSE),
  selectInput(inputId = "yvariable",
              label = "Y Variable",
              choices = colnames(mtcars)),
  checkboxInput("LogY", "Log Transform", FALSE),
  
  h3(""),
  plotOutput("plot")
)

server <- function(input, output, session) {
  output$plot <- renderPlot({
    req(input$xvariable)
    req(input$yvariable)
    
    ## Copy mtcars into new dataframe
    df <- mtcars
    
    ## Create Y Variable
    # If LogY is TRUE
    if(isTRUE(input$LogY)){
      df$y <- log(df[[as.character(input$yvariable)]])
    }
    # If LogY is FALSE
    if(!isTRUE(input$LogY)){
      df$y <- df[[as.character(input$yvariable)]]
    }

    ## Modify X Variable Based on Variable
    if (input$xvariable %in% c("mpg", "disp", "hp", "drat", "wt", "qsec")) {
    ## Create X Variable
      # If LogX is TRUE
    if(isTRUE(input$LogX)){
      df$x <- log(df[[as.character(input$xvariable)]])
    }
      # If LogX is FALSE
    if(!isTRUE(input$LogX)){
      df$x <- df[[as.character(input$xvariable)]]
    }
      
      ## Graph
      g <- ggplot(df, aes(x = x, y = y)) + geom_point()
      
    } else {
      df$x <- as.factor(df[[as.character(input$xvariable)]])
      
      ## Graph
      g <- ggplot(df, aes(x = x)) + geom_bar()
    }

    g
  })
}

推荐阅读