用箭头注释ggplot中的hline

时间:2019-02-15 09:34:10

标签: r ggplot2

我制作一个这样的箱线图,在其中用“测试”注释行。

library(ggplot2)
df <- data.frame(x = rnorm(100))

ggplot(df, aes(y=x)) + geom_boxplot() + geom_hline(yintercept = 0.0) + 
   annotate("text", label = "test", x = 0, y = 0.2)

enter image description here

但是,我实际上希望“测试”出现在左下角,只是向箭头添加一个箭头,就像这样

enter image description here

箭头可以是直线或弯曲的。 当我在具有不同y轴范围的构面中使用它时,它应该是稳定的,但是,hline始终处于yintercept = 0

1 个答案:

答案 0 :(得分:1)

尝试一下:

library(ggplot2)
library(wrapr)

df <- data.frame(x = rnorm(100))

df %.>%
  ggplot(data = ., aes(y = x)) +
  geom_boxplot() +
  geom_hline(yintercept = 0.0) +
  geom_text(aes(
      x = -.3,
      y = min(.$x),
      label = 'test'
    ),
    check_overlap = TRUE
  ) +
  geom_segment(aes(
      x = -.3,
      xend = -.2,
      y = min(.$x) * .95,
      yend = 0
    ),
    size = 1,
    arrow = arrow()
  )

如果要弯曲线,请使用geom_curve代替geom_segment,并使用curvature参数调整曲率。