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

如何为死、活线虫双变量创建同Y轴的分处理并列箱线图

杀线虫剂处理效果并列箱线图解决方案

核心思路

当前数据集为宽格式,死亡、存活线虫为独立列,无法直接绘制分组并列箱线图。首先需要将数据集转换为长格式:新增「存活状态」列标识数值属于死亡/存活线虫、新增「数量」列存储对应计数值,之后以处理组为X轴、数量为Y轴、存活状态为分组变量绘图,即可实现同一Y轴下两个指标的并列展示。

R语言(ggplot2)实现方案

# 加载依赖包
library(tidyverse)

# 读取数据集(请根据你的数据存储路径调整读取方式,以下为示例)
# nematode_data <- read.csv("你的数据路径.csv", header = T, sep = ",")

# 宽表转长表
nematode_long <- nematode_data %>%
  pivot_longer(cols = c(Dead, Alive),
               names_to = "存活状态",
               values_to = "线虫数量")

# 绘制并列箱线图
ggplot(nematode_long, aes(x = Treatment, y = 线虫数量, fill = 存活状态)) +
  geom_boxplot(position = position_dodge(width = 0.8), width = 0.7) +
  # 自定义颜色和图例标签
  scale_fill_manual(values = c("Dead" = "darkred", "Alive" = "darkgreen"),
                    labels = c("死亡线虫", "存活线虫")) +
  labs(x = "杀线虫剂处理方案", y = "线虫数量", fill = "指标类型") +
  theme_bw() +
  # 旋转X轴标签避免文字重叠
  theme(axis.text.x = element_text(angle = 45, hjust = 1, size = 10))

Python(seaborn+matplotlib)实现方案

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

# 读取数据集(请根据你的数据存储路径调整读取方式,以下为示例)
# nematode_df = pd.read_csv("你的数据路径.csv")

# 宽表转长表
nematode_long = pd.melt(
    nematode_df,
    id_vars=["Rep", "Treatment"],
    value_vars=["Dead", "Alive"],
    var_name="存活状态",
    value_name="线虫数量"
)

# 绘制并列箱线图
plt.figure(figsize=(14, 7))
sns.boxplot(
    data=nematode_long,
    x="Treatment",
    y="线虫数量",
    hue="存活状态",
    dodge=True,
    palette=["darkred", "darkgreen"]
)
# 调整图表样式
plt.xlabel("杀线虫剂处理方案", fontsize=12)
plt.ylabel("线虫数量", fontsize=12)
plt.xticks(rotation=45, ha="right", fontsize=10)
plt.legend(title="指标类型", labels=["死亡线虫", "存活线虫"], fontsize=10)
plt.tight_layout()
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 01:54:01