我想从图的底部开始连接一个线段,直到它在给定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")
答案 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
所不存在的数据,则必须进行插值。
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 ~ .)
答案 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")
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")))