我如何使用原生管道和占位符内的ggploy geom?

当传递一个data.Frame来进行ggmap时,本机管道工作得很好,但是在geom中,当我想要过滤原始的data.Frame时,我需要使用‘magrittr’管道.

因此,这项功能运行良好:

mtcars |> 
     ggplot() +
     geom_col(data = . %>% filter(cyl == 4),
              aes(x = gear, y = mpg),
              fill = "grey80") +
     geom_text(data = . %>% filter(cyl == 4 & gear == 3),
               aes(x = gear,
                   y = mpg,
                   label = "ooo"), color = "tomato3") +
     theme_minimal()

使用匿名函数,我可以完全切换到本地管道:

mtcars |> 
     ggplot() +
     geom_col(data = (\(x) filter(x, cyl == 4)),
              aes(x = gear, y = mpg),
              fill = "grey80") +
     geom_text(data = (\(x) filter(x, cyl == 4 & gear == 3)),
               aes(x = gear,
                   y = mpg,
                   label = "ooo"), color = "tomato3") +
     theme_minimal()

但是,有没有一种很好的方法来使用R的本地管道操作符和占位符来执行相同的操作呢?

这将引发错误"Invalid Use of PIPE PLACEHOLDER":

mtcars |> 
     ggplot() +
     geom_col(data = _ |>  filter(cyl == 4),
              aes(x = gear, y = mpg),
              fill = "grey80") +
     geom_text(data = _ |>  filter(cyl == 4 & gear == 3),
               aes(x = gear,
                   y = mpg,
                   label = "ooo"), color = "tomato3") +
     theme_minimal()

推荐答案

可以继续使用本机管道,但利用ggplot2仍然有效,尽管可能会弃用公式语法而支持新的匿名函数语法.

mtcars |> 
  ggplot() +
  geom_col(data = ~filter(., cyl == 4),
           aes(x = gear, y = mpg),
           fill = "grey80") +
  geom_text(data =  ~filter(., cyl == 4 & gear == 3),
            aes(x = gear,
                y = mpg,
                label = "ooo"), color = "tomato3") +
  theme_minimal()

这就是说,我个人非常相信不要在我的绘图/图表代码中进行数据操作. 我更愿意提前完成所有的数据更改,然后编写一个纯粹的绘图函数.

d1 <- filter(mtcars, cyl == 4)
d2 <- filter(mtcars, cyl == 4 & gear == 3)

  ggplot() +
  geom_col(data =  d1,
           aes(x = gear, y = mpg),
           fill = "grey80") +
  geom_text(data =  d2,
            aes(x = gear,
                y = mpg,
                label = "ooo"), color = "tomato3") +
  theme_minimal()

R相关问答推荐

如何将y轴设置为在ggplot 2中x=0处与x轴相交?

如何生成包含可能条目列表而不是计数的表?

如何将log 2刻度上的数字转换为自然log

如果列中存在相同的字符串,则对行值进行总和

在(g)子中使用asserable字符

如何从当前行上方找到符合特定条件的最接近值?

将嵌套列表子集化为嵌套列表

根据文本字符串中的值粘贴新列

R—将各种CSV数字列转换为日期

如何从R ggplot图片中获取SVG字符串?

为了网络分析目的,将数据框转换为长格式列联表

使用data.table::fcase()而不是dplyr::case_When()时保持值

如何删除最后一个可操作对象

从非重叠(非滚动)周期中的最新数据向后开窗并在周期内计数

R中的类别比较

如何在R中使用混合GAM模型只对固定的影响因素进行适当的预测?

计算Mean by分组和绑定到R中的数据集

在r中整理图例和堆叠图的问题

如何在R中创建条形图,使条形图在y轴上围绕0.5而不是0构建条形图?

如何用不同长度的向量填充列表?