使用geom_segment指示超出log10比例限制的geom_errorbar

时间:2019-04-07 00:29:01

标签: r ggplot2

我有一些数据,其中一些估计值的误差范围很大。我想通过设置图表极限来绘制有意义的比例。但是,我还要指出误差条超出限制的地方。最好使用箭头,如果可能的话,最好使用箭头,而不使用geom_segment,因为它似乎不能很好地适应log10刻度。之后,将在红色箭头下方绘制。解决方案是在geom_errorbar超出ggplot中的绘图限制的地方添加箭头或其他指示。

set.seed(12345)
data <- data.frame(A = rnorm(10), 
                   group = c(rep("Dog", 5), rep("Cat", 5)),
                   Time = c(rep(1:5), rep(1:5)))
data <- data %>% mutate(
  SE = abs(rnorm(10)),
  B = A + SE,
  C = A - SE
  )

upper <- (with(data, max(B)) - 0.5) %>% exp()
lower <- (with(data, min(C)) + 0.5) %>% exp()

data <- data %>% mutate_at(vars(A, B, C), funs(exp))

library (ggplot2)
ggplot(data = data, aes(y = A, x = Time, color = group)) +
  geom_point(position = position_dodge(width = 0.2), size = 2) +
  geom_errorbar(aes(ymin = C, ymax = B), position = "dodge", width = 0.2, size = 0.8) +
  coord_cartesian(ylim = c(lower, upper)) +
  scale_y_log10()

enter image description here

1 个答案:

答案 0 :(得分:0)

我找到了一个不太精确的解决方案。您可以一次为向上的三角形调用geom_point,为向下的三角形再次调用geom_point。唯一的问题是,coord_cartesian似乎没有将限制精确地设置为指定的值,因此您必须对每个限制加或减以使三角形位于正确的位置。另外,由于position_dodge已经被使用,所以position_nudge不可用。它涉及猜测要添加到geom_point的y坐标的值。

如果有更好的解决方案,请发表评论。

    library(ggplot2)
    library(tidyverse)

    set.seed(12345)
    data <- data.frame(A = rnorm(10), 
                       group = c(rep("Dog", 5), rep("Cat", 5)),
                       Time = c(rep(1:5), rep(1:5)))
    data <- data %>% mutate(
      SE = abs(rnorm(10)),
      B = A + SE,
      C = A - SE
      )

    upper <- (with(data, max(B)) - 0.5) %>% exp()
    lower <- (with(data, min(C)) + 0.5) %>% exp()

    data <- data %>% mutate_at(vars(A, B, C), funs(exp))

    data <- data %>% 
      mutate(upper_out = ifelse(B > upper, upper, NA),
             lower_out = ifelse(C < lower, lower, NA))

    ggplot(data = data, aes(y = A, x = Time, color = group, fill = group)) +
      geom_point(position = position_dodge(width = 0.2), size = 2) +
      geom_errorbar(aes(ymin = C, ymax = B), position = "dodge", width = 0.2, size = 0.8) +
      geom_point(aes(y = upper_out + 1.02), shape = 24, 
          position = position_dodge(width = 0.2), size = 4, show.legend = F) +
      geom_point(aes(y = lower_out - 0.013), shape = 25, 
          position = position_dodge(width = 0.2), size = 4, show.legend = F) +
      scale_y_log10() +
      coord_cartesian(ylim = c(lower, upper))

enter image description here