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

如何修正sjPlot生成的lmer模型边际效应图的图例顺序(实现低值在下、高值在上)

Hey there! I’ve dealt with this exact legend ordering quirk in sjPlot before, so let’s get your marginal effects plot looking exactly how you want it.

The core issue here is that plot_model() defaults to reversing the legend order for continuous grouping variables like wt, which puts higher values at the bottom. To fix this, we can leverage the fact that sjPlot outputs a ggplot2 object—so we can tweak the legend directly using ggplot2 functions.

Solution 1: Reverse the Legend Directly (Simplest)

Just add guides() or scale adjustments to your plot object to flip the legend order:

library(sjPlot)
library(lme4)
library(ggplot2)

# Your original model
mdl <- lmer(disp~mpg:wt+vs+(1|cyl) , data = mtcars)

# Generate the plot and adjust the legend
p <- plot_model(mdl, type = 'pred', terms = c("mpg [all]","wt"))
p +
  # Reverse color legend (for line colors)
  guides(color = guide_legend(reverse = TRUE)) +
  # Reverse fill legend if your plot uses filled elements
  guides(fill = guide_legend(reverse = TRUE))

This will immediately flip the legend so lower wt values appear at the bottom and higher values at the top, matching your desired order.

Solution 2: Manually Control Legend Levels (For Fine-Tuning)

If you want even more control over exactly which values appear in what order, you can reorder the grouping factor in the plot's underlying data:

p <- plot_model(mdl, type = 'pred', terms = c("mpg [all]","wt"))

# Extract current wt values from the plot data, sort them numerically
sorted_wt <- sort(as.numeric(levels(p$data$group)))

# Reassign the group factor with sorted levels
p$data$group <- factor(p$data$group, levels = as.character(sorted_wt))

# Plot with the new order (no need to reverse here)
p

This method ensures the legend follows the exact numerical order of wt values, which is helpful if you want to exclude specific values or customise the sequence further.

Why does this happen? sjPlot’s default behavior for continuous grouping variables is to reverse the legend so the top line in the plot matches the top legend item—but this doesn’t always align with the "low-to-high bottom-to-top" preference many users have. The fixes above override that default easily.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 05:32:42