如何移除finalfit::or_plot中的类别列?寻求更灵活OR可视化方法
解决finalfit::or_plot移除类别列及OR可视化替代方案
一、移除or_plot中的类别列
finalfit::or_plot生成的是ggplot2对象,因此可以通过修改ggplot主题直接移除左侧的类别列(即y轴的文本、标题和刻度):
data(iris) library(finalfit) library(dplyr) library(ggplot2) iris <- iris %>% mutate(setosa_on = ifelse(Species=="setosa", 1, 0), sl_5 = ifelse(Sepal.Length>5, ">5", "<= 5")) # 生成基础OR图 p <- iris %>% or_plot("setosa_on", "sl_5", plot_opts=xlab("OR, 95% CI"), remove_ref=TRUE) # 移除左侧类别列相关元素 p + theme( axis.text.y = element_blank(), # 隐藏y轴类别文本 axis.title.y = element_blank(), # 隐藏y轴标题 axis.ticks.y = element_blank() # 隐藏y轴刻度 )
二、更灵活的OR自动可视化函数
如果需要更高的自定义自由度,无需手动输入OR值的方案有以下几种:
1. ggplot2手动绘制(最高自由度)
先通过broom包提取回归模型的OR、置信区间,再用ggplot2构建完全可控的图形:
library(ggplot2) library(broom) # 拟合逻辑回归模型 model <- glm(setosa_on ~ sl_5, data=iris, family=binomial) # 提取OR、95%CI结果(exponentiate=TRUE转换为OR而非对数优势比) result_df <- tidy(model, exponentiate=TRUE, conf.int=TRUE) %>% filter(term != "(Intercept)") # 移除截距项 # 绘制OR森林图 ggplot(result_df, aes(x=estimate, y=term)) + geom_vline(xintercept=1, linetype="dashed", color="gray50") + # 添加OR=1的参考线 geom_pointrange(aes(xmin=conf.low, xmax=conf.high), size=1) + # 绘制点估计和置信区间 labs(x="OR, 95% CI", y="") + theme_minimal() + theme(axis.text.y = element_blank()) # 按需移除y轴类别文本
2. forestplot包
专门用于森林图绘制,支持直接从模型结果提取数据,样式简洁易调整:
library(forestplot) # 复用上述模型结果 result_df <- tidy(model, exponentiate=TRUE, conf.int=TRUE) %>% filter(term != "(Intercept)") # 绘制森林图 forestplot( labeltext = result_df$term, mean = result_df$estimate, lower = result_df$conf.low, upper = result_df$conf.high, xlab = "OR, 95% CI", zero = 1, # 设置OR=1的参考线位置 col = fpColors(box="black", lines="gray") )
3. ggforest(survival包)
若偏好简洁的默认森林图样式,可使用survival::ggforest,需将逻辑回归模型适配为coxph对象:
library(survival) # 构建适配ggforest的cox模型 cox_model <- coxph(Surv(setosa_on, rep(1, nrow(iris))) ~ sl_5, data=iris) ggforest(cox_model, data=iris)
内容的提问来源于stack exchange,提问作者BPeif
相关产品推荐
相关产品推荐

