【问题标题】:Adding individual arrows in multiple plots在多个图中添加单个箭头
【发布时间】:2012-02-27 22:01:05
【问题描述】:

我想在 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"))

发生了什么: 箭头放置在同一区域的两个方面。如何选择特定的地块来放置箭头?

【问题讨论】:

    标签: r ggplot2


    【解决方案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.df,其中x、y 和z 为“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'
    

    因此,您只需在 aes 参数中添加 factorvariablename=factor 即可在该特定面板上绘图(因为 xp 数据框中的 z 列具有级别“A”和“B”)。

    【讨论】:

    • 非常感谢。这就是我想要的,但解决方案的简单程度令人尴尬。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-09
    • 2021-12-01
    • 2012-06-17
    • 2020-07-23
    • 1970-01-01
    • 2019-08-06
    相关资源
    最近更新 更多