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

ggplot分面绘制各深度下丰度最高的前3个物种

解决方案

步骤1:加载依赖包

先安装并加载数据处理和绘图所需的包:

install.packages(c("dplyr", "ggplot2"))
library(dplyr)
library(ggplot2)

步骤2:筛选各深度下丰度Top3物种

先计算每个深度下各物种的总丰度,再提取每个深度排名前3的物种,最后匹配回原始数据:

# 计算每个深度下各物种的总丰度(若需用平均丰度,把sum换成mean即可)
top_species <- df %>%
  group_by(depth, species) %>%
  summarize(total_count = sum(count), .groups = "drop") %>%
  group_by(depth) %>%
  slice_max(total_count, n = 3) %>% # 提取每个深度总丰度前3的物种
  select(depth, species) # 保留关键匹配字段

# 过滤原始数据,仅保留各深度的Top3物种
filtered_df <- df %>%
  inner_join(top_species, by = c("depth", "species"))

步骤3:绘制分面柱状图

用ggplot2生成按深度分面的柱状图,同时展示误差棒:

ggplot(filtered_df, aes(x = factor(year), y = count, fill = species)) +
  geom_col(position = position_dodge(width = 0.8), alpha = 0.8) +
  geom_errorbar(
    aes(ymin = count - se, ymax = count + se),
    width = 0.2,
    position = position_dodge(width = 0.8)
  ) +
  facet_wrap(~depth, scales = "free_y") + # 分面y轴自由缩放,适配不同深度的数值范围
  labs(
    x = "年份",
    y = "物种数量",
    fill = "物种",
    title = "各深度下丰度Top3物种的年度数量分布"
  ) +
  theme_bw() +
  theme(plot.title = element_text(hjust = 0.5))

针对多位点数据的补充

如果你的实际数据需要按深度+位点组合筛选Top3物种,只需调整分组逻辑:

top_species <- df %>%
  group_by(depth, site, species) %>% # 新增site分组维度
  summarize(total_count = sum(count), .groups = "drop") %>%
  group_by(depth, site) %>%
  slice_max(total_count, n = 3) %>%
  select(depth, site, species)

filtered_df <- df %>%
  inner_join(top_species, by = c("depth", "site", "species"))

# 绘图时分面可改为depth与site的组合,例如:
# facet_grid(depth ~ site)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 15:02:13