简体   繁体   中英

Colored ribbons and different linetypes in sjPlot plot_model()

I want to use plot_model() from the sjPlot package to plot predicted values of a model with both different linetypes and colored ribbons . I also want the linetypes and ribbon colors to show up in the legend . I did find a way to make this work using ggpredict() and ggplot(), but I would much prefer using the plot_model() function as it saves me writing a lot of code when having to fit and plot a lot of models for my projects.

I did try two different ways shown below, but neither worked for me. How can I do this?

library("ggplot2")
library("ggeffects")
library("sjPlot")
data(efc)
fit <- lm(neg_c_7 ~ c12hour * barthtot, data = efc)

# Preferred output
ggpredict(fit, terms = c("c12hour", "barthtot")) %>%
  ggplot(aes(x, predicted)) +
  geom_ribbon(aes(
    ymin = conf.low,
    ymax = conf.high,
    fill = group
  ),
  alpha = 0.5
  ) +
  geom_line(aes(linetype = group)) +
  scale_linetype_manual(values = c("dotted", "dashed", "solid")) +
  labs(
    title = "Predicted values of Negative impact with 7 items",
    x = "average number of hours of care per week",
    y = "Negative impact with 7 items",
    fill = "Total score BARTHEL INDEX",
    linetype = "Total score BARTHEL INDEX"
  )

# First try: Changing the linetype does not seem to work
plot_model(fit,
           type = "pred",
           terms = c("c12hour", "barthtot")
) +
  scale_linetype_manual(values = c("dotted", "dotdash", "longdash"))

# Second try: With colors = "bw" I can change the linetype, and with
# scale_fill_brewer() I can add colored ribbons, but the legend does 
# not show the colors
plot_model(fit,
           type = "pred",
           terms = c("c12hour", "barthtot"),
           colors = "bw"
) +
  scale_linetype_manual(values = c("dotted", "dotdash", "longdash")) +
  scale_fill_brewer(palette = "Set1")

Maybe you can explore the functions set_theme() and update_geom_defaults() that allow you to customize the plot appearance. You only need to call it one time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM