Search code examples
rplotlegend

Plot_model() How to change legend title when color is set to black and white


In plot_model() function (sjPlot package), setting colors to black and white, colors="bw", does not allow the user to modify the character string in the title of the legend in legend.title. Is there a workaround for this without modifying the data itself?

EDIT

Example with colors="bw"

plot_model(mod4, type="int",
           colors="bw",
           mdrt.values="minmax", 
           title = "",
           axis.title = c("Variable 1", "Response"),
           legend.title="Distance (Meters)"
           ) 

enter image description here

With colors="Set1"

plot_model(mod4, type="int",
           colors="Set1",
           mdrt.values="minmax", 
           title = "",
           axis.title = c("Variable 1", "Response"),
           legend.title="Distance (Meters)"
           ) 

enter image description here


Solution

  • The 'internals' of sjPlot are based on ggplot2, so you can use ggplot2 commands to customise your plot.

    Example plot (from https://strengejacke.github.io/sjPlot/articles/plot_marginal_effects.html):

    library(sjPlot)
    library(ggplot2)
    data(efc)
    theme_set(theme_sjplot())
    
    fit <- lm(barthtot ~ c12hour + neg_c_7 + c161sex + c172code, data = efc)
    
    plot_model(fit, type = "pred", terms = c("c12hour", "c172code"))
    

    With colors = "bw":

    plot_model(fit, type = "pred", terms = c("c12hour", "c172code"), colors = "bw")
    

    Changing the legend title:

    plot_model(fit, type = "pred", terms = c("c12hour", "c172code"), colors = "bw") +
      scale_linetype_manual(name = "New Title",
                            values = c(1,2,3))
    

    Changing the color and size of the title:

    plot_model(fit, type = "pred", terms = c("c12hour", "c172code"), colors = "bw") +
      scale_linetype_manual(name = "New Title",
                            values = c(1,2,3)) +
      theme(legend.title = element_text(colour = "red"))
    

    Created on 2023-10-19 with reprex v2.0.2


    Edit

    Also, it seems that changing legend.title does work in my example:

    library(sjPlot)
    library(ggplot2)
    data(efc)
    theme_set(theme_sjplot())
    
    fit <- lm(barthtot ~ c12hour + neg_c_7 + c161sex + c172code, data = efc)
    
    plot_model(fit, type = "pred", terms = c("c12hour", "c172code"))
    

    
    plot_model(fit, type = "pred", terms = c("c12hour", "c172code"), colors = "bw")
    

    
    plot_model(fit, type = "pred", terms = c("c12hour", "c172code"),
               colors = "bw", legend.title = "new title")
    

    Created on 2023-10-19 with reprex v2.0.2

    Are you able to provide a minimal reproducible example to illustrate your problem? Are you running the most up-to-date version of R/sjPlot?