GGPLOT之后如何使用%t>%管道?
让我们看一下以下两种代码:
mtcars %>%
ggplot(aes(x = cyl, y = mpg))+
geom_line()
这可以工作并创建以下图:
现在让我们请看一下:
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&gt;%
文档中,我希望在ggplot mtcars
将返回>。不幸的是,这似乎不起作用。我是否误解了%t&gt;%
管道?代码应该如何使这项工作看起来如何?
Let's take a look at the following two pieces of code:
mtcars %>%
ggplot(aes(x = cyl, y = mpg))+
geom_line()
This works and creates the following plot:
Now let's look at this:
mtcars %>%
group_by(cyl) %>%
summarise(mpg = mean(mpg))
This also works and creates the following output:
# A tibble: 3 x 2
cyl mpg
<dbl> <dbl>
1 4 26.7
2 6 19.7
3 8 15.1
However, this doesn't work:
mtcars %T>%
ggplot(aes(x = cyl, y = mpg))+
geom_line() %>%
group_by(cyl) %>%
summarise(mpg = mean(mpg))
It gives the following error:
Error in UseMethod("group_by") :
no applicable method for 'group_by' applied to an object of class "c('LayerInstance', 'Layer', 'ggproto', 'gg')"
Why doesn't it work? From the %T>%
documentation, I would expect that the left-hand side object, in this case, mtcars
, would be returned after ggplot
. Unfortunately that doesn't seem to work. Did I misunderstand the %T>%
pipe? How is the code supposed to look like to make this work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要将
ggplot
打电话给print
,以便您接到两个呼叫。您可以使用以下代码:在2022-06-30创建的 reprex软件包 (v2.0.1)
You need to wrap the
ggplot
call in aprint
so you get both calls. You can use the following code:Created on 2022-06-30 by the reprex package (v2.0.1)