Search code examples
rggplot2ggeffects

scale_x_discrete doesn't work in ggeffects


I"d like to customise my x-axis using scale_x_discrete, but in plot, using ggeffects doesn't work. In my example:

library(ggplot2)
library(ggeffects)
library(datawizard)
data(efc, package = "ggeffects")
efc$c172code <- datawizard::to_factor(efc$c172code)
fit <- lm(barthtot ~ c12hour + neg_c_7 + c161sex + c172code, data = efc)
# categorical variables have errorbars
dat <- predict_response(fit, terms = c("c172code", "c161sex"))
plot(dat) + scale_x_discrete(labels=c("high level of education","intermediate level of education","low level of education")) 

ggeffects_1

Please, any help with it?


Solution

  • Specifying factor levels before plotting is probably the most straightforward approach. However, in case you want to fiddle around with the plot further, it may be helpful to create it from the ggeffect object "manually".

    dat |>
      as.data.frame() |>
      ggplot(aes(x = x,
                 y = predicted,
                 ymin = conf.low,
                 ymax = conf.high,
                 color = group)) +
      geom_pointrange(position = position_dodge(width = 0.2)) +
      labs(x = "carer's level of education",
           y = "Total score BARTHEL INDEX",
           color = "carer's gender") +
      scale_color_manual(values = c('red','blue')) +
      theme_bw() 
    

    Created on 2024-05-31 with reprex v2.1.0