使用R基础barplot函数绘制正负值分色显示的条形图
R基础barplot实现正负值分色条形图方案
核心实现逻辑
仅需要为barplot函数的col参数传入和数值长度一致的动态颜色向量,根据数值正负匹配对应颜色即可,无需引入额外包。
修改后完整代码
# 构造测试数据 df <- data.frame(MM=(1:12), value=rnorm(12)) options(repr.plot.width=6, repr.plot.height=4) label <- seq(1:12) a <- barplot(df$value, names=label, # 核心改动:按正负值匹配颜色 col = ifelse(df$value >= 0, 'deepskyblue3', 'red'), xaxt = "n", yaxt = "n", ) axis(1, cex.axis=0.55, las=1, at=a, labels=label) axis(2, las='2', cex.axis=0.6) abline(h = 0, col = "black")
代码说明
ifelse(df$value >= 0, 'deepskyblue3', 'red')会自动生成与df$value长度完全匹配的颜色向量,正值/0匹配蓝色,负值匹配红色- 保留了你原有代码的坐标轴、尺寸、0参考线的全部设置,无需调整其他逻辑
- 如果需要单独为0值设置其他颜色,可调整判断条件实现,比如:
col = dplyr::case_when( df$value > 0 ~ 'deepskyblue3', df$value == 0 ~ 'gray', df$value < 0 ~ 'red' )
内容的提问来源于stack exchange,提问作者gianca
相关产品推荐
相关产品推荐

