Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render ggplotly() in R Markdown github_document

Interactive graphs created with ggplotly() go along nicely with html_document output in R Markdown, see eg. RMarkdown and ggplotly. For github_document output, however, the knitted HTML preview file does not show ggplotly() graphs.

I adopted the code from the linked SO post and only changed the output format in the header. Does anyone know how to render plotly graphs correctly with this kind of output? Or at least, if that is even possible?

---
title: "RmarkdownExample"
author: "fdetsch"
date: "April 16, 2020"
output: github_document
---

Here is the graph I generated. 

```{r setup, message = FALSE, echo = FALSE, warning=FALSE}
# Require
library(plotly)
# Create
dsamp <- diamonds[sample(nrow(diamonds), 1000), ]
# Plot
g <- qplot(carat, price, data=dsamp, colour=clarity)
# Call
ggplotly(g)
```

enter image description here

like image 335
fdetsch Avatar asked Sep 19 '26 14:09

fdetsch


2 Answers

For output: github_document, I found a workaround that renders ggplotly() graphs nicely using iframes. The trick is to export the plotly widget as HTML and subsequently embed it as iframe. In my opinion, the advantage over output: html_document with keep_md enabled is that the online .md file simply prints a link to the intermediary HTML file instead of the full widget code, making it much tidier.

---
title: "Render `ggplotly()` graphs in `github_document`"
author: "fdetsch"
date: "`r Sys.Date()`"
output: github_document
---

Here is the graph I generated. 

```{r setup, message = FALSE, echo = FALSE, warning = FALSE}
# Require
library(plotly)
# Create
dsamp <- diamonds[sample(nrow(diamonds), 1000), ]
# Plot
g <- qplot(carat, price, data=dsamp, colour=clarity)
# Call
p <- ggplotly(g)

```

```{r include, echo = FALSE}
htmlwidgets::saveWidget(p, "index.html")

htmltools::tags$iframe(
  src=file.path(getwd(), "index.html"),
  width="100%",
  height="600",
  scrolling="no",
  seamless="seamless",
  frameBorder="0"
)

```

At least when opening the preview HTML in an external viewer, the interactive graph shows up. The RStudio (preview version 1.3.938) viewer currently fails to render the image.

like image 97
fdetsch Avatar answered Sep 22 '26 07:09

fdetsch


There seem to be some problems with github_document, see here. My workaround: knit to html_document and save the resulting *.md-file. So the YAML header is:

---
title: "RmarkdownExample"
author: "fdetsch"
date: "April 16, 2020"
output: 
  html_document:
    keep_md: true
---

You can then use the md file to upload to github.

like image 28
J_F Avatar answered Sep 22 '26 05:09

J_F



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!