Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ggplotly from inside for loop in .Rmd file does not work #570

Closed
GegznaV opened this issue May 3, 2016 · 4 comments
Closed

ggplotly from inside for loop in .Rmd file does not work #570

GegznaV opened this issue May 3, 2016 · 4 comments

Comments

@GegznaV
Copy link

GegznaV commented May 3, 2016

I tried to plot series of interactive ggplotly graphs from inside for loop in R markdown (.Rmd) file. Contents of my .Rmd file:


---
title: "Untitled"
output: html_document

---

```{r}
library(ggplot2) # for plots
library(plotly)  # for interactive plots

# Convert 4 variables to factor variables:
factor_vars <- c("vs", "am", "gear", "carb")
mtcars[factor_vars] <- data.frame(Map(as.factor, mtcars[factor_vars])) 



for (VAR in factor_vars) {
    cat(paste("Factor variable:", VAR))
    # Contents of "VAR" changes inside the loop
    p <- ggplot(mtcars, aes_string(x = "mpg", y = "wt", color = VAR)) + geom_point()

    # Print an interactive plot
    print(ggplotly(p))
}

```

I push Knit HTML button in RStudio. Unfortunately, none of interactive plots appear in the .html file.

Question: why the graphs aren't plotted? And how can I create interactive plot in combination with for loop in Rmd file?

p.s. If I use print(p) instead of print(ggplotly(p)), ggplot2 plots appear in resulting .html file.

@GegznaV GegznaV changed the title ggplotly from inside for loop in .Rmd file does not work ggplotly from inside for loop in .Rmd file does not work May 3, 2016
@cpsievert
Copy link
Collaborator

See this comment.

I'll open an issue in our documentation repo to make sure we have better docs of this...

@nmhamoud
Copy link

nmhamoud commented Mar 7, 2018

Is this problem solved? I seem to have the same issue.

@mkoohafkan
Copy link

mkoohafkan commented Dec 20, 2018

The current workaround is (based on the example code in the original issue):

plotlist = list()

for (VAR in factor_vars) {
    p <- ggplot(mtcars, aes_string(x = "mpg", y = "wt", color = VAR)) + geom_point()
    plotlist[[VAR]] = ggplotly(p)
}
htmltools::tagList(setNames(plotlist, NULL))

Although I sometimes get memory access errors from pandoc when I try to do this.

@PavelKarasek2
Copy link

I do not understand why this issue is closed. This solution is clearly just a workaround. It should be an easy thing to just output the plot in a for loop if desired.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants