I used the mtcars
public data as it did not have the use by the asker.
data(mtcars)
Create the boxplot, as usual, and assign to object. I took a random variable as a factor for the boxplot and another variable as numeric.
g <- ggplot(mtcars, aes(factor(carb), mpg)) + geom_boxplot()
Add the geom_smooth. The geom_smooth inherits the necessary information from the geom_boxplot.
g + geom_smooth(method = "lm", se=TRUE, aes(group=1))
Noted that the expression aes(group=1)
it's required by the geom_smooth in this case. Without it, R returns the error:
geom_smooth: Only one unique x value each group.Maybe you want aes(group = 1)?
The values for fixing the line smoothing are the coefficients of the linear regression, whereas the intercept corresponds to the lowest level of the factor (carb = 1)