You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何去除R中plot_model(ggplot)绘制图形的图例键外方框

使用sjPlot的plot_model绘制交互图时去除图例键方框的问题

我正在用R语言的sjPlot包中plot_model()函数创建线性模型的交互可视化,遇到了图例定制的问题:绘制出的图例键被方框包围,我希望移除这些方框。查阅文档、尝试多种方法并搜索相关问题后,仍未解决。

已尝试的无效方法

  • 使用theme(legend.key = element_blank())和theme(legend.background = element_rect(color = NA)),要么完全移除图例键,要么仍保留灰色背景和黑色边框
  • 使用guides(color = guide_legend(override.aes = list(fill = NULL, color = NULL)))等控制图例美学的代码,同样无效

当前图形效果

带方框的图例

测试脚本

rm(list=ls())

library(nlme)
library(lme4)
library(ggplot2)
library(sjPlot)
library(ggthemes) # ggplot主题库

# 加载数据集
data <- sleepstudy # 示例1
data(efc) # 示例2

# 示例1
group_colors <- c(old = "#3b71cd", young = "#c0393d")
threshold_subject_number <- 9
data$Subject <- as.numeric(data$Subject)
data$Group <- ifelse(data$Subject <= threshold_subject_number, "young", "old")

analysis_model = lme(Reaction ~ Days * Group,
                     data=data,
                     random=~1+Days|Subject, 
                     control = lmeControl(opt = "optim"), 
                     method = "REML")

line_plot = 
  
  plot_model(analysis_model, # 要绘制的模型
             type = "int", # 图类型:交互图
             title = "Title", # 添加标题
             colors = group_colors, # 定义颜色
             axis.title = c("Day", "Predicted Value")) +
  theme_hc() +
  theme(plot.title = element_text(hjust = 0.5)) + # 标题居中
  theme(legend.position = "right") + # 图例移至右侧
  guides(color = guide_legend(override.aes = list(fill = NA, # 使方框透明
                                                  size = 2), # 修改方框大小
                              reverse = TRUE)) # 反转图例顺序

# 示例2
m = glm(tot_sc_e ~ c161sex + c172code * neg_c_7,
        data = efc,
        family = poisson())

mp = plot_model(m, type = "int") +
     theme_hc() + # 更换主题
     theme(plot.title = element_text(hjust = 0.5)) + # 标题居中
     theme(legend.position = "right") + # 图例移至右侧
     guides(color = guide_legend(override.aes = list(fill = NA, # 使方框透明
                                                     size = 2), # 修改方框大小
                                 reverse = TRUE)) # 反转图例顺序

## 我尝试过的各种方法:

# 参考方法1
mp +
  theme(legend.key = element_blank()) # 无效——无任何变化

# 参考方法2
mp +
  theme(legend.background = element_rect(color = NA)) # 无效——无任何变化

mp +
  theme(legend.key = element_rect(colour = NA, fill = NA)) # 无效——无任何变化

mp + 
  guides(color = guide_legend(override.aes = list(fill = NA, color = NA))) # 无效——同时移除了图例键

mp + 
  guides(color = guide_legend(override.aes = list(fill = NULL, color = NULL))) # 无效——移除了线条,但所有图例键变成黑色且恢复灰色背景

mp + 
  guides(color = guide_legend(override.aes = list(fill = NULL, line = 0))) # 无效——移除了线条,但所有图例键变成黑色且恢复灰色背景

内容的提问来源于stack exchange,提问作者Zaida

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 14:05:19