使用plot_model修改图例标签与轴标签字号及颜色的问题
解决plot_model交互效应图中轴标签设置被覆盖的问题
问题描述
使用plot_model绘制交互效应图时,通过scale_color_manual修改图例标签后,原本设置的轴标签字号未生效,同时需要将X轴标签从灰色改为黑色。数据结构如下:
X Groups DV SK 1 1 Group 1 5.00 1.1813822 2 2 Group 1 1.00 1.1813822 3 3 Group 1 2.00 1.1813822 4 4 Group 1 1.75 0.2678133 5 5 Group 1 3.75 0.2678133 6 6 Group 1 2.50 0.7245978 ... 360 360 Group 3 6.00 0.2678133 361 361 Group 3 1.75 -1.5593244 362 362 Group 3 3.25 -0.6457555 363 363 Group 3 5.25 -1.1025399 364 364 Group 3 3.00 -2.9296776 365 365 Group 3 2.75 0.2678133
原尝试代码:
library(sjPlot) library(ggplot2) fit1 = lm(DV~Groups*SK, data=df1) gg_colors <- c("blue", "red") p1 <- plot_model(fit1, type = "pred", terms = c("Groups", "SK[-0.6457555 ,0.7245978]"), title= "", axis.title = c("","Y TITLE"), legend.title="SK") p1 + scale_color_manual(labels = c("25 Percentile", "75th Percentile"), values=gg_colors) + font_size(axis_title.y = 12, labels.x=12) + legend_style(pos="top")
解决方案
问题出在sjPlot的font_size函数与scale_color_manual的图层优先级冲突,改用ggplot2原生的theme()函数来控制轴标签的字号和颜色,同时保留图例的自定义设置:
library(sjPlot) library(ggplot2) fit1 = lm(DV~Groups*SK, data=df1) gg_colors <- c("blue", "red") p1 <- plot_model(fit1, type = "pred", terms = c("Groups", "SK[-0.6457555 ,0.7245978]"), title= "", axis.title = c("","Y TITLE"), legend.title="SK") p1 + scale_color_manual(labels = c("25 Percentile", "75th Percentile"), values=gg_colors) + theme( # 设置Y轴标题字号 axis.title.y = element_text(size=12), # 设置X轴标签字号和黑色 axis.text.x = element_text(size=12, color="black"), # 调整图例位置到顶部 legend.position = "top" )
说明
- 使用ggplot2原生的
theme()替代sjPlot的font_size和legend_style,避免图层顺序导致的设置覆盖问题; axis.text.x的color="black"直接将X轴标签从默认灰色改为黑色;legend.position = "top"实现图例置顶的需求,和原legend_style(pos="top")效果一致。
内容的提问来源于stack exchange,提问作者user21143935
相关产品推荐
相关产品推荐

