r - 在 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)
解决方案
这应该有效。根据所选变量,您创建一个新的 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
})
}
推荐阅读
- reactjs - react-native-localize:更改所有屏幕的语言
- javascript - PokeAPI 仅使用节点快递向我的前端发送 1 个元素
- ios - 如何在 UIPickerview 中启用子视图的标签手势
- node.js - mysql和异步调用的NodeJS noob问题
- terraform - TF cidr_block 正确的字符串
- javascript - jquery自动完成中的unicode字体问题
- wordpress - 如何从子主题functions.php将php片段插入父主题文件
- r - 如何根据数据框名称中的单个字符在数据框中添加新列?
- php - 电子邮件欺骗错误:表单是从提交的电子邮件发送的,而不是服务器/域
- dockerfile - 如何为 ERPNext 开源 ERP 创建 Docker 镜像?