【发布时间】:2022-01-27 10:10:14
【问题描述】:
我有一个 shinyApp 可以根据数据生成两种不同类型的图。 这些数据完全相同(变量和列),除了其中一个是原始的,另一个是离散的。
现在我有一个应用程序,每次你想更改绘图类型时,你都需要手动更改数据集。 因此,您将上传一个或另一个数据集(原始数据集或离散化数据集),具体取决于您要获取的图。
如果您选择一种或另一种类型的数据,我想要一个自动更改数据的应用程序。
例如,假设我上传了原始数据(例如鸢尾花数据集),然后我点击boxplot 获取两个给定变量,
但是,我想获得相同变量的离散版本的barplot,因此 shinyApp 应该能够自动更改数据集。
这可能吗?
这里有基本的 RepEx。
# Shiny
library(shiny)
# Data
library(readxl)
library(dplyr)
# Plots
library(ggplot2)
not_sel <- "Not Selected"
ui <- navbarPage(
tabPanel(
title = "Plotter",
sidebarLayout(
sidebarPanel(
title = "Inputs",
fileInput("xlsx_input", "Select XLSX file to import", accept = c(".xlsx")),
selectInput("num_var_1", "Variable X axis", choices = c(not_sel)),
selectInput("num_var_2", "Variable Y axis", choices = c(not_sel)),
prettyRadioButtons(
inputId = "graph_selection",
label = "Choose:",
choices = c("Boxplot", "Barplot")
),
actionButton("run_button", "Run Analysis", icon = icon("play"))
),
mainPanel(
tabsetPanel(
tabPanel(
title = "Plot",
plotOutput("sel_graph")
)
)
)
)
)
)
# Server
server <- function(input, output, session){
# Dynamic selection of the data
data_input <- reactive({
#req(input$xlsx_input)
#inFile <- input$xlsx_input
#read_excel(inFile$datapath, 1)
iris
})
# We update the choices available for each of the variables
observeEvent(data_input(),{
choices <- c(not_sel, names(data_input()))
updateSelectInput(inputId = "num_var_1", choices = choices)
updateSelectInput(inputId = "num_var_2", choices = choices)
})
num_var_1 <- eventReactive(input$run_button, input$num_var_1)
num_var_2 <- eventReactive(input$run_button, input$num_var_2)
## Obtain plots dynamically --------------------------------------------------
#Boxplot
draw_boxplot <- function(data_input, num_var_1, num_var_2){
ggplot(data = data_input, aes(x = .data[[num_var_1]], y = .data[[num_var_2]])) +
geom_boxplot() +
theme_bw()
}
## Barplot
draw_barplot <- function(data_input, num_var_1, num_var_2){
ggplot(data = data_input, aes(x = Var1, y = Freq, fill = Var2, label = round(Freq, 3))) +
geom_bar(stat = "identity") +
ylim(0, 1) +
theme_bw()
}
## BoxPlot -------------------------------------------------------------------
plot_1 <- eventReactive(input$run_button,{
req(data_input(), num_var_1(), num_var_2())
draw_boxplot(data_input(), num_var_1(), num_var_2())
})
# Create another plot for display --------------------------------------------
plot_2 <- eventReactive(input$run_button,{
req(data_input(),input$num_var_2)
draw_barplot(data_input(), num_var_1(), num_var_2())
})
graphInput <- reactive({
switch(input$graph_selection,
"Boxplot" = plot_1(),
"Barplot" = plot_2()
)
})
output$sel_graph <- renderPlot(
graphInput()
)
}
shinyApp(ui = ui, server = server)
【问题讨论】:
-
您是否在询问,考虑到用户单击 Shiny 应用程序中的某个选项,Shiny 是否可以在您的计算机上自行查找数据集?我就是这样理解你的问题的。
-
嗨@jpiversen,是的,这是我的问题