如何修改交互效应图(Interaction plot)的线条颜色与主题
修改交互效应图的主题与线条颜色
需要协助修改以下交互效应图的主题与线条颜色,绘图对象p包含全部相关信息。
原代码与效果图
text = " ability edu sales 2.1696 1.8571 3717.1243 4.0558 1.8571 6030.4851 5.9420 1.8571 8343.8458 2.1696 3.8233 3796.0685 4.0558 3.8233 5795.6345 5.9420 3.8233 7795.2006 2.1696 5.7894 3875.0127 4.0558 5.7894 5560.7840 5.9420 5.7894 7246.5554 " mod_data = read.table(text = text, header = TRUE) pacman::p_load(interactions) fit = lm(sales ~ ability*edu, data = mod_data) p = interact_plot(fit, pred = "ability", modx = "edu") p

修改方案
由于interact_plot返回的是ggplot2对象,可直接用ggplot2语法调整主题和线条颜色:
修改后的完整代码
text = " ability edu sales 2.1696 1.8571 3717.1243 4.0558 1.8571 6030.4851 5.9420 1.8571 8343.8458 2.1696 3.8233 3796.0685 4.0558 3.8233 5795.6345 5.9420 3.8233 7795.2006 2.1696 5.7894 3875.0127 4.0558 5.7894 5560.7840 5.9420 5.7894 7246.5554 " mod_data = read.table(text = text, header = TRUE) pacman::p_load(interactions, ggplot2) fit = lm(sales ~ ability*edu, data = mod_data) p = interact_plot(fit, pred = "ability", modx = "edu") # 自定义线条颜色与主题 p + # 设置线条颜色,向量长度需与edu的类别数匹配 scale_color_manual(values = c("#E63946", "#457B9D", "#1D3557")) + # 替换为黑白主题,也可选用theme_minimal()、theme_classic()等 theme_bw() + # 可选:细化主题样式 theme( plot.title = element_text(size = 14, face = "bold", hjust = 0.5), axis.title = element_text(size = 12), legend.title = element_text(size = 12), legend.position = "top" )
关键说明
scale_color_manual:自定义每条线的颜色,传入颜色向量即可,颜色数量要和modx(这里是edu)的类别数量一致- 内置主题:
theme_bw()是常用的简洁主题,可根据需求替换为其他ggplot2内置主题 - 细节调整:
theme()函数可进一步修改标题、坐标轴、图例的字体大小、位置等样式
内容的提问来源于stack exchange,提问作者Ramakrishna S
相关产品推荐
相关产品推荐

