2012-04-01 4 views
1

In Adding individual arrows in multiple plots Ich beschrieb ein Problem, das dank Mathematic.coffee gelöst wurde.facettieren: Hinzufügen einzelner Pfeile in mehreren Plots funktioniert nicht

Mein Problem war, wie man einen einzigen Pfeil zu nur einer Facette hinzufügt. Vor kurzem habe ich eine neue Version von R:

Plattform i386-pc-mingw32
version.string R Version 2.14.2 (2012-02-29) ggplot2_0.9.0

Hier ist die Beispielcode

# data frame 
xdf <- data.frame(x=rep(1:10,2) 
        ,y=c(2*c(1:10)+rnorm(10,0,3), 4*c(1:10)+rnorm(10,0,5)) 
        ,z=rep(c("A","B"),each=10) 
       ) 
xdf 

# plot 
ggplot with faceting 
xp <- ggplot(xdf,aes(x=x,y=y)) + 
    geom_line() + 
    facet_grid(. ~ z) 
xp 

# location of the arrow: x=4, y=y+1 on the top of the first facet (A) 
(f1x4 <- xdf[4,"y"]+1) 

# add arrow and label 
xp + geom_segment(aes(x=4,xend=4,y=f1x4+3,yend=f1x4,z='A') # <-- see the z='A' 
        , arrow=arrow(length=unit(0.4,"cm") 
        ) 
       ) + 
    geom_text(aes(x=4,y=f1x4+5, label="a",z='A'))  # <-- see the z='A' 

Was soll passieren: der Pfeil sollte nur auf Facette A. erstellt Was geschieht: der Pfeil auf beiden Facetten entsteht A und B.

Hat jemand eine Idee, wie Sie dieses Problem lösen können?

Antwort

1

Offensichtlich gab es eine Änderung nach der Aktualisierung von R und ggplot. Die Koordinatendaten müssen mit einem Datenrahmen geliefert werden. Hier ist ein Beispiel mit einer zusätzlichen Gruppierung:

xdf <- data.frame(x=rep(1:10,each=4) 
       ,y=rep(1:10,each=4)*rep(1:4,10) +rnorm(40,0,1) 
       ,g=rep(c("R","S"),20) 
       ,z=rep(c("A","A","B","B"),10) 
      ) 
head(xdf) 
# plot 
xp <- ggplot(xdf,aes(x=x,y=y, group=g)) + 
geom_line() + 
facet_grid(. ~ z) 
xp 
# location of the arrow: x=4, y=y+1 on the top of the first facet (A) 
(f1x4 <- subset(xdf,x==4 & g=="R" & z=="A")$y) 
arrdf <- data.frame(x = 4, y = f1x4, z = "A", g = "R") # create new data.frame for annotations 
# add arrow and label 
xp + geom_segment(data=arrdf,aes(x=x,xend=x,y=y+3,yend=y,z=z,g=g) # <-- see the z='A' 
       , arrow=arrow(length=unit(0.4,"cm") 
       ) 
      ) + 
geom_text(data=arrdf,aes(x=x,y=y+4, label="a",z=z, g=g))