Search code examples
rggplot2sjplot

How to reverse the legend order in a plot created with sjPlot


I use the data of mtcars to build a lmer model as below. The problem is that when I use sjplot::plot_model to plot marginal effect plot, I found the order of legend is reversed. The expected order is that the low value is at the bottom and the large value is at the top. Could you help me resolve it? Thanking everyone who pays attention to this issue.

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

sjplot::plot_model(mdl,type = 'pred',terms = c("mpg [all]","wt"))

enter image description here


Solution

  • As you are basically dealing with a ggplot you could reverse the order of the legend via guide_legend:

    library(lme4)
    #> Loading required package: Matrix
    library(ggplot2)
    
    mdl <- lmer(disp~mpg:wt+vs+(1|cyl) , data = mtcars)
    
    sjPlot::plot_model(mdl,type = 'pred',terms = c("mpg [all]","wt")) +
      guides(color = guide_legend(reverse = TRUE))