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

如何将观测行转换为整洁数据以绘制ggplot箱线图?

宽格式转长格式并绘制ggplot箱线图

1. 宽格式转长格式

你的数据是典型的宽格式,需要转成长格式整洁数据才能用ggplot绘制分组箱线图。以下两种方法适配行列数不固定的场景:

方法1:使用tidyverse的pivot_longer()(推荐)

pivot_longer()可灵活指定转换列,不管有多少个重复测量列(如V1、V2...Vn)都能处理:

先加载包并导入数据:

library(tidyverse)

# 你的示例数据
df <- structure(list(markerID = c("1", "2", "3", "4", "5", "6", "7", 
"8", "9", "10", "11", "12", "13", "14", "15"), V1 = c(0.863636363636364, 
0.886363636363636, 0.886363636363636, 0.795454545454545, 0.795454545454545, 
0.863636363636364, 0.931818181818182, 0.909090909090909, 0.840909090909091, 
0.863636363636364, 0.886363636363636, 0.795454545454545, 0.818181818181818, 
0.863636363636364, 0.886363636363636), V2 = c(0.840909090909091, 
0.840909090909091, 0.909090909090909, 0.772727272727273, 0.772727272727273, 
0.909090909090909, 0.886363636363636, 0.886363636363636, 0.954545454545455, 
0.75, 0.818181818181818, 0.772727272727273, 0.681818181818182, 
0.863636363636364, 0.840909090909091), V3 = c(0.795454545454545, 
0.840909090909091, 0.886363636363636, 0.818181818181818, 0.818181818181818, 
0.795454545454545, 0.818181818181818, 0.863636363636364, 0.818181818181818, 
0.818181818181818, 0.931818181818182, 0.772727272727273, 0.772727272727273, 
0.886363636363636, 0.886363636363636)), class = "data.frame", row.names = c(NA, 
-15L))

执行转换:

# 转换为长格式:排除markerID列,其他列转为replicate和rate
df_long <- df %>%
  pivot_longer(cols = -markerID,  # 除markerID外的所有列都参与转换
               names_to = "replicate",  # 原列名存入replicate列
               values_to = "rate",  # 原列值存入rate列
               names_prefix = "V")  # 移除列名中的"V",让replicate显示为数字

转换后的数据结构与你需求一致:

markerID replicate      rate
       1          1 0.8636364
       1          2 0.8409091
       1          3 0.7954545
       2          1 0.8863636
       ...

方法2:使用reshape2的melt()

若习惯用reshape2包,也可通过melt()实现:

library(reshape2)

df_long <- melt(df, 
                id.vars = "markerID",  # 指定标识列
                variable.name = "replicate",  # 原列名的列名
                value.name = "rate")  # 原列值的列名
# 可选:移除replicate列的"V"前缀,转为数字格式
df_long$replicate <- gsub("V", "", df_long$replicate)

2. 绘制ggplot箱线图

转换完成后,即可按markerID分组绘制箱线图:

ggplot(df_long, aes(x = markerID, y = rate)) +
  geom_boxplot(fill = "#619CFF", alpha = 0.7) +  # 设置箱线图填充色与透明度
  labs(title = "各markerID的rate分布箱线图",
       x = "markerID",
       y = "rate") +
  theme_minimal()

若需展示原始数据点,可添加geom_jitter()避免点重叠:

ggplot(df_long, aes(x = markerID, y = rate)) +
  geom_boxplot(fill = "#619CFF", alpha = 0.7) +
  geom_jitter(width = 0.2, color = "black", size = 1) +  # 散点偏移设置
  labs(title = "各markerID的rate分布箱线图(含原始数据)",
       x = "markerID",
       y = "rate") +
  theme_minimal()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 22:14:51