当观察结果低于某个数字时,在ggplot中标记

时间:2018-03-13 12:20:08

标签: r ggplot2

我有一个数据集

example <- data.frame(
  Country = rep(c("A", "B"), each = 12),
  IP = c(55,56,59,63,67,69,69,73,74,74,79,87,0,22,24,26,26,31,37,41,43,46,46,47),
  Mean_st = c(46,47,49,50,53,55,53,57,60,57,58,63,0,19,20,21,22,25,26,28,29,30,31,31)
)

ggplot(example) + 
  geom_line(aes(x = IP, y = Mean_st, color = Country), size = 2) +
  geom_vline(xintercept = 73) +
  geom_vline(xintercept = 42)

我需要标记观察数量低于某个数字的位置(假设小于5)。我可以在我的电子表格中为每个国家/地区(73和42)找到这一点,并在示例中使用geom_vline,但有没有办法直接在ggplot中找到该点而无需检查电子表格?

1 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

n_below <- 5
ggplot(example) + 
  geom_line(aes(x = IP, y = Mean_st, color = Country), size = 2) + 
  geom_vline(xintercept = sort(example$IP[example$Country == "A"][n_below])) + 
  geom_vline(xintercept = sort(example$IP[example$Country == "B"][n_below]))