在多个图中添加单个箭头

时间:2012-02-27 22:01:05

标签: r ggplot2

我想在ggplot和faceting生成的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 个答案:

答案 0 :(得分: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))上绘制所有方面,因为缺少了facetting变量。

您的分面变量为z,因此您可以:

  • 创建一个数据框arrow.dfxyz为'A'
  • 直接将z投放到aes

第二种选择似乎更方便:

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即可在该特定面板上绘图(因为z数据框中的xp列具有级别' A'和'B')。

相关问题