【问题标题】:R Shiny not plotting at allR Shiny 根本没有绘图
【发布时间】: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 &lt;-
  • 是的。要么:(1)在coord_cartesian()之后添加p,(2)删除p &lt;-并保留ggplot2(...) + ... + ...表达式,或者(3)添加print(p)

标签: r ggplot2 shiny reactive


【解决方案1】:

简单修复:删除 p

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-27
    • 2019-07-27
    • 1970-01-01
    • 2014-08-03
    • 1970-01-01
    • 2018-12-20
    • 2021-12-14
    • 2014-04-19
    相关资源
    最近更新 更多