r - 如何在 ggplot 之后使用 %T>% 管道?

标签 r ggplot2 pipeline

我们来看下面两段代码:

mtcars %>%
    ggplot(aes(x = cyl, y = mpg))+
    geom_line()

这有效并创建了以下情节:

enter image description here

现在让我们看看这个:

mtcars %>%
    group_by(cyl) %>% 
    summarise(mpg = mean(mpg))

这也有效并创建以下输出:

# A tibble: 3 x 2
    cyl   mpg
  <dbl> <dbl>
1     4  26.7
2     6  19.7
3     8  15.1

但是,这不起作用:

mtcars %T>%
    ggplot(aes(x = cyl, y = mpg))+
    geom_line() %>%
    group_by(cyl) %>% 
    summarise(mpg = mean(mpg))

它给出了以下错误:

Error in UseMethod("group_by") : 
  no applicable method for 'group_by' applied to an object of class "c('LayerInstance', 'Layer', 'ggproto', 'gg')"

为什么不起作用?从 %T>% 文档中,我希望左侧对象(在本例中为 mtcars)会在 ggplot 之后返回>。不幸的是,这似乎不起作用。我是否误解了 %T>% 管道?使这项工作正常运行的代码应该是什么样子?

最佳答案

您需要将 ggplot 调用包装在 print 中,以便同时调用。您可以使用以下代码:

library(tidyverse)
#> Warning: package 'ggplot2' was built under R version 4.1.2
#> Warning: package 'tibble' was built under R version 4.1.2
#> Warning: package 'tidyr' was built under R version 4.1.2
#> Warning: package 'readr' was built under R version 4.1.2
#> Warning: package 'dplyr' was built under R version 4.1.2
library(magrittr)
#> Warning: package 'magrittr' was built under R version 4.1.2
#> 
#> Attaching package: 'magrittr'
#> The following object is masked from 'package:purrr':
#> 
#>     set_names
#> The following object is masked from 'package:tidyr':
#> 
#>     extract
mtcars %T>%
  {print(ggplot(., aes(x = cyl, y = mpg))+
  geom_line())} %>%
  group_by(cyl) %>% 
  summarise(mpg = mean(mpg))

#> # A tibble: 3 × 2
#>     cyl   mpg
#>   <dbl> <dbl>
#> 1     4  26.7
#> 2     6  19.7
#> 3     8  15.1

reprex package 创建于 2022-06-30 (v2.0.1)

关于r - 如何在 ggplot 之后使用 %T>% 管道?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72812356/

相关文章:

R SVM 预测

R:混合模型 - 如何使用同一变量的先前值来预测变量

python - 如何为opencv安装gstreamer 1.0 badplugin?

assembly - 预测现代超标量处理器上的操作的延迟需要考虑哪些因素,我如何手动计算它们?

r - 如何在 Rstudio 中使用 z shell 而不是 bash 为 linux 使用 windows 子系统?

ruby - 如何使用 R 搜索 pubmed,就像使用 Ruby 一样?

r - 使用 geom_smooth 维护 x 轴的日期类

r - 帮助 R 和 grouping/aggregate/*apply/data.table

r - 直方图中不同的 bin 宽度与 ggplot2,r

python - 如何在 scrapy python 中使用蜘蛛名称动态创建 csv 文件