Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include plotly in R Studio Presentations (Rpres)

How to include a plotly plot in a Rpres file? If you do it like in a normal Rmd file

Basic Plot
========================================================
```{r, echo=FALSE}
library(plotly)
plot_ly(economics, x = date, y = unemploy / pop)
```

The result looks as follows: Error in file(con, "rb") : cannot open the connection

The solution I came up with, which uses the possibility that Markdown can contain HTML:

Basic Plot
========================================================
```{r, results='hide', echo=FALSE}
library(plotly)
p = plot_ly(economics, x = date, y = unemploy / pop)
htmlwidgets::saveWidget(as.widget(p), file = "demo.html")
```
<iframe src="demo.html" style="position:absolute;height:100%;width:100%"></iframe>

But I am hoping for a somehow more elegant solution which does not use any additional files.

like image 496
jakob-r Avatar asked Aug 19 '16 09:08

jakob-r


People also ask

Does Plotly work in R markdown?

If you are creating R charts in an RMarkdown environment with HTML output (such as RStudio), simply printing a graph you created using the plotly R package in a code chunk will result in an interactive HTML graph in the viewer.

How do I embed a plot in R markdown?

You can embed an R code chunk like this: ```{r} summary(cars) ``` You can also embed plots, for example: ```{r, echo=FALSE} plot(cars) ``` Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.

How do you create a presentation in R?

To create a new R Presentation you execute the New File -> R Presentation command: After specifying the location to save the presentation, a new presentation will be created and a preview will show within the Presentation tab in the upper right corner of the IDE.


1 Answers

The following is a minimal example on how to include a plot_ly graph in an ioslides presentation, so it does not quite answer the question for Rpres, but provides an alternative.

The first slide displays a plot transformed from a ggplot into a plot_ly, preserving the ggplot style. The second slide displays a plot using plot_ly directly.

---
title: "Plot_ly demo"
date: "8 December 2016"
output: ioslides_presentation
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```

## A simple plot_ly

```{r, fig.align='center', message = FALSE}
library(plotly)

df <- data.frame(x =  1:10, y = (1:10)^2)

p <- ggplot(df, aes(x = x, y = y)) + geom_line() + labs(x = "X", y = "Y", title = "X and Y")

ggplotly(p)
```

## Another simple plot_ly

```{r, echo = FALSE, fig.align = 'center', message = FALSE}
plot_ly(df, x = x, y = y)
```
like image 174
Antoine Vernet Avatar answered Sep 21 '22 08:09

Antoine Vernet