在R的ggplot中为水平直线添加标签

时间:2019-06-02 07:52:03

标签: r ggplot2

我在ggplot中添加了两条直线(除了其他直线)分别用于min_safety_stock和max_safety_stock。现在,我要显示这两行的标签,并带有其相应的min_safety_stock days和max_safety_stock_days值。我该怎么办?

1 个答案:

答案 0 :(得分:1)

您可以手动使用annotate添加注释:

ggplot(mtcars, aes(wt, mpg)) + 
  geom_point() +
  geom_hline(yintercept = 27) +
  annotate("text", x = 2.5, y = 27, label = "This is at 27", vjust = -0.5)

enter image description here

如果您要执行一些操作或希望使其更加自动化,可以使用以下功能:

add_label_line <- function(y, x, text = paste("This line is at", y)) {
  list(geom_hline(yintercept = y),
       annotate("text", x = x, y = y, label = text, vjust = -0.5)
  )
}

ggplot(mtcars, aes(wt, mpg)) + 
  geom_point() +
  add_label_line(c(25, 28, 31), 2.5)

enter image description here