繁体   English   中英

R Shiny:在一个R markdown文档中调用多个renderPlot

[英]R Shiny: multiple renderPlot calls in one R markdown document

背景:您可以“询问” RStudio以生成示例R Markdown Shiny文档,其中包含以下示例代码:

## Inputs and Outputs

You can embed Shiny inputs and outputs in your document.
Outputs are automatically updated whenever inputs 
change. This demonstrates how a standard R plot can be 
made interactive by wrapping it in the Shiny 
`renderPlot` function. The `selectInput` and 
`sliderInput` functions create the input widgets used to
drive the plot.

```{r, echo=FALSE}
inputPanel(
  selectInput("n_breaks", label = "Number of bins:",
              choices = c(10, 20, 35, 50), selected = 20),

  sliderInput("bw_adjust", label = "Bandwidth adjustment:",
              min = 0.2, max = 2, value = 1, step = 0.2)
)

renderPlot({
  hist(faithful$eruptions, probability = TRUE, breaks = as.numeric(input$n_breaks),
       xlab = "Duration (minutes)", main = "Geyser eruption duration")

  dens <- density(faithful$eruptions, adjust = input$bw_adjust)
  lines(dens, col = "blue")
})
```

请注意,此示例使用包含ui.R和server.R的文件夹。

问题:如果您多次复制此文件,则第一个可以按预期工作,而后一个也可以显示,但对输入参数的更改没有反应。

问题:如何创建具有上述多个嵌入图的R Markdown文档(不使用带有ui.R和server.R的外部文件夹),但要确保每个文档都可以交互工作?

您必须为输入元素赋予不同的ID,例如:

First embedded shiny plot :

```{r}
inputPanel(
  selectInput("n_breaks", label = "Number of bins:",
              choices = c(10, 20, 35, 50), selected = 20),

  sliderInput("bw_adjust", label = "Bandwidth adjustment:",
              min = 0.2, max = 2, value = 1, step = 0.2)
)

renderPlot({
  hist(faithful$eruptions, probability = TRUE, breaks = as.numeric(input$n_breaks),
       xlab = "Duration (minutes)", main = "Geyser eruption duration")

  dens <- density(faithful$eruptions, adjust = input$bw_adjust)
  lines(dens, col = "blue")
})
```

Second embedded shiny plot :

```{r}
inputPanel(
  selectInput("n_breaks2", label = "Number of bins:",
              choices = c(10, 20, 35, 50), selected = 20),

  sliderInput("bw_adjust2", label = "Bandwidth adjustment:",
              min = 0.2, max = 2, value = 1, step = 0.2)
)

renderPlot({
  hist(faithful$eruptions, probability = TRUE, breaks = as.numeric(input$n_breaks2),
       xlab = "Duration (minutes)", main = "Geyser eruption duration")

  dens <- density(faithful$eruptions, adjust = input$bw_adjust2)
  lines(dens, col = "blue")
})
```

RStudio Shiny Tutorial中所述,小部件功能的第一个参数是小部件名称,它标识小部件。 具有相同名称的多个小部件将各自不可用,这就是为什么仅创建示例的两个副本而不会创建两个工作副本的原因。

要使其工作,必须在每个inputPanel调用inputPanel窗口小部件名称唯一,然后在renderPlot调用中使用此名称。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM