Adel
Adel

Reputation: 313

Shiny Document: how to center align output of RenderPlot

I am creating a Shiny Document in R and want the plot generated with Shiny RenderPlot to be centered, or right, or height = 50%. However, the fig.align=center or right or out-width = "50%" in the r chunk does not affect the output (I suppose it is for figures generated directly in R, not via Shiny). How to center?

Try to change out.width, or fig.align, and it won't change a thing.

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

Thanks!

Upvotes: 0

Views: 1019

Answers (1)

St&#233;phane Laurent
St&#233;phane Laurent

Reputation: 84529

Here is how you can reduce the width of the plot and centering it. Add this CSS:

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

Then include you renderPlot in a div with the class 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")
    })
    
)
```

Upvotes: 1

Related Questions