13

fig.align is not working with R Markdown HTML outputs and plotly and I looking for some help!

Here is a MWE:

---
title: "Untitled"
output: html_document
editor_options: 
chunk_output_type: console
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, fig.align = "center")
library(plotly)
```


```{r}
plot_ly(
  x = c("giraffes", "orangutans"),
  y = c(20, 14),
  name = "SF Zoo",
  type = "bar")
```


```{r, fig.align = 'right'}
plot_ly(
  x = c("giraffes", "orangutans"),
  y = c(20, 14),
  name = "SF Zoo",
  type = "bar")
```

```{r, fig.align = 'center'}
plot_ly(
  x = c("giraffes", "orangutans"),
 y = c(20, 14),
 name = "SF Zoo",
type = "bar")
```

3 Answers 3

16

Unlike normal plots, plotly graphics have a different HTML setup. What you can do is use the shiny package and wrap another div container around each plot:

library(shiny)
div(plot_ly(
x = c("giraffes", "orangutans"),
y = c(20, 14),
name = "SF Zoo",
type = "bar"), align = "right")
Sign up to request clarification or add additional context in comments.

1 Comment

This almost works for me...the plot_ly plot is centred but spans the entire html text width (so it would be centred regardless). However the figure caption disappears when I use the above code...did that happen on yours?
6

As pointed out in the comments, the solution proposed above made my plotly plot span the entire html text width. The following worked for me without streching the plot:

---
title: "Untitled"
output: html_document
chunk_output_type: console
---

```{css, echo=FALSE}
.center {
  display: table;
  margin-right: auto;
  margin-left: auto;
}
```

<div class = 'center'>
```{r, echo = F, message = F}
library(plotly)
plot_ly(
  x = c("giraffes", "orangutans"),
  y = c(20, 14),
  name = "SF Zoo",
  type = "bar")
```
</div>

For also showing the code snipped this solution is a bit ugly since the code snipped will also get centered. I use the following work-around:

```{r plot1, results = F, message = F}
library(plotly)
plot_ly(
  x = c("giraffes", "orangutans"),
  y = c(20, 14),
  name = "SF Zoo",
  type = "bar")
```

<div class = 'center'>
```{r plot1, echo = F}
```
</div>

Comments

2

adding the previous explanation from Martin, I figured out another way that you might be useful:

You can add and just between the chunk for making plotly:

    <center>

    ```{r, echo = FALSE, out.width = "60%"}
    library(dplyr)
    library(ggplot2)
    library(plotly)

    plot <- iris %>% 
      ggplot(aes(x = Species, y = Sepal.Width)) +
      geom_boxplot()
    
    ggplotly(plot)
    ```

    </center>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.