简体   繁体   English

将多条水平线添加到小的多图

[英]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.该图显示了两个模型的结果:由 cyl 和 disp 预测的两种传输类型的 mpg。 0 is the first model, fit for automatic transmission. 0为第一款,适用于自动变速箱。 1 is the second model, fit for manual transmission. 1为第二种型号,适合手动档。 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) ).我想在每个子图中添加一条水平线,它对应于没有组的模型拟合的系数(完整的池模型: cp=lm(mpg~cyl+disp, data=mtcars) )。 I know how to add a generic horizontal line, with intercept 0, for instance.例如,我知道如何添加一条通用水平线,截距为 0。 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.当我对cp ( cp_coeff=coef(cp) ) 的系数进行矢量化并将它们添加到图中时,我会在每个子图上同时获取所有这些cp_coeff=coef(cp) 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.查看broom::tidy(cp)以解释为什么它起作用(与np_mtcars相比),并考虑在图中已经定义的方面如何绘制它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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