如何在R语言中根据数值为geom_errorbarh设置不同颜色
解决geom_errorbarh条件着色问题
要实现根据average_att的数值给误差棒设置不同颜色,你可以通过在aes()中映射colour参数,并结合条件判断来实现,具体步骤如下:
在
geom_errorbarh的aes中添加colour映射,用case_when定义颜色规则:- 当
average_att > 1时,颜色标记为"red" - 当
average_att < -1时,颜色标记为"blue" - 其余情况保留原代码的"cyan4"作为默认颜色
- 当
用
scale_colour_identity()让ggplot直接使用定义的颜色字符串,无需额外映射
修改后的完整代码:
library(ggplot2) forestdata <- data.frame(city = c("HK6", "IS2", "CR5"), average_att = c(0.752007081, -4.384720798, -0.66515768), average_att_lower = c(-1.284027031, -6.088057285, -3.094599095), average_att_upper = c(2.073787674, -2.637218695, 1.766942459)) ggplot(forestdata, aes(average_att, city))+ geom_errorbarh(aes(xmax = average_att_upper, xmin = average_att_lower, colour = case_when( average_att > 1 ~ "red", average_att < -1 ~ "blue", TRUE ~ "cyan4" )), size= 1, height = 0.1) + geom_point(size=2, color = "black")+ scale_x_continuous(limits= c(-6.5, 6.5))+ geom_vline(aes(xintercept = 0), color="darkgoldenrod2", size = 1, alpha=0.5) + scale_colour_identity()
代码说明
case_when:实现多条件分支判断,精准匹配你需要的数值区间scale_colour_identity():因为我们直接指定了具体颜色字符串,这个函数能让ggplot直接应用这些颜色值,避免自动生成颜色映射
修改后,IS2的误差棒会变为蓝色(average_att=-4.38<-1),HK6的误差棒保持原有的cyan4(average_att=0.75在-1到1之间),完全符合你的需求。
内容的提问来源于stack exchange,提问作者Chauncey Tong
相关产品推荐
相关产品推荐

