【问题标题】:piping df into geom_hline parameters管道 df 到 geom_hline 参数
【发布时间】:2021-02-15 05:40:01
【问题描述】:

试图理解为什么以下工作

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"
))

【问题讨论】:

    标签: r ggplot2 tidyverse


    【解决方案1】:

    我认为这里涉及两件事。

    1. 试图引用aes() 内部的yintercept,因此它在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))
        }
    

    【讨论】:

    • 有趣的方法。谢谢!那么在这种情况下,我如何能够合并 aes 组件,例如,更改线型和颜色?
    • 这样你就可以在没有aes()的情况下更改所有这些东西,只需“裸”使用它,geom_line(linetype = 3),它就会调整该层的属性
    猜你喜欢
    • 1970-01-01
    • 2018-11-05
    • 1970-01-01
    • 1970-01-01
    • 2012-04-11
    • 2019-12-19
    • 1970-01-01
    • 2021-12-22
    • 2020-02-22
    相关资源
    最近更新 更多