r - 使用 ggplot2 绘制误差线时抑制一些交叉线

标签 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() ymin 中的声明geom_errorbar 的论据在上面的例子中确实有效,将下误差条减少到零,但它仍然显示误差条的水平部分。我如何抑制这个,所以只出现上面的误差条?我尝试输入 NULL而不是我的条件中的 0 ifelse()语句,但收到一条错误消息。也许是 width = 的条件参数?

最佳答案

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

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 删除。我添加到 scale_y_continuous() 的声明.

关于r - 使用 ggplot2 绘制误差线时抑制一些交叉线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48817930/

相关文章:

r - 有没有办法将 rda/RData 数据从 R 加载到 SAS 中?

r - ggplot2:如何从绘图对象读取比例变换

r - ggmap 具有值的热图

R:使用 ggplot2/ggmap 的世界地图 - 如何加载 png 图像作为 map

r - 尝试在 Linux 服务器上运行多个实例时 H2o 崩溃

r - 插入符号 : Error in table(y) : attempt to make a table with >= 2^31 elements

r - 如何将内存中的变量转换为RDA格式

r - 如何保存在 Shiny 的应用程序中制作的绘图

r - 在 ggplot2 注释中使用 "*"或 "|"符号

r - ..x.. 在 ggplot 表示法中代表什么