I'm trying to add a geom_smooth()
trend to some a boxplot graph, but am not getting the layers correctly.
How can I merge these two together?
geom_boxplot:
ggplot(test) + geom_boxplot(aes(x=factor(year), y = dm))
geom_smooth
ggplot(test, aes(year, dm)) + geom_smooth()
Both geom_boxplot and geom_smooth
ggplot(test) + geom_boxplot(aes(x=factor(year), y = dm)) + geom_smooth(aes(x = year, y = dm))
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With