This vignettes demonstrates how to customize plots created with the plot()
-method of the ggeffects-package.
plot()
returns an object of class ggplot, so it is easy to apply further modifications to the resulting plot. You may want to load the ggplot2-package to do this: library(ggplot2)
.
Let’s start with a default-plot:
library(ggeffects)
library(ggplot2)
data(mtcars)
m <- lm(mpg ~ gear + as.factor(cyl) + wt, data = mtcars)
# continuous x-axis
dat <- ggpredict(m, terms = c("gear", "wt"))
# discrete x-axis
dat_categorical <- ggpredict(m, terms = c("cyl", "wt"))
# default plot
plot(dat)
The simplest thing is to change the titles from the plot, x- and y-axis. This can be done with ggplot2::labs()
:
plot(dat) +
labs(
x = "Number of forward gears",
y = "Miles/(US) gallon",
title = "Predicted mean miles per gallon"
)
The legend-title can also be changed using the labs()
-function. The legend in ggplot-objects refers to the aesthetic used for the grouping variable, which is by default the colour
, i.e. the plot is constructed in the following way:
Hence, using colour
in labs()
changes the legend-title:
For black-and-white plots, the group-aesthetic is mapped to different linetypes, not to different colours. Thus, the legend-title for black-and-white plots can be changed using linetype
in labs()
:
If the variable on the x-axis is discrete for a black-and-white plot, the group-aesthetic is mapped to different shapes, so following code must be used to change the legend title:
The x-axis for plots returned from plot()
is always continuous, even for discrete x-axis-variables. The reason for this is that many users are used to plots that connect the data points with lines, which is only possible for continuous x-axes. You can do this using the connect.lines
-argument:
Since the x-axis is continuous (i.e. ggplot2::scale_x_continuous()
), you can use scale_x_continuous()
to modify the x-axis, and change breaks, limits or labels.
Arguments in ...
are passed down to ggplot::scale_y_continuous()
(resp. ggplot::scale_y_log10()
, if log.y = TRUE
), so you can control the appearance of the y-axis by putting the arguments directly into the call to plot()
:
The legend labels can also be changed using a scale_*()
-function from ggplot. Depending on the color-setting (see section Changing the Legend Title), following functions can be used to change the legend labels:
scale_colour_manual()
resp. scale_colour_brewer()
scale_linetype_manual()
scale_shape_manual()
Since you overwrite an exising “color” scale, you typically need to provide the values
or palette
-argument, to manuall set the colors, linetypes or shapes.
For plots using default colors: