【问题标题】:Shiny Document: how to center align output of RenderPlot闪亮的文档:如何居中对齐 RenderPlot 的输出
【发布时间】:2021-10-09 11:38:30
【问题描述】:

我正在 R 中创建一个闪亮的文档,并希望使用闪亮的 RenderPlot 生成的绘图居中,或右,或高度 = 50%。但是,r 块中的 fig.align=center 或 right 或 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")
})
```

谢谢!

【问题讨论】:

  • 你能提供一个完整的、最小的例子吗?这会有所帮助。
  • 当然可以。我重新编辑了这个问题。谢谢!
  • 这不是完整的。请包括文件头等。
  • 道歉。现在应该是正确的。
  • 所以你想减小情节的宽度?因为默认情况下宽度为 100%,并且绘图居中。

标签: r shiny r-markdown document


【解决方案1】:

以下是如何减小绘图宽度并使其居中的方法。添加这个 CSS:

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

然后将renderPlot 包含在div 中,并使用center50 类:

---
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")
    })
    
)
```

【讨论】:

  • 太棒了,谢谢!是否可以像这样将它添加到 css r 块中:```{css, echo=FALSE} .center50y {...} 而不是使用
  • @Adel 我没有尝试,但这听起来可能。对于左对齐,只需删除 margin: auto
  • @Adel 在谷歌上输入“html align div right”,你会发现。
  • 还有一件事:奇怪的行为。我需要关闭 div 吗?如果我在那个 r 块之后写一些降价,它就会被情节隐藏。
  • @Adel 对不起,我不明白你的意思。我试图在这个块之后写“Hello”并且它有效。你做了什么?
猜你喜欢
  • 2017-07-17
  • 1970-01-01
  • 2020-08-28
  • 2019-05-23
  • 1970-01-01
  • 2018-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多