我希望用户操纵滑块来回答问题。要查看它们是否正确,单击“检查”后,滑块将移至正确的答案。饼图将同时移动。我认为将Shiny与滑块动画选项结合使用是可能的。但是,我不知道如何以编程方式打开和关闭动画。或者,如果滑块的值可能减小-例如,从80%移至60%。
如果运行下面的代码,则可以模拟所需的行为。滑块从60开始。当滑块达到80时,按一下播放并按一下暂停。如何以编程方式做同样的事情?例如,按下“检查”按钮,饼图会自动从40%扩展到60%。
library(shiny)
library(ggplot2)
library(scales)
ui <- fluidPage(
# App title ----
titlePanel("How Many Canadians Speak French?"),
# Sidebar layout with input and output definitions ----
sidebarLayout(
# Sidebar to demonstrate various slider options ----
sidebarPanel(
# Size of slice A, B is determined automagically
sliderInput("per_a", "Percent French Speaking",
min = 0, max = 100,
value = 60, step = 1,
animate = animationOptions(interval = 300, loop = TRUE)),
actionButton(
inputId = "check",
label = "Check"
)
),
# Main panel for displaying outputs ----
mainPanel(
plotOutput(outputId = "pieChart")
)
)
)
# Define server logic for slider examples ----
server <- function(input, output, session) {
df <- data.frame(
group = c("English", "French"),
value = c(40, 60)
)
# Functions
draw_plot <- function(df) {
bp <- ggplot(df, aes(x = "", y = value, fill = group)) +
geom_bar(width = 1, size = 1, color = "grey23", stat = "identity")
pie <- bp + coord_polar("y", start = 0)
pie +
theme(axis.text.x = element_blank(),
axis.title.x = element_blank(),
axis.title.y = element_blank(),
panel.border = element_blank(),
panel.grid = element_blank(),
legend.position = "none",
axis.ticks = element_blank(),
plot.title = element_text(size = 19, face = "bold")) +
geom_text(aes(label = paste0(round(value), "% ", c("English", "French"))),
position = position_stack(vjust = 0.5),
color = "white", size = 6) +
labs(x = NULL, y = NULL, title = "") +
scale_fill_manual(values = c("red4", "#003399")) # Pie chart colours: English, French
}
output$pieChart <- renderPlot({
df$value[2] <- input$per_a
df$value[1] <- 100 - input$per_a
draw_plot(df)
})
observeEvent(input$check, {
# Insert code here that starts the slider animation at current value and stops it at 80
})
}
shinyApp(ui, server)