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

如何在R中绘制X轴为分类变量的累积死亡率折线图

绘制不同饲养条件下个体发育累积死亡率折线图

数据准备

先把你的数据导入R,同时将X1设为有序分类变量,确保生命阶段的顺序符合研究逻辑:

# 构造数据框
mort_data <- data.frame(
  X2 = rep(c("a", "b", "c", "d", "e"), each = 6),
  X1 = rep(c("E", "1", "2", "3", "4", "P"), 5),
  Cumulative.%.mortality = c(
    19.64285714, 28.16901408, 26.66666667, 49.72972973, 78.84615385,
    26.78571429, 32.3943662, 29.09090909, 51.89189189, 79.80769231,
    26.78571429, 40.84507042, 31.51515152, 52.97297297, 79.80769231,
    28.57142857, 53.52112676, 33.93939394, 56.21621622, 79.80769231,
    30.35714286, 56.33802817, 41.81818182, 58.37837838, 82.21153846,
    30.35714286, 56.33802817, 42.42424242, 58.37837838, 82.21153846
  )
)

# 指定X1的有序级别,保证生命阶段顺序正确
mort_data$X1 <- factor(mort_data$X1, levels = c("E", "1", "2", "3", "4", "P"), ordered = TRUE)

方法一:基础plot函数实现

你之前用plot()直接生成箱线图,是因为R默认对分类变量采用箱线图可视化逻辑。可以通过手动循环分组绘制折线:

# 初始化画布,先绘制第一个饲养条件的折线与点
plot(x = mort_data$X1[mort_data$X2 == "a"], 
     y = mort_data$Cumulative.%.mortality[mort_data$X2 == "a"],
     type = "b",  # 同时显示点和折线
     col = "red",
     xlab = "生命阶段",
     ylab = "累积死亡率(%)",
     ylim = c(0, 100),  # 固定y轴范围,确保所有数据点可见
     main = "不同饲养条件下的累积死亡率"
)

# 循环添加剩余饲养条件的折线
cols <- c("blue", "green", "orange", "purple")
conditions <- c("b", "c", "d", "e")
for(i in 1:length(conditions)){
  lines(x = mort_data$X1[mort_data$X2 == conditions[i]],
        y = mort_data$Cumulative.%.mortality[mort_data$X2 == conditions[i]],
        type = "b",
        col = cols[i])
}

# 添加图例区分不同饲养条件
legend("topleft", legend = c("a", "b", "c", "d", "e"),
       col = c("red", cols), lty = 1, pch = 1, bty = "n")

方法二:ggplot2实现(更简洁高效)

使用ggplot2包可以更直观地实现分组折线图,代码可读性更强:

# 未安装ggplot2时先执行安装
# install.packages("ggplot2")
library(ggplot2)

ggplot(mort_data, aes(x = X1, y = Cumulative.%.mortality)) +
  geom_line(aes(color = X2, group = X2)) +  # 按饲养条件分组绘制折线
  geom_point(aes(color = X2)) +  # 添加数据点
  labs(x = "生命阶段", y = "累积死亡率(%)", 
       title = "不同饲养条件下的累积死亡率",
       color = "饲养条件") +
  theme_minimal() +
  ylim(0, 100)  # 确保y轴覆盖所有数据范围

两种方法都能实现你的需求:为每个饲养条件绘制独立折线,连接对应生命阶段的累积死亡率数据点。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 15:32:35