You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为R语言barplot条形图添加数值标注与自定义分类颜色

R 基础绘图条形图修改方案

问题1:条形顶部添加数值标签

barplot函数会返回所有条形的中心点X轴坐标,我们可以存储这个坐标后配合text()函数添加标签,指定标签位置在条形正上方即可。

问题2:按季节自定义条形配色

提前建立季节到颜色的映射向量,将映射后的值传入barplot的col参数即可实现按季节分类配色。


修改后完整代码

res <- data.frame( aggregate( rentals ~ weatherCond + season, bikes, sum ))

res$weatherCond <- ordered(res$weatherCond,
levels = c(1, 2, 3, 4),
labels = c("Clear", "Fog", "Snow", "Storm"))

res$season <- factor(res$season,
levels = c(1, 2, 3, 4),
labels = c("Winter", "Spring", "Summer", "Autumn"))

# 建立季节-颜色映射
season_colors <- c(
  "Winter" = "royalblue",
  "Spring" = "forestgreen",
  "Summer" = "firebrick",
  "Autumn" = "goldenrod"
)

par(mar=c(10,4,2,1)+.5) 
# 存储barplot返回的条形中点坐标
bp <- barplot(
  res[,"rentals"], 
  names=apply( res[,1:2], 1, function(x) paste0(x[1],"_",x[2]) ), 
  las=3,
  col = season_colors[res$season] # 传入自定义配色
)

# 在条形顶部添加数值标签,pos=3表示在坐标点上方,cex调整字体大小
text(
  x = bp, 
  y = res$rentals, 
  label = res$rentals,
  pos = 3,
  cex = 0.8
)

配色方案建议

如果需要更专业、对色觉障碍用户更友好的配色,推荐使用以下两种方案:

  • 调用RColorBrewer包的Set2、Paired等离散调色板,色彩柔和区分度高
  • 调用viridis包的调色板,支持色盲友好、印刷显示效果一致

内容的提问来源于stack exchange,提问作者Embargo96

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 19:36:01