Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add geom_smooth to boxplot [duplicate]

Tags:

r

ggplot2

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))

enter image description here

geom_smooth

ggplot(test, aes(year, dm)) + geom_smooth() 

enter image description here

Both geom_boxplot and geom_smooth

ggplot(test) + geom_boxplot(aes(x=factor(year), y = dm)) + geom_smooth(aes(x = year, y = dm))

enter image description here

like image 693
Vedda Avatar asked Jan 05 '16 09:01

Vedda


1 Answers

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)

enter image description here

like image 55
PereG Avatar answered Oct 27 '22 22:10

PereG