2016-05-03 11 views
6

Ich habe versucht, Reihe von interaktiven ggplotly Graphen von innen for Schleife in R Markdown (.Rmd) Datei zu plotten. Inhalt meiner .Rmd Datei:Interaktiver `ggplotly` Graph wird nicht von innen` for` Schleife in `Rmd` Datei in R

--- 
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)) 
} 

``` 

Ich schiebe Knit HTML Taste in RStudio. Leider erscheint keine der interaktiven Plots in der Datei .html.

Frage: warum die Graphen sind nicht aufgetragen? Und wie kann ich interaktives Plot in Kombination mit for Schleife in Rmd Datei erstellen?

p.s. Wenn ich print(p) anstelle von print(ggplotly(p)) verwende, erscheinen ggplot2 Plots in der resultierenden Datei .html.

Antwort

10

Basierend auf diesen github issue sollten Sie in der Lage sein, so etwas zu tun:

--- 
    title: "Untitled" 
    output: html_document 
    --- 

    ```{r, message = F} 
    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])) 

    plt <- htmltools::tagList() 
    i <- 1 
    for (VAR in factor_vars) { 

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


     # Print an interactive plot 
     # Add to list 
     plt[[i]] <- as.widget(ggplotly(p)) 
     i <- i + 1 
    } 

    ``` 

    ```{r, echo = F} 
    plt 
    ``` 
+0

Nizza workarround. Leider kann ich es in meiner aktuellen automatisierten Analyse nicht verwenden, wo in jeder Iteration von 'for' Loop-Plots Tabellen folgen, die statistische Tests ergeben. Alle Plots an einem Ort zu drucken wäre verwirrend. Ich bemerkte, dass das Ergebnis von 'pander()' auch nicht von innen nach 'for' loop gedruckt wird. Ist es ein Fehler in 'Knitr'? – Vilmantas

+0

Sieht so aus, als hätten Sie Ihre Bedenken im Github-Repo ebenfalls angesprochen. Wahrscheinlich am besten, wenn Sie mit pünktlichen Portfolio darauf arbeiten. – royr2