2016-08-09 9 views
1

Ich versuche, mehrere Funktionen mit ggplot2 Paket unter Verwendung stat_function zu plotten. Da ich mehrere Parameteroptionen habe, benutze ich for-Schleife. Ich speichere meine Plots in die Listenvariable myplot. Das Problem tritt auf, wenn ich versuche, sie zu drucken. Mit print scheint alles in Ordnung, aber wenn ich nur Option z. myplot[[1]] Die Linien sind die gleichen wie für myplot[[2]] usw., aber Punkte sind korrekt geplottet. Das gleiche Problem kann beobachtet werden, wenn ich versuche, alle meine Graphen mithilfe der Funktion grid.arrange mit einer Figur zu plotten.stat_function und grid.arrange in for Schleife

Siehe mein Beispiel:

library("ggplot2") 
myfun <- function(x, group, a, b, e){ 
    a * x + b + group * e 
} 
abe <- rbind(c(1, 2, 3), c(7, 0, -4), c(-1, -5, 8)) 
myplot <- list() 
for (i in 1:3){ 
    x1 <- rnorm(10, 0, 1) 
    x2 <- rnorm(10, 1, 1) 
    num <- runif(20, -10, 10) 
    df <- cbind(rbind(data.frame(x = x1, group = "group 1"), 
        data.frame(x = x1, group = "group 2")), 
       num) 
    myplot[[i]] <- ggplot(df, aes_string("x", "num")) + 
        geom_point(aes_string(colour = "group")) + 
        stat_function(aes(colour = "group 1"), 
           fun = function(x) 
           myfun(x, 0, abe[i, 1], abe[i, 2], abe[i, 3]), 
           geom = "line") + 
        stat_function(aes(colour = "group 2"), 
           fun = function(x) 
           myfun(x, 1, abe[i, 1], abe[i, 2], abe[i, 3]), 
           geom = "line") + 
        ylim(c(-10, 10)) + xlim(c(-2, 2)) 
} 

### everything OK 
for (i in 1:3){ 
    print(myplot[[i]]) 
} 
### points are changing but lines remain the same 
myplot[[1]]; myplot[[2]]; myplot[[3]] 
### again points are changing but lines remain the same 
grid.arrange(myplot[[1]], myplot[[2]], myplot[[3]], ncol = 3) 

Wie ich alle Zahlen in einer Datei speichern möchten Ich würde gerne richtig grid.arrange Plotlinien zu machen.

Antwort

2

Wenn Sie die Diagramme drucken, i == 3 und Ihre Funktion bewertet die Parameter nur dann und mit diesem Wert von i. Verwenden Sie die richtige stat_function Syntax stattdessen:

myplot[[i]] <- ggplot(df, aes_string("x", "num")) + 
    geom_point(aes_string(colour = "group")) + 
    stat_function(aes(colour = "group 1"), 
        fun = myfun, 
        args = list(a = abe[i, 1], b = abe[i, 2], 
           e = abe[i, 3], group = 0), 
        geom = "line") + 
    stat_function(aes(colour = "group 2"), 
        fun = myfun, 
        args = list(a = abe[i, 1], b = abe[i, 2], 
           e = abe[i, 3], group = 1), 
        geom = "line") + 
    ylim(c(-10, 10)) + xlim(c(-2, 2)) 
+0

Vielen Dank, das hat mein Problem gelöst! – Adela