You need to enable JavaScript to run this app. 如何用R的ggplot绘制按月份分组的鲨鱼物种数量堆叠柱状图
优惠活动
大模型
产品
解决方案
定价
更多

如何用R的ggplot绘制按月份分组的鲨鱼物种数量堆叠柱状图

R语言鲨鱼捕获数据堆叠条形图实现方案

前置预处理

先修正月份因子顺序,避免绘图时月份按字母排序:

# 按自然月份顺序设置因子水平
sharks$Month <- factor(sharks$Month, levels = month.name)

注:如果导入数据时列名空格被自动替换为点,后续代码中`Species Name`请替换为`Species.Name`。

需求1:全年单张堆叠条形图

你现有代码的核心问题是原始数据没有提前计算好的count列,不需要手动指定y值,使用geom_bar默认的计数统计规则即可实现:

绝对计数堆叠(y轴为当月总捕获量)

ggplot(sharks, aes(fill = `Species Name`, x = Month)) + 
  # position = "stack" 为普通堆叠,stat="count"自动统计分组数量
  geom_bar(position = "stack", stat = "count") +
  labs(y = "捕获数量", x = "月份", fill = "鲨鱼物种") +
  # 倾斜x轴标签避免重叠
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

百分比堆叠(y轴为当月物种占比)

如果需要看各物种当月占比,修改position参数即可:

ggplot(sharks, aes(fill = `Species Name`, x = Month)) + 
  geom_bar(position = "fill", stat = "count") +
  labs(y = "物种占比", x = "月份", fill = "鲨鱼物种") +
  # y轴转为百分比格式
  scale_y_continuous(labels = scales::percent) +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

如果确实需要提前计算计数列使用stat="identity"写法,可以先做聚合:

library(dplyr)
sharks_count <- sharks |> 
  count(Month, `Species Name`, name = "count")

ggplot(sharks_count, aes(fill = `Species Name`, y = count, x = Month)) + 
  geom_bar(position = "stack", stat = "identity")

需求2:每月单独的物种数量条形图

使用分面功能即可批量生成,将物种放在y轴避免24种物种名称重叠:

ggplot(sharks, aes(y = `Species Name`)) + 
  geom_bar() +
  # 按月份分面,每个分面对应一个月的统计
  facet_wrap(~Month, scales = "free_x") +
  labs(x = "当月捕获数量", y = "鲨鱼物种")

如果需要导出为单独的图片文件,可以使用循环实现:

library(dplyr)
for (month_name in levels(sharks$Month)) {
  # 过滤单月数据
  monthly_data <- filter(sharks, Month == month_name)
  # 跳过无数据的月份
  if(nrow(monthly_data) == 0) next
  # 绘图
  p <- ggplot(monthly_data, aes(y = `Species Name`)) +
    geom_bar() +
    labs(title = paste0(month_name, "鲨鱼捕获统计"), x = "捕获数量", y = "物种")
  # 保存图片
  ggsave(paste0(month_name, "_鲨鱼捕获统计.png"), p, width = 8, height = 6)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 20:45:05