Can we keep the caption at the top of plotly objects in html output from rmarkdown?

时光总嘲笑我的痴心妄想 提交于 2020-08-24 06:58:39

问题


The following markdown shows the problem that captions that successfully go to the top of ggplot figures with the use of fig.topcaption=TRUE, but do not with plotly objects.

I learnt about fig.topcaption here. The underlying code for the fig.topcaption appears to live here in knitr, though either that is not compatible with plotly figures, or it could be pandoc, or html/html widgets-related, or somewhere else in the chain from the rmarkdown to final output.

I'm happy enough with a work around for now - suggestions?

---
title: "Untitled"
author: "Internet"
date: "29 février 2020"
output:
  bookdown::html_document2
---

```{r setup, message=FALSE, echo=FALSE}

library(knitr)
library(ggplot2)
library(plotly)

```

Here is a ggplot object with caption at the top as desired.


```{r, fig.cap="Hello ggplot", fig.topcaption=TRUE, message=FALSE, echo=FALSE}
ggplot(diamonds,aes(price,carat)) + geom_point()
```

Here is the previous ggplot converted to a plotly object with caption reverting to the bottom.


```{r, fig.cap="Hello plotly", fig.topcaption=TRUE, message=FALSE, echo=FALSE}
my_ggplot <- ggplot(diamonds,aes(price,carat)) + geom_point()
ggplotly(my_ggplot)
```

Caption reverts to bottom even if plotly object is not created from ggplot object

```{r, fig.cap="Hello plotly2", fig.topcaption=TRUE, message=FALSE, echo=FALSE}
plot_ly(
  x=c(1,2,3),
  y=c(5,6,7),
  type='scatter',
  mode='lines')
```

回答1:


The following trick will work arround HTML output.
We can format the figure as a table (with image as it only cell) and the paragraph (where the figure caption live) as a table caption and place it on the top.

Just place this CSS chunk below YAML:

```{css plotly-caption, echo = FALSE}
div.figure {
  display: table;
}
div.figure p {
  display: table-caption;
  caption-side: top;
}
```


来源:https://stackoverflow.com/questions/60647728/can-we-keep-the-caption-at-the-top-of-plotly-objects-in-html-output-from-rmarkdo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!