如何将geom_segment连接到geom_line?

时间:2019-05-06 21:02:51

标签: r ggplot2

我想从图的底部开始连接一个线段,直到它在给定x处与geom_line相交为止。我认为最好的方法是使用geom_segment。如何以编程方式找到给定x的geom_line的位置?如何扩展此框架以支持构面?

mtcars %>% 
  ggplot(aes(hp, wt)) +
  geom_line() +
  geom_segment(aes(x = 150, y = 0, xend = 150, yend = 3.248397), col = "red")

enter image description here

2 个答案:

答案 0 :(得分:1)

对于这种特定情况,它应该起作用:

mtcars %>% 
  ggplot(aes(hp, wt)) +
  geom_line() +
  geom_segment(aes(x = 150, y = 0, xend = 150, yend = min(mtcars[mtcars$hp == 150, "wt" ])), col = "red")

如果您想要x所不存在的数据,则必须进行插值。

enter image description here 对于所有可用的x值并带有小平面:

library(dplyr)
df <-  mtcars %>% select(hp, wt, vs) %>% group_by(hp, vs) %>% summarise(min_wt = min(wt))
mtcars %>% 
  ggplot(aes(hp, wt)) +
  geom_line() +
  geom_segment( aes(x = hp, y = 0, xend = hp, yend = min_wt),data = df, col = "red") +  
  facet_grid(vs ~ .)

enter image description here

答案 1 :(得分:1)

library(tidyverse)

mtcars %>% 
  ggplot(aes(hp, wt)) +
  geom_line() +
  geom_segment(aes(x = 150, ####
                   y = 0, xend = 150, yend = 3.248397), col = "red")

enter image description here

data("mtcars")
# View(mtcars)
yy <- mtcars %>% 
  dplyr::filter(hp == 150) %>% 
  dplyr::select(hp, wt)
# length(yy$wt)

由于有两个感兴趣的值,使用线段和曲线表示可能会很有趣。

mtcars %>% 
  ggplot(aes(hp, wt)) +
  geom_line() +
  geom_segment(aes(x = 150, y = 0, xend = 150, yend = min(yy$wt)), col = "red") + 
  geom_curve(aes(x = 150, y = 0, xend = 150, yend = max(yy$wt)), 
                 curvature = -0.2, col = "blue",
             arrow = arrow(length = unit(0.03, "npc")))

enter image description here