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

如何用ggplot2基于给定浮游植物数据创建堆叠柱状图?

用ggplot2绘制浮游植物堆叠柱状图的解决方案

你的核心问题是当前数据为宽格式,而ggplot2绘制堆叠柱状图需要长格式数据(即每一行对应一个站点的一种浮游植物类型及其数量)。以下是完整的实现步骤:

1. 加载所需R包

需要用到tidyverse(包含ggplot2和数据重塑工具tidyr):

library(tidyverse)

2. 导入数据

将你提供的数据转换成R数据框:

df <- data.frame(
  Station = c("A3", "A6", "A8", "B", "C", "D", "E", "F", "G", "H", "I", "J"),
  Salinity = c(18.3, 27.4, 25.7, 29.77785714, 31.283, 32.21625, 32.23, 32.8, 33.185, 33.67, 34.33294118, 34.537),
  CentricD = c(181000, 584666.6667, 625071.4286, 503693.8776, 266991.5966, 349375, 379200, 559000, 209276.7857, 98714.28571, 113302.521, 68142.85714),
  PennateD = c(26500, 4666.666667, 2000, 2000, 5285.714286, 6437.5, 466.6666667, 0, 2125, 1812.5, 1764.705882, 1000),
  Dinoflag = c(1000, 11666.66667, 74000, 6642.857143, 10714.28571, 6142.857143, 3714.285714, 333.3333333, 5714.285714, 7125, 40142.85714, 12842.85714),
  MarineFlag = c(15500, 0, 294.1176471, 7642.857143, 71352.94118, 39651.78571, 12228.57143, 0, 27937.5, 6410.714286, 5588.235294, 20228.57143),
  Cilliates = c(2250, 61333.33333, 1907.563025, 5622.44898, 12067.22689, 4339.285714, 4504.761905, 11000, 3062.5, 7750, 9260.504202, 5271.428571)
)

3. 数据重塑(宽格式转长格式)

使用pivot_longer函数将浮游植物的各列合并为两列:type(浮游植物类型)和abundance(数量),保留Station列:

df_long <- df %>%
  select(Station, CentricD, PennateD, Dinoflag, MarineFlag, Cilliates) %>%  # 只保留需要的列
  pivot_longer(cols = -Station, names_to = "type", values_to = "abundance")

4. 绘制堆叠柱状图

用ggplot2绘制,指定x轴为Station,y轴为数量abundance,填充色由type区分:

ggplot(df_long, aes(x = Station, y = abundance, fill = type)) +
  geom_bar(stat = "identity") +  # stat="identity"表示直接使用y轴数值
  labs(title = "各站点浮游植物组成与总量",
       x = "站点",
       y = "浮游植物数量",
       fill = "浮游植物类型") +
  theme_minimal()

额外优化(可选)

如果需要按盐度排序站点,可以在绘图前对Station按Salinity排序:

df <- df %>% arrange(Salinity)
df$Station <- factor(df$Station, levels = df$Station)  # 把Station转为有序因子

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 18:08:09