ggplot2多因子顺序控制:如何让较大OR值的类别前置?
调整ggplot2中因子顺序,让OR更大的类别优先显示
我用ggplot2绘制了如下图表,想要调整因子顺序,让OR(比值比)更大的类别排在前面(也就是青色的Pairwise类别放在红色的MAGMA类别之前),但尝试后没能成功。以下是我的代码、数据和当前图表:
当前代码
ggplot(df, aes(x = Gene.Set.Size, y = OR, label =P.value, color = Method, group = Method)) + geom_point(position=position_dodge(width=0.5)) + ggrepel::geom_text_repel(size = 6, box.padding = 1, segment.angle = 20, position=position_dodge(width=0.5))+ geom_pointrange(aes(ymax = UpperCI, ymin = LowerCI),position=position_dodge(width=0.5)) + theme_bw() + theme(text=element_text(size=25),axis.text.x = element_text(angle = 45, hjust = 1)) + ylab("Odds ratio") + xlab("Gene set size") + theme(plot.margin = unit(c(2,2,2,2), "cm"))
数据
> dput(df) structure(list(Method = structure(c(1L, 1L, 1L, 2L, 2L, 2L), .Label = c("MAGMA", "Pairwise"), class = "factor"), P.value = c(8.74e-28, 1.33e-56, 5.57e-92, 1.63e-44, 4.23e-71, 2.78e-95), OR = c(1.39, 1.424668, 1.4, 1.513, 1.478208, 1.409563), UpperCI = c(1.481491, 1.487065, 1.446039, 1.601557, 1.417117, 1.455425), LowerCI = c(1.316829, 1.364601, 1.356358, 1.42, 1.541768, 1.365056), Gene.Set.Size = structure(c(1L, 2L, 3L, 1L, 2L, 3L), .Label = c("500", "1000", "2000"), class = "factor")), row.names = c(NA, -6L), class = "data.frame")
当前图表

解决方案
问题根源
你的Method因子默认水平顺序是MAGMA在前、Pairwise在后,ggplot2会严格遵循因子的内置顺序来渲染分组元素,所以默认会把MAGMA放在前面。
方法1:手动指定因子顺序
如果你明确知道想要的顺序,直接修改Method的因子水平即可:
# 将Pairwise设为第一个水平,MAGMA为第二个 df$Method <- factor(df$Method, levels = c("Pairwise", "MAGMA"))
方法2:按OR均值动态排序(通用场景)
如果后续数据可能变化,想要自动按平均OR从大到小排序,用reorder函数:
# 按每个Method的平均OR倒序排列因子水平 df$Method <- reorder(df$Method, -df$OR, FUN = mean)
修改后的完整代码
把因子顺序调整代码放在绘图代码之前,完整代码如下:
# 先调整因子顺序(二选一即可) df$Method <- factor(df$Method, levels = c("Pairwise", "MAGMA")) # df$Method <- reorder(df$Method, -df$OR, FUN = mean) # 绘图代码不变 ggplot(df, aes(x = Gene.Set.Size, y = OR, label = P.value, color = Method, group = Method)) + geom_point(position=position_dodge(width=0.5)) + ggrepel::geom_text_repel(size = 6, box.padding = 1, segment.angle = 20, position=position_dodge(width=0.5))+ geom_pointrange(aes(ymax = UpperCI, ymin = LowerCI), position=position_dodge(width=0.5)) + theme_bw() + theme(text=element_text(size=25), axis.text.x = element_text(angle = 45, hjust = 1)) + ylab("Odds ratio") + xlab("Gene set size") + theme(plot.margin = unit(c(2,2,2,2), "cm"))
效果说明
调整因子顺序后,position_dodge会按照新的水平顺序排列分组点和误差线,Pairwise就会显示在MAGMA的前方,符合你想要的OR更大的类别在前的需求。
内容的提问来源于stack exchange,提问作者Workhorse
相关产品推荐
相关产品推荐

