我想在 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))
但是,如果您真的想要横杆,可以使用
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))
请注意,丢失的段由
limits
删除。我添加到 scale_y_continuous()
的声明.
关于r - 使用 ggplot2 绘制误差线时抑制一些交叉线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48817930/