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

如何在ggplot2中绘制因子并排的散点图?

问题描述

我有如下数据表,想制作散点图,让同一Phenotype类别下不同Method因子对应的点并排显示,请问能否实现?以下是当前使用的ggplot2代码、数据:

现有代码:

fishers.drugs %>%
  ggplot(aes(fill = Method, color=Method, x=Phenotype, y=OR, ymin = Lower.CI, ymax = Upper.CI)) +
  geom_errorbar(aes(color=Method), show.legend = FALSE)+
  geom_point(shape=21, size=12) +
  scale_fill_manual(values = c("yellow", "cyan4"))+
  scale_color_manual(values = c("black","black"))+
  theme_bw(base_size = 20) +
  theme(text=element_text(size=34),axis.text.x = element_text(hjust = 1))  

数据:

fishers.drugs <- structure(list(Phenotype = c("SCZ", "BD", "MDD", "PTSD", "SCZ", 
"BD", "MDD", "PTSD"), P.value = c(3.6e-05, 7.6e-06, 0.0023, 0.03, 
0.29, 0.043, 0.19, 0.71), Method = c("Pairwise", "Pairwise", 
"Pairwise", "Pairwise", "MAGMA", "MAGMA", "MAGMA", "MAGMA"), 
    OR = c(3.1, 3.7, 2.53996, 2.6, 1.27, 1.9, 1.574722, 0.8), 
    Lower.CI = c(1.80232, 2.124302, 1.352569, 0.9064928, 0.5729662, 
    0.9067536, 0.7052697, 0.09566171), Upper.CI = c(4.846504, 
    6.090133, 4.40825, 5.8462159, 2.4825332, 3.6740963, 3.0758353, 
    3.01399383)), class = "data.frame", row.names = c(NA, -8L
))
解决方案

当然可以实现,核心是给geom_point和geom_errorbar添加**position = position_dodge(width = 0.5)**参数(width值可按需调整),让同一Phenotype下的不同Method元素横向错开,避免重叠。

修改后的完整代码:

library(ggplot2)
library(dplyr)

fishers.drugs <- structure(list(Phenotype = c("SCZ", "BD", "MDD", "PTSD", "SCZ", 
"BD", "MDD", "PTSD"), P.value = c(3.6e-05, 7.6e-06, 0.0023, 0.03, 
0.29, 0.043, 0.19, 0.71), Method = c("Pairwise", "Pairwise", 
"Pairwise", "Pairwise", "MAGMA", "MAGMA", "MAGMA", "MAGMA"), 
    OR = c(3.1, 3.7, 2.53996, 2.6, 1.27, 1.9, 1.574722, 0.8), 
    Lower.CI = c(1.80232, 2.124302, 1.352569, 0.9064928, 0.5729662, 
    0.9067536, 0.7052697, 0.09566171), Upper.CI = c(4.846504, 
    6.090133, 4.40825, 5.8462159, 2.4825332, 3.6740963, 3.0758353, 
    3.01399383)), class = "data.frame", row.names = c(NA, -8L
))

fishers.drugs %>%
  ggplot(aes(fill = Method, color=Method, x=Phenotype, y=OR, ymin = Lower.CI, ymax = Upper.CI)) +
  geom_errorbar(aes(color=Method), show.legend = FALSE, position = position_dodge(width = 0.5))+
  geom_point(shape=21, size=12, position = position_dodge(width = 0.5)) +
  scale_fill_manual(values = c("yellow", "cyan4"))+
  scale_color_manual(values = c("black","black"))+
  theme_bw(base_size = 20) +
  theme(text=element_text(size=34),axis.text.x = element_text(hjust = 1))  

关键细节

  • position_dodge(width = 0.5):控制同一x轴分类下不同分组元素的横向偏移幅度,值越大偏移越远,可根据点的大小调整,确保点之间既不重叠又保持在对应类别区域内。
  • 必须给geom_errorbar和geom_point设置相同的position参数,这样误差线才能和对应点精准对齐。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 14:18:28