【发布时间】:2017-04-12 13:22:21
【问题描述】:
我正在尝试使用 Shiny 创建一个显示采样动画的应用程序。类似于here 所示的示例。
这里有一些最小的代码,只显示了我遇到问题的部分。这不是我使用的数据,而是一个可重现的示例数据集。
library(shiny)
library(ggplot2)
data <- data.frame(ID=1:60,
x=sort(runif(n = 60)),
y=sort(runif(n = 60)+rnorm(60)))
ui <- fluidPage(
sidebarPanel(
sliderInput("n",
"Number of samples:",
min = 10,
max = 100,
value = 20),
sliderInput("surveys",
"Number of surveys:",
min = 10,
max = 100,
value = 20),
checkboxInput("replacement",
"Sample with replacement?"),
actionButton("button", "Go!")
),
# Show the plot
mainPanel(
plotOutput("plot1")
)
)
server <- function(input, output) {
output$plot1 <- renderPlot({
plot1 <- ggplot(data, aes(x=x, y=y)) + geom_point(colour="red") + theme_bw()
plot1 <- plot1 + geom_vline(xintercept = mean(data$x), size=1.1, colour="red")
plot1
for(i in 1:20){
data$sampled <- "red"
sample.rows <- sample(data$ID, 20, replace = F)
data$sampled[sample.rows] <- "green"
plot1 <- plot1 + geom_point(x=data$x, y=data$y, colour=data$sampled, size=2)
sample.mean.x <- mean(data$x[sample.rows])
plot1 <- plot1 + geom_vline(xintercept = sample.mean.x, colour="green")
print(plot1)
Sys.sleep(1.5)
}
})
}
# Run the application
shinyApp(ui = ui, server = server)
renderPlot({ ... }) 中的部分在粘贴到控制台时完全符合我的要求,但是如何在 Shiny 中实现这一点?理想情况下,我还希望情节首先出现,然后在单击 actionButton 时开始动画(绿色条)。
谢谢!
【问题讨论】:
-
或许看看这个问题:stackoverflow.com/questions/30647828/…。你的策略是行不通的,因为在函数返回之前什么都不会更新。