Reputation: 311
I have a small multiple plot that looks like this:
The plot presents the results from two models: mpg predicted by cyl and disp for two transmission types. 0 is the first model, fit for automatic transmission. 1 is the second model, fit for manual transmission. The code to get the plot is this:
library(tidyverse)
library(dotwhisker)
mod_mtcars='mpg~cyl+disp'
np_mtcars=mtcars%>%
group_by(am)%>%
do(broom::tidy(lm(mod_mtcars, data= . )))%>%
rename(model=am)
small_multiple(np_mtcars)
I would like to add a horizontal line to each subplot which corresponds to the coefficients of a model fit without groups (a complete pooling model: cp=lm(mpg~cyl+disp, data=mtcars)
). I know how to add a generic horizontal line, with intercept 0, for instance. However, does anyone know how to add a different line to each subplot?
When I vectorise the coefficients of cp
(cp_coeff=coef(cp)
) and add them to the plot, I get all of them at once on every subplot. When I run the below loop, I get the last element of the vector printed on each subplot.
for (i in 1:2){
small_multiple(np_mtcars)+
geom_hline(cp_coeff[i])}
Upvotes: 0
Views: 132
Reputation: 5336
You need to add another layer as follows:
small_multiple(np_mtcars) +
geom_hline(data = broom::tidy(cp)[-1,], aes(yintercept=estimate))
Look at broom::tidy(cp)
for an explanation as to why this works (compared to np_mtcars
), and think about how it will be plotted given the facets already defined in the graph.
Upvotes: 1