GLMM预测结果可视化:带误差棒的柱状图绘制优化需求
基于GLMM预测结果绘制带误差棒的优化柱状图
1. 提取预测数据
先用ggpredict从GLMM模型中提取包含置信区间的预测结果,转为数据框便于后续绘图:
library(ggpredict) # 替换model_glmm为你的模型对象,terms参数指定要可视化的自变量 pred_data <- ggpredict(model_glmm, terms = c("你的自变量")) pred_df <- as.data.frame(pred_data)
2. ggplot绘制带误差棒的柱状图
用ggplot2构建符合需求的专业级柱状图,样式贴近参考图:
library(ggplot2) ggplot(pred_df, aes(x = x, y = predicted)) + # 设置柱状图填充色和宽度 geom_col(fill = "#4287f5", width = 0.65) + # 添加误差棒,设置宽度、颜色和粗细 geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = 0.2, color = "#2c3e50", size = 0.7) + # 自定义轴标签 labs(x = "自变量名称", y = "预测响应值") + # 使用简洁主题,去除多余元素 theme_classic() + # 调整文字样式 theme( axis.title.x = element_text(size = 12, face = "bold"), axis.title.y = element_text(size = 12, face = "bold"), axis.text = element_text(size = 10), plot.title = element_blank() )
3. 优化基础plot()图形方案
如果只能使用基础plot()函数,可通过以下代码优化图形样式:
# 提取关键数据 pred_vals <- pred_data$predicted conf_low <- pred_data$conf.low conf_high <- pred_data$conf.high x_pos <- 1:length(pred_vals) x_labels <- pred_data$x # 绘制柱状图 barplot(pred_vals, col = "#4287f5", ylim = c(min(conf_low)*0.9, max(conf_high)*1.1), # 预留误差棒空间 xlab = "", ylab = "", border = NA, cex.axis = 1) # 添加误差棒 arrows(x0 = x_pos, y0 = conf_low, x1 = x_pos, y1 = conf_high, angle = 90, code = 3, length = 0.05, col = "#2c3e50") # 添加轴标签和样式 title(xlab = "自变量名称", ylab = "预测响应值", cex.lab = 1.2, font.lab = 2) axis(1, at = x_pos, labels = x_labels, cex.axis = 1)
内容的提问来源于stack exchange,提问作者Katie OToole
相关产品推荐
相关产品推荐

