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

如何用R语言barplot函数为多变量聚合数据的条形图添加物种名

按物种分组绘制胸径与树高均值成对条形图的解决方案

问题背景

我有一份名为ufc.csv的树木数据文件,使用read.csv()读取后,通过aggregate函数按物种名(Species)计算胸径(Dbh)和树高(Height)的均值:

ufcmeans = aggregate(x = ufc[,4:5], by = ufc[3], FUN = mean, na.rm = TRUE)

删除首行空值后得到对应数据框。希望绘制条形图,让每个物种对应一对Dbh和Height均值条形,物种名标注在条形对下方。尝试将ufcmeans转矩阵传入barplot()时出错;去除物种列后绘图成功但无法正确添加物种名,求解决方法。


两种可行解决方案

方法一:基础R barplot() 实现

核心是将数据整理为行=物种、列=指标均值的结构,利用beside=TRUE实现并排条形,同时通过names.arg指定物种名。

  1. 确认数据结构(确保第一列是物种名,后两列是均值):
# 若列名不明确,手动指定
colnames(ufcmeans) <- c("Species", "Dbh_mean", "Height_mean")
  1. 提取数值矩阵并绘图:
# 提取数值部分,将物种名设为矩阵行名
data_mat <- as.matrix(ufcmeans[, -1])
rownames(data_mat) <- ufcmeans$Species

# 绘制成对条形图
barplot(data_mat, 
        beside = TRUE,  # 开启并排模式
        names.arg = ufcmeans$Species,  # 指定x轴物种标签
        col = c("steelblue", "forestgreen"),
        xlab = "物种", 
        ylab = "均值",
        main = "不同物种胸径与树高均值对比")

# 添加图例区分指标
legend("topright", 
       legend = colnames(data_mat), 
       fill = c("steelblue", "forestgreen"))

方法二:ggplot2 实现(更灵活美观)

ggplot2无需手动处理矩阵,通过长格式数据即可轻松实现并排条形:

  1. 安装并加载依赖包:
# install.packages(c("ggplot2", "tidyr"))
library(ggplot2)
library(tidyr)
  1. 将宽格式数据转为长格式:
ufc_long <- pivot_longer(ufcmeans, 
                         cols = -Species,  # 排除物种列
                         names_to = "指标", 
                         values_to = "均值")
  1. 绘制条形图:
ggplot(ufc_long, aes(x = Species, y = 均值, fill = 指标)) +
  geom_bar(stat = "identity", position = position_dodge()) +  # 并排条形
  labs(x = "物种", y = "均值", title = "不同物种胸径与树高均值对比") +
  scale_fill_manual(values = c("steelblue", "forestgreen")) +
  theme_bw()  # 清爽主题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 20:56:18