James Martherus
James Martherus

Reputation: 1043

Changing linetype and line color with plot_model()

I am trying to create a plot of predicted values using the plot_model() function from sjPlot. I want my prediction lines to have different linetypes and different colors.

The function includes a colors argument, and setting colors to bw will change linetype, but set colors to greyscale. This question is similar, but received no helpful answers: Colored ribbons and different linetypes in sjPlot plot_model()

Examples:

Different linetypes, but not 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")

Different colors, but not 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"))

How can I get both different colors and different linetypes? In other words, I want something like this

this

Upvotes: 8

Views: 11740

Answers (2)

Dominix
Dominix

Reputation: 441

plot_model does allow ggplot2 functions to adjust features of the plot. You can easily change colors or linetypes.

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

Upvotes: 4

Arienrhod
Arienrhod

Reputation: 2581

sjPlot seems to be rather rigid when it comes to customisation, but there are ways around it. You can get the data from ggpredict (from ggeffects package) and customise the plot as usual in 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"))

example

Upvotes: 9

Related Questions