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

如何用ggplot绘制宿主-病原体组合的堆叠柱状图?

用ggplot绘制堆叠柱状图的解决方案

先把你的数据集处理成R可识别的格式,再通过分组和堆叠设置实现需求:

步骤1:准备数据

先将你的数据转换成R数据框,并创建宿主-病原体组合的分组变量:

library(tidyverse)

# 构建数据集
df <- tibble(
  host = c("bird", "bird", "bird", "bird", "fish", "fish", "fish", "mammal"),
  pathogen = c("bacteria", "virus", "helminth", "bacteria", "virus", "virus", "bacteria", "virus"),
  doses = c(2, 3, 5, 1, 6, 7, 8, 4),
  number_of_observations = c(7, 4, 6, 4, 8, 1, 4, 2)
)

# 生成宿主-病原体组合的x轴分组
df <- df %>%
  mutate(host_pathogen = str_c(host, "-", pathogen))

步骤2:绘制堆叠柱状图

用geom_col()配合堆叠参数,把不同剂量的观测数在同一宿主-病原体分组下堆叠展示:

ggplot(df, aes(x = host_pathogen, y = number_of_observations, fill = factor(doses))) +
  geom_col(position = "stack") +
  # 给每个堆叠块添加观测数标签,居中显示
  geom_text(aes(label = number_of_observations), 
            position = position_stack(vjust = 0.5), size = 3) +
  # 设置轴标签和标题
  labs(
    x = "宿主-病原体组合",
    y = "观测数量",
    fill = "剂量(doses)",
    title = "各宿主-病原体组合下不同剂量的观测数堆叠图"
  ) +
  # 倾斜x轴标签避免重叠
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

关键说明

  • 将doses转为因子,是为了让ggplot把每个剂量作为独立分组进行堆叠,而非连续变量处理。
  • position_stack(vjust = 0.5)确保数值标签居中显示在每个堆叠区块内,提升可读性。

内容的提问来源于stack exchange,提问作者K.W

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 11:13:16