2012-02-27 16 views
1

我想在用ggplot和分面生成的2個地塊中添加箭頭。問題:如何避免兩個圖形中箭頭的複製?我想添加個別箭頭到每個情節。 下面是一個例子:在多個地塊中添加單獨的箭頭

library(ggplot2) 
# data frame with fake data 
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 

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

# location of the arrow: x=4, y= on the top 

(f1x4 <- xdf[4,"y"])+1 
xp + geom_segment(aes(x=4,xend=4,y=f1x4+3,yend=f1x4) 
         , arrow=arrow(length=unit(0.4,"cm") 
         ) 
        ) + 
     geom_text(aes(x=4,y=f1x4+5, label="a")) 

事件描述: 箭頭被放置在兩端面在同一區域中。我如何選擇一個特定的陰謀放置箭頭?

回答

1

據我所知,要將各個圖層添加到一個構面上,您需要提供一個具有相應構面值的數據框。

ggplot2 facet_grid page

# If you combine a facetted dataset with a dataset that lacks those 
# facetting variables, the data will be repeated across the missing 
# combinations: 

所以只是做xp + geom_segment(aes(x,xend,y,yend))將借鑑各方面,因爲磨製變量缺失。

你磨製變量是z,所以你可以:

  • 創建一個數據幀arrow.dfxy,並且z是 'A'
  • 直接喂到zaes

第二個選擇似乎更加得心應手:

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' 

所以,你只是在一個factorvariablename=factor添加到aes參數繪製特定的面板上(因爲你在數據幀zxp有水平「A '和'B')。

+0

非常感謝。這就是我想要的,它不知道如何簡單的解決方案。 – giordano 2012-02-28 07:28:14