首页 > 解决方案 > 管道 df 到 geom_hline 参数

问题描述

试图理解为什么以下工作

stackover_df %>%
  ggplot(., aes(x=sample_name, y=estimate, group=sample_name, color=sample_name))+ 
  geom_point() +
  geom_hline(aes(yintercept = stackover_df %>% filter(sample_name == "control1") %>% pull(upper_limit_value)))

但如果我只是将 stackover_df 更改为 . 对于 geom_hline 部分

stackover_df %>%
  ggplot(., aes(x=sample_name, y=estimate, group=sample_name, color=sample_name))+ 
  geom_point() +
  geom_hline(aes(yintercept = . %>% filter(sample_name == "control1") %>% pull(upper_limit_value)))

我收到以下错误消息

错误:美学必须是有效的数据列。有问题的美学:yintercept = . %>% 过滤器(sample_name == "control1") %>% pull(upper_limit_value)。您是否输入错误数据列的名称或忘记添加 after_stat()?

谢谢!

这是示例数据

stackover_df <- structure(list(sample_name = c("control1", "control2", "S01", 
"S02", "S03", "S04", "S05", "S06", "S07", "S08"), estimate = c(1.703, 
5.553, 4.851, 5.257, 4.573, 3.278, 1.687, 3.628, 1.877, 5.826
), std.error = c(1.767, 2.382, 1.641, 1.062, 1.133, 1.477, 0.978, 
0.611, 1.893, 0.78), upper_limit_value = c(5.166, 10.223, 8.067, 
7.339, 6.795, 6.173, 3.605, 4.825, 5.586, 7.355), lower_limit_value = c(-1.761, 
0.884, 1.635, 3.175, 2.352, 0.384, -0.231, 2.431, -1.833, 4.298
)), row.names = c(NA, -10L), class = c("tbl_df", "tbl", "data.frame"
))

标签: rggplot2tidyverse

解决方案


我认为这里涉及两件事。

  1. 尝试引用yintercept内部,aes()因此它正在寻找列名data以提供到值的每行映射。这不是你想要的,所以第一件事是删除aes()并直接引用它

  2. 由于ggplot()实际上是一系列函数调用,因此您需要使用表达式(由 定义{ ... })来对它们进行分组并保持.所有层都可以访问传入的内容。

所以一切看起来像这样:

stackover_df %>% 
  { # make it an expression
    ggplot(., aes(x=sample_name, y=estimate, group=sample_name, color=sample_name)) + 
      geom_point() +
      geom_hline(yintercept = filter(., sample_name == "control1") %>% pull(upper_limit_value))
    }

推荐阅读