使用 plot_model() 更改线型和线条颜色

Changing linetype and line color with plot_model()

我正在尝试使用 sjPlot 中的 plot_model() 函数创建预测值图。我希望我的预测线具有不同的线型和不同的颜色。

该函数包含一个colors参数,将colors设置为bw将改变linetype,但将colors设置为灰度。这个问题很相似,但没有得到有用的答案:Colored ribbons and different linetypes in sjPlot plot_model()

示例:

不同 linetypes,但不是 colors

data(iris)
toy_model <- lm( Sepal.Length ~ Sepal.Width + Species, data=iris)

my_plot <- plot_model(toy_model, type=("pred"),
terms=c("Sepal.Width","Species"),
colors="bw")

不同 colors,但不是 linetypes

data(iris)
toy_model <- lm( Sepal.Length ~ Sepal.Width + Species, data=iris)

my_plot <- plot_model(toy_model, type=("pred"),
terms=c("Sepal.Width","Species"))

如何获得不同的 colors 和不同的 linetypes?换句话说,我想要这样的东西

sjPlot在自定义方面似乎相当死板,但有很多方法可以解决。您可以从 ggpredict(来自 ggeffects 包)获取数据并像往常一样在 ggplot.

中自定义绘图
df <- ggpredict(toy_model, terms = c("Sepal.Width","Species"))
ggplot(df, aes(x, predicted)) + 
    geom_line(aes(linetype=group, color=group)) +
    geom_ribbon(aes(ymin=conf.low, ymax=conf.high, fill=group), alpha=0.15) +
    scale_linetype_manual(values = c("solid", "dashed", "dotted"))

plot_model 确实允许 ggplot2 函数调整绘图的特征。 您可以轻松更改颜色或线型。

library(sjPlot)
library(ggplot2)

data(iris)
toy_model <- lm( Sepal.Length ~ Sepal.Width + Species, data=iris)

#Use aes to change color or linetype
plot_model(toy_model, type=("pred"),
                      terms=c("Sepal.Width","Species")) + aes(linetype=group, color=group)

#Change color
plot_model(toy_model, type=("pred"),
                      terms=c("Sepal.Width","Species"), colors = "Set2") + aes(linetype=group, color=group)

enter image description here