我想在其中的映射语句中添加一个 if else 语句geom_errorbar(),如果它满足特定条件,则会删除较低的错误栏。请参阅以下玩具数据集和图表
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
Run Code Online (Sandbox Code Playgroud)
请注意,上面示例中参数中的ifelse()语句确实有效,将下误差条减少到零,但它仍然显示误差条的水平部分。我如何抑制这个,所以只出现上面的误差条?我尝试在条件语句中输入而不是 0,但收到一条错误消息。也许是一个有条件的论证?ymingeom_errorbarNULLifelse()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))
Run Code Online (Sandbox Code Playgroud)
但是,如果您真的想要横杆,则可以使用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))
Run Code Online (Sandbox Code Playgroud)
请注意,limits我添加到scale_y_continuous().