简体   繁体   中英

Add several horizontal lines to small multiple plot

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM