0

我正在尝试根据过滤的数据和从一列中选择的值来分配 geom_hline,但是这一切都是在同一个代码块中完成的。我不确定最好的方法是什么 - 任何帮助将不胜感激。

样本数据:

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"
))
df%>%
  ggplot(., aes(x=sample_name, y=estimate, group=sample_name, color=sample_name))+ 
  geom_point() +
  geom_hline(???)

在 geom_hline() 部分中,有没有办法根据过滤的数据定义 y 截距应该是什么 - 几乎就像一个侧面分配?

类似的东西

geom_hline(aes(yintercept = df %>% filter(sample_name="control1") %>% select("upper_limit_value"))) +
geom_hline(aes(yintercept = df %>% filter(sample_name="control1") %>% select("lower_limit_value")))

在这种情况下,sample_name="control1" 只有一行过滤数据,我尝试使用“upper_limit_value”列下的值(和“lower_limit_value”值作为单独的 geom_hline)。

谢谢!

4

1 回答 1

1

尝试对参数中的数据进行子data

geom_hline(data = df %>% filter(sample_name == "control") %>% select(upper_limit_value),
           mapping = aes(yintercept = upper_limit_value))

完整的代码将变为以下。

df %>%
  ggplot(aes(x=sample_name, y=estimate, group=sample_name, color=sample_name))+ 
  geom_point() +
  geom_hline(data = df %>% filter(sample_name == "control") %>% select(upper_limit_value),
             mapping = aes(yintercept = upper_limit_value))

(我不认为有必要,select(upper_limit_value)但没有测试数据很难说。)

另一种选择是pull在问题的代码中使用,而不是select. 不同之处在于select返回包含这些列的数据集并pull返回列值。

geom_hline(aes(yintercept = df %>% filter(sample_name == "control") %>% pull(upper_limit_value)))

编辑

我上面提到的数据转换是

df$sample_name[df$sample_name == "control2"] <- "control"

然后filteringeom_hline返回一个包含 1 行的数据集。

此评论之后,我已经使用发布的数据测试了代码(但在更改"control2"为之后"control")并且一切都按预期工作。

我还建议不需要dfinto的初始管道,因为不会对数据集应用任何转换。ggplot

ggplot(df, aes(x=sample_name, y=estimate, group=sample_name, color=sample_name))+ 
  geom_point() +
  geom_hline(aes(yintercept = df %>% filter(sample_name == "control") %>% pull(upper_limit_value)))
于 2020-11-01T18:02:00.483 回答