【问题标题】:Passing arguments to renderPlot in R shiny在 R 中将参数传递给 renderPlot
【发布时间】:2016-10-03 14:59:29
【问题描述】:

我想用 R Shiny 绘制数据框中包含的变量。因此,我将有几个绘图,即几个 renderPlot 函数,但我只想创建一次该数据框。因此,我寻找一种方法来做类似的事情

library(shiny)

server <- shinyServer(function(input, output, session) {

## Creating and plotting the dataframe

## Calling renderPlot
output$plotxy <- renderPlot({
x = c(1,2,3)
y = c(4,5,6)
z = c(7,8,9)
d = data.frame( x, y, z )
plot( d$x, d$y )
})

output$plotxz <- renderPlot({
x = c(1,2,3)
y = c(4,5,6)
z = c(7,8,9)
d = data.frame( x, y, z )
plot( d$x, d$z )
})

output$plotzy <- renderPlot({
x = c(1,2,3)
y = c(4,5,6)
z = c(7,8,9)
d = data.frame( x, y, z )
plot( d$z, d$y )
})

})




ui <- shinyUI(
fluidPage(
plotOutput("plotxy"),
plotOutput("plotxz"),
plotOutput("plotzy")
)
)

shinyApp(ui = ui, server = server)

将数据框“d”创建为全局变量是个好主意吗?有什么建议吗?

【问题讨论】:

  • 为什么不能接受全局变量?我建议将其包含在global.R 而不是server.R 中,但效果是一样的。您实际上不喜欢当前的行为吗?如果是这样,请提供完整的MWE,并说明结果有什么问题。
  • 我将同时读取和写入此数据帧,并希望避免此数据帧的不同版本之间的“数据冲突”。这就是为什么我更喜欢明确控制情节的内容
  • 在不了解您的用例的情况下,我无法建议最好的方法。您能否发布一个 MWE,显示您打算对数据进行更改的示例?如果您也可能写入数据,我完全不清楚您打算如何避免“数据冲突”。
  • 我明白,我刚刚编辑并制作了一个完整的工作示例。首先最重要的问题是如何将数据框的创建外部化
  • MWE 中的所有示例都没有表明单个全局变量 d 是不可接受的。 (注意:编辑是为了让应用程序自成一体,让其他人更容易运行。)

标签: r plot shiny


【解决方案1】:

这是一个使用reactive 的示例,它允许您在一个地方更改数据。但是,这与全局加载 data.frame 没有什么不同,除非/直到您将响应部分添加到定义 d() 的函数中(例如,由于输入而发生的更改或响应单击按钮从磁盘重新读取)。

library(shiny)

server <- shinyServer(function(input, output, session) {

  ## Creating the dataframe
  d <- reactive({
    data.frame(
      x = 1:3
      , y = 4:6
      , z = 7:9 
    )
  })

  ## Calling renderPlot
  output$plotxy <- renderPlot({
    plot( d()$x, d()$y )
  })

  output$plotxz <- renderPlot({
    plot( d()$x, d()$z )
  })

  output$plotzy <- renderPlot({
    plot( d()$z, d()$y )
  })

})




ui <- shinyUI(
  fluidPage(
    plotOutput("plotxy"),
    plotOutput("plotxz"),
    plotOutput("plotzy")
  )
)

shinyApp(ui = ui, server = server)

【讨论】:

  • 我刚试了一下,没有问题,我想我估计错了写/读的问题,它有效!
猜你喜欢
  • 2019-08-26
  • 2015-12-05
  • 1970-01-01
  • 2012-06-07
  • 1970-01-01
  • 1970-01-01
  • 2018-08-05
  • 2019-03-18
相关资源
最近更新 更多