用箭头注释躲避的条形图

时间:2018-08-13 16:52:40

标签: r ggplot2 bar-chart

我有以下代码

d <- data.frame(a = c("a", "b", "a", "b"), b = c("c", "c", "d", "d"), y = c(4, 5, 3, 2))
ggplot(data = d, aes(x = a, y = y, fill = b)) +
   geom_col(position = position_dodge(0.9)) +
   annotate("segment", x = "a", xend = "a", y = 5, yend = 4, arrow = arrow())

我得到的是以下信息:

enter image description here

我想要的是有一个指向混凝土条的箭头。而且可能我想要多个箭头。例如这样的

enter image description here

问题是我不知道如何在x轴上处理具体的钢筋,即,各个闪避钢筋的x值。

2 个答案:

答案 0 :(得分:3)

data.frame(a=c("a", "b", "a", "b"), b=c("c", "c", "d", "d"), y=c(4, 5, 3, 2)) %>%
  ggplot(aes(x=a, y=y, fill=b)) +
  geom_col(position=position_dodge(0.9)) +
  annotate("segment", x=1, xend=.7, y = 5, yend=4.1, arrow=arrow()) +
  annotate("segment", x=1.2, xend=1.2, y = 4, yend=3.1, arrow=arrow())

enter image description here

答案 1 :(得分:3)

您可以从1开始用数字表示ab的位置。这里,a将为1,b将为2。数字对应于级别的位置(请参见levels(d$a))。

要放置多个注释,可以添加多个annotate元素,也可以将向量用于x / xend / y / yend位置。

因此,在您的情况下,以下应该可以正常工作:

dodge <- 0.9
ggplot(data = d, aes(x = a, y = y, fill = b)) +
  geom_col(position = position_dodge(dodge)) +
  annotate("segment", x = 1,       xend = 1 - dodge/4, y = 5, yend = 4, arrow = arrow()) +
  annotate("segment", x = 1 + dodge/4, xend = 1 + dodge/4, y = 4, yend = 3, arrow = arrow())

或使用向量:

dodge <- 0.9
ggplot(data = d, aes(x = a, y = y, fill = b)) +
  geom_col(position = position_dodge(dodge)) +
  annotate("segment", x     = c(1, 1 + dodge/4),
                      xend  = c(1 - dodge/4, 1 + dodge/4),
                      y     = c(5, 4),
                      yend  = c(4, 3), arrow = arrow())

当然,您可以将data.frame用于annotate元素的数据,就像处理任何geom_*元素一样。

Rplot showing annotations with two arrows