Colored ribbons and different linetypes in sjPlot plot_model()

限于喜欢 提交于 2020-01-06 02:21:06

问题


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")

回答1:


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.



来源:https://stackoverflow.com/questions/56060618/colored-ribbons-and-different-linetypes-in-sjplot-plot-model

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!