【发布时间】:2020-07-23 05:38:22
【问题描述】:
我是 Shiny 的新手,我正在尝试用它来模拟猎物/捕食者模型。
首先,我想生成包含每只动物所有初始位置的数据框;并尝试使用 ggplot 绘制它;但是当我点击actionButton时,情节从未出现过。我不明白为什么,并且有任何错误消息让我至少知道出了什么问题。
代码如下:
library(shiny)
library(tidyverse)
library(ggplot2)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
sliderInput("nPrey", "select total number of preys", 1, 100, 10, 1),
sliderInput("nHunter", "select total number of Hunters", 1, 100, 10, 1),
actionButton ("play", "Begin simulation")
),
mainPanel(
plotOutput("plot")
)
)
)
server <- function(input, output, session) {
zMax = 20
simulation <- eventReactive(input$play, {
createInitialTable(input$nPrey, input$nHunter)
})
output$plot <- renderPlot({
p <- ggplot() +
geom_point(aes_string(x="X",y="Y"), data=simulation()) +
coord_cartesian(xlim =c(0, zMax), ylim = c(0, zMax))
})
createInitialTable <- function (nPrey, nHunter){
aAnimal <- data.frame()
cVar <- c("X", "Y")
for (i in 1:nPrey){
aAnimal <- rbind(aAnimal, c(round(runif(1)*zMax), round(runif(1)*zMax)))
}
for (i in 1:nHunter){
aAnimal <- rbind(aAnimal, c(round(runif(1)*zMax), round(runif(1)*zMax)))
}
colnames(aAnimal) <- cVar
return (aAnimal)
}
}
shinyApp(ui, server)
感谢您阅读本文
【问题讨论】:
-
在
renderPlot中,您将p命名为您的情节,但没有运行它。在coord_cartesian()之后添加p或删除p <- -
是的。要么:(1)在
coord_cartesian()之后添加p,(2)删除p <-并保留ggplot2(...) + ... + ...表达式,或者(3)添加print(p)。