r - 分面 : adding individual arrows in multiple plots does not work

标签 r ggplot2

Adding individual arrows in multiple plots 我描述了一个已经通过 math.coffee 解决的问题。

我的问题是如何仅向一个方面添加单个箭头。最近我安装了新版本的R:

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

这是代码示例

# 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'

应该发生什么:箭头应该只在 A 方面创建。 发生了什么:在 A 面和 B 面都创建了箭头。

有人知道如何解决这个问题吗?

最佳答案

显然,更新 R 和 ggplot 后发生了变化。坐标数据必须与数据帧一起传送。下面是一个带有附加分组的示例:

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

关于r - 分面 : adding individual arrows in multiple plots does not work,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9967628/

相关文章:

r - 如何从数据框中删除少于 5 个观察值的个体

r - 根据第二个数据框中的日期范围汇总 R 数据框

r - ggplot2 geom_area 意外绘制(在错误的位置结束)

r - 使用雷达坐标将线段添加到ggplot2中的直方图中

r - 有一组点线图和垂直线图的单独图例

r - 我为什么会得到“position_dodge需要恒定宽度”,即使在ggplot2中宽度不变

r - 在 R 中使用 which() 函数时进行矢量化

r - ggplot2 - 为数据框的每一列创建一个条形图

r - 如何在ggplot中添加带有标签的水平虚线

r - 如何用按平均值着色的较小矩形填充矩形