R语言plot_model绘制模型图时的图例外观自定义问询
解决plot_model图例自定义问题
问题背景
使用plot_model绘制经AIC模型选择得到的二项式广义线性混合效应模型预测图时,图例自定义遇到困难,需要完成以下4项调整:
- 将“Males”“Females”旁的线型图标改为对应颜色的填充方块
- 图例项堆叠显示(Males在上,Females在下)
- 手动移动图例至图内更靠下的位置
- 修改图例字体为Times New Roman(衬线体)并调大字号
原始代码
# generate break positions breaks = c(seq(-30, 0, by=10), -2) # and labels labels = as.character(breaks) plot1 <- plot_model(m2, type = "pred" , terms = c("Day [all]", "Sex"), colors = c("blue", "red"), ci.lvl = .95, legend.title = "", line.size = 1) + labs(x = "Days Relative to Clutch Initiation", y = "P(Attend at night)", title = NULL) + scale_x_continuous(expand = c(0, 0), breaks = breaks, labels = labels) + scale_y_continuous(limit = c(0, 1), expand = c(0, 0)) + theme_classic() + theme(axis.text=element_text(size=16), axis.title=element_text(size=14), axis.title.x = element_text(vjust=-0.5), axis.title.y = element_text(vjust=2.5), axis.ticks.length=unit(0.1,"inch"), legend.key.size = unit(1, 'cm'), legend.position = "top", legend.justification = "left", plot.margin = margin(1,.5,1,1, "cm")) plot1
修改后的代码
# generate break positions breaks = c(seq(-30, 0, by=10), -2) # and labels labels = as.character(breaks) plot1 <- plot_model(m2, type = "pred" , terms = c("Day [all]", "Sex"), colors = c("blue", "red"), ci.lvl = .95, legend.title = "", line.size = 1) + labs(x = "Days Relative to Clutch Initiation", y = "P(Attend at night)", title = NULL) + scale_x_continuous(expand = c(0, 0), breaks = breaks, labels = labels) + scale_y_continuous(limit = c(0, 1), expand = c(0, 0)) + # 调整图例符号为填充方块 guides(color = guide_legend(override.aes = list(linetype = 0, shape = 15))) + theme_classic() + theme(axis.text=element_text(size=16), axis.title=element_text(size=14), axis.title.x = element_text(vjust=-0.5), axis.title.y = element_text(vjust=2.5), axis.ticks.length=unit(0.1,"inch"), legend.key.size = unit(1, 'cm'), # 手动设置图例坐标(x,y范围0-1,对应图的左下角到右上角) legend.position = c(0.1, 0.2), legend.justification = "left", # 堆叠图例项 legend.direction = "vertical", # 修改图例字体为Times New Roman并调大字号 legend.text = element_text(family = "Times New Roman", size = 16), plot.margin = margin(1,.5,1,1, "cm")) plot1
各需求对应实现说明
将线型图标改为填充方块:
使用guides(color = guide_legend(override.aes = list(linetype = 0, shape = 15))),通过override.aes覆盖默认的线型符号,shape=15是实心方块,linetype=0隐藏原有线条。图例项堆叠显示:
在theme中添加legend.direction = "vertical",设置图例方向为垂直,实现上下堆叠。手动移动图例位置:
将legend.position从"top"改为坐标c(0.1, 0.2),x=0.1对应图左侧10%位置,y=0.2对应图底部20%位置,可根据实际需求调整数值。修改图例字体及字号:
在theme中添加legend.text = element_text(family = "Times New Roman", size = 16),指定字体为Times New Roman,同时设置字号为16(可按需调整)。
内容的提问来源于stack exchange,提问作者NeedHelpWithR
相关产品推荐
相关产品推荐

