我想做一个反应式显示,根据选择的输入选择器的值显示不同数量的图。在mtcars数据集的情况下,假设我要让用户选择按Nr切割。齿轮或Nr。的Carburatos,用于生产地块。
查看unique(mtcars$gear)
,我们看到它有4 3 5
个3个可能值,而unique(mtcars$carb)
有4 1 2 3 6 8
个6个可能值。因此,我想在选择Nr. of Carburators
时生成6个单独的图,而在选择Nr. of Gears
时仅生成3个图。我玩过conditionalPanel
,但是在选择器之间切换一两次后,它总是会炸毁。救命?
闪亮的用户界面:
library(shiny)
library(googleVis)
shinyUI(bootstrapPage(
selectInput(inputId = "choosevar",
label = "Choose Cut Variable:",
choices = c("Nr. of Gears"="gear",
"Nr. of Carburators"="carb")),
htmlOutput('mydisplay') ##Obviously I'll want more than one of these...
# conditionalPanel(...)
))
闪亮的服务器:
shinyServer(function(input, output) {
#Toy output example for one out of 3 unique gear values:
output$mydisplay <- renderGvis({
gvisColumnChart(
mtcars[mtcars$gear==4,], xvar='hp', yvar='mpg'
)
})
})
最佳答案
受this的启发,您可以执行以下操作:
用户界面
shinyUI(pageWithSidebar(
headerPanel("Dynamic number of plots"),
sidebarPanel(
selectInput(inputId = "choosevar",
label = "Choose Cut Variable:",
choices = c("Nr. of Gears"="gear", "Nr. of Carburators"="carb"))
),
mainPanel(
# This is the dynamic UI for the plots
uiOutput("plots")
)
))
服务器
library(googleVis)
shinyServer(function(input, output) {
#dynamically create the right number of htmlOutput
output$plots <- renderUI({
plot_output_list <- lapply(unique(mtcars[,input$choosevar]), function(i) {
plotname <- paste0("plot", i)
htmlOutput(plotname)
})
tagList(plot_output_list)
})
# Call renderPlot for each one. Plots are only actually generated when they
# are visible on the web page.
for (i in 1:max(unique(mtcars[,"gear"]),unique(mtcars[,"carb"]))) {
local({
my_i <- i
plotname <- paste0("plot", my_i)
output[[plotname]] <- renderGvis({
data <- mtcars[mtcars[,input$choosevar]==my_i,]
if(dim(data)[1]>0){
gvisColumnChart(
data, xvar='hp', yvar='mpg'
)}
else NULL
})
})
}
})
它基本上动态创建
htmlOutput
图,并在子集中有数据时绑定googleVis
图。关于r - Shiny :输出元素/图的动态数量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31686773/