使用ggplot2绘制误差条时抑制一些交叉开关

时间:2018-02-15 23:30:03

标签: r ggplot2

我想在geom_errorbar()内的映射语句中添加if else语句,如果满足某个条件,则会删除较低的错误栏。请参阅以下玩具数据集和图表

df <- data.frame(change = rep(c("increased", "reduced", "same"), 2),
                 group = rep(c("0", "1"), each = 3),
                 freq = c(0, 17, 21, 1, 27, 9),
                 perc = c(0, 44.73, 55.26, 2.70, 72.97, 24.32),
                 se = c(NaN, 12.06, 10.85, 16.22, 8.54, 14.30))

polytPlot <- ggplot(dfT, aes(y = perc, x = change, fill = Group)) +
                    geom_bar(stat = "identity", position = "dodge") +
                    scale_y_continuous(breaks=pretty) + 
                    ylab("% of group total") +
                    xlab("Change") +
                    geom_errorbar(aes(ymin = ifelse(perc-se < 0, 0, perc-se), ymax = perc+se), position = position_dodge(.9), width = .1)
polytPlot

请注意,上例ifelse()的{​​{1}}参数中的ymin语句有效,将较低的错误栏降低为零,但它仍然显示错误栏的水平部分。我该如何抑制它,所以只出现上面的错误条?我尝试在条件geom_errorbar语句中输入NULL而不是0,但收到了错误消息。也许是ifelse()的条件参数?

1 个答案:

答案 0 :(得分:3)

一种选择是完全删除水平横杆:

ggplot(df, aes(y = perc, x = change, fill = group)) +
  geom_bar(stat = "summary", position = "dodge") +
  scale_y_continuous(breaks=pretty) + 
  ylab("% of group total") +
  xlab("Change") +
  geom_linerange(aes(ymin = ifelse(perc-se < 0, 0, perc-se), ymax = perc+se), position = position_dodge(.9))

enter image description here

但是,如果你真的想要横杆,你可以使用geom_segment()分别绘制它们:

ggplot(df, aes(y = perc, x = change, fill = group)) +
  geom_bar(stat = "summary", position = "dodge") +
  scale_y_continuous(breaks=pretty, limits = c(0, 85)) + 
  ylab("% of group total") +
  xlab("Change") +
  geom_linerange(aes(ymin = ifelse(perc-se < 0, 0, perc-se), ymax = perc+se), position = position_dodge(.9)) +
  geom_segment(aes(x = as.numeric(change) + .45*(as.numeric(group)-1.5) - .05,
                   xend = as.numeric(change) + .45*(as.numeric(group)-1.5) + .05,
                   y = perc + se, yend = perc + se)) +
  geom_segment(aes(x = as.numeric(change) + .45*(as.numeric(group)-1.5) - .05,
                   xend = as.numeric(change) + .45*(as.numeric(group)-1.5) + .05,
                   y = perc - se, yend = perc - se))

enter image description here

请注意,我添加到limits的{​​{1}}语句删除了缺失的细分。