Reputation: 11
I am trying to create a plot that shows a regression interaction between variables. Note that both variables are continuous. I am trying to modify the plot so that it shows the each line with a different color and a different linetype (solid, dotted, etc). I am not able to change both the color and the linetype. I have so far only been able to change the linetype and color in the plot, but not in the legend. Additionally, when I add the linetype the correct labels in the legend disappear. Any help would be appreciated.
fit <- lm(Comp ~ D_Merit * Class, data = df)
set_theme(base = theme_classic(), axis.title.color = "black", axis.textcolor.x = "black",
axis.textcolor.y = "black")
p1 <- plot_model(fit, type = "int", mdrt.values = "meansd", terms = c("D_Merit", "Class"), axis.title = c("Descriptive Meritocracy", "Perceived Competitiveness"), axis.lim = list(c(-2,2),c(-2,2)), title = "", colors="bw")
p1 +
scale_color_discrete(labels = c("-1 SD", "mean", "+1 SD"))
If I do not put colors = "bw" I just get different colors, but no different linetypes (and the legend has the correct labels of -1SD, mean, and +1 SD). When I put colors = "bw", I am able to get dotted lines in the legend and the graph, however the legend shows up in black and white (without colors) while the graph has colors and linetypes. Additionally, the labels for the legend are not correct.
I saw another post about changing the linetype and color, but it does not seem to work with an "int" plot model.
Upvotes: 0
Views: 483
Reputation: 125228
One possible option would be to add the mapping on linetype
manually via aes()
. Afterwards you could set the labels
and the name
via scale_linetype_discrete
so that the linetype
legend gets merged with the color
legend. Finally, I added a hacky p1$layers[[2]]$show.legend <- FALSE
to prevent that the geom_ribbon
used under the hood will add a colored and "dotted" outline around the legend key.
Using some fake random example data:
library(sjPlot)
library(ggplot2)
set.seed(123)
set_theme(
base = theme_classic(), axis.title.color = "black", axis.textcolor.x = "black",
axis.textcolor.y = "black"
)
df <- data.frame(
Comp = rnorm(100),
D_Merit = rnorm(100),
Class = rnorm(100)
)
fit <- lm(Comp ~ D_Merit * Class, data = df)
p1 <- plot_model(fit,
type = "int", mdrt.values = "meansd", terms = c("D_Merit", "Class"),
axis.title = c("Descriptive Meritocracy", "Perceived Competitiveness"),
axis.lim = list(c(-2, 2), c(-2, 2)), title = ""
)
#> Scale for y is already present.
#> Adding another scale for y, which will replace the existing scale.
p1$layers[[2]]$show.legend <- FALSE
p1 +
aes(linetype = group_col) +
scale_color_discrete(labels = c("-1 SD", "mean", "+1 SD")) +
scale_linetype_discrete(labels = c("-1 SD", "mean", "+1 SD"), name = "Class")
#> Scale for colour is already present.
#> Adding another scale for colour, which will replace the existing scale.
#> Warning: Removed 12 rows containing missing values (`geom_line()`).
Upvotes: 1