rggplot:如何添加两条直线的最大距离垂直线

dfty9e19  于 2023-01-06  发布在  其他
关注(0)|答案(1)|浏览(224)

我有一个数据表dt,如下所示:

time   col_A    col_B     diff
1:    930  9925642  10025714  100098.53
2:    931  9925642  10025714  100098.53
3:    932  9925642  10025714  100098.53
4:    933  9925642  10025714  100098.53
5:    934  9925642  10025714  100098.53
---
237: 1456  9949509  10029605  80095.54
238: 1457  9949509  10029605  80095.54
239: 1458  9949509  10029605  80095.54
240: 1459  9949509  10029605  80095.54
241: 1500  9949509  10029605  80095.54

使用以下代码,我可以生成一个图:

idx <- 1:nrow(dt)
g <- ggplot(data = dt, aes(x = idx)) +
     geom_line(aes(y = col_A, group = 1, colour = "A"))
     geom_line(aes(y = col_B, group = 2, colour = "B")) +
     geom_vline(xintercept = dt[, .I[diff == max(diff)]], color = "black") +
     scale_color_manual(values = c("A" = "red", "B" = "blue") 
g

但是上面的黑线并不是我想要的,我想要的是用蓝色和红色的给这条线盖上盖子,并添加一个文本标签来显示最大的差值,就像这样:

我怎样才能实现这一点?谢谢

nle07wnf

nle07wnf1#

您可以在此处使用geomtextpath中的geom_textsegment

library(geomtextpath)

ggplot(data = dt, aes(x = idx, y = col_A)) +
  geom_line(aes(group = 1, colour = "A")) +
  geom_line(aes(y = col_B, group = 2, colour = "B")) +
  geom_textsegment(data = dt[which.max(dt$diff),], 
               aes(yend = col_B, xend = idx, label = round(diff, 3))) +
  scale_color_manual(values = c("A" = "red", "B" = "blue"))

    • 所用数据**

问题中的示例数据不足以进行演示,因此以下是用于上述示例的可重现数据集:

set.seed(1)

dt <- data.frame(time = 1:100, 
                 col_A = cumsum(runif(100, -5, 5)), 
                 col_B = cumsum(runif(100, -5, 5)) + 50)

dt$diff <- dt$col_B - dt$col_A
dt$idx  <- seq(nrow(dt))

相关问题