Shiny Document:如何居中对齐 RenderPlot 的输出

Shiny Document: how to center align output of RenderPlot

我正在 R 中创建一个 Shiny Document,并希望使用 Shiny RenderPlot 生成的绘图居中,或向右,或高度 = 50%。但是,r 块中的 fig.align=center or right or out-width = "50%" 不影响输出(我想这是针对直接在 R 中生成的图形,而不是通过 Shiny)。如何居中?

尝试改变 out.width 或 fig.align,它不会改变一件事。

--
title: "Untitled"
author: "Gahis"
date: "8/4/2021"
output: html_document
runtime: shiny
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```


```{r eruptions, echo=FALSE, fig.align='right', out.width="50%"}
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")
})
```

谢谢!

这里介绍了如何减小图的宽度并将其居中。添加这个 CSS:

<style>
.center50 { 
  margin: auto;
  width: 50%;
}
</style>

然后将您 renderPlot 与 class center50:

一起包含在 div
---
title: "Test"
output: html_document
runtime: shiny
---

<style>
.center50 { 
  margin: auto;
  width: 50%;
}
</style>

```{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)
)
```

```{r}
div(class = "center50",
    
    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")
    })
    
)
```