【问题标题】:How can I connect geom_segment to geom_line?如何将 geom_segment 连接到 geom_line?
【发布时间】:2019-05-07 05:30:18
【问题描述】:

我想从图表底部连接一个线段,直到它与给定 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")

【问题讨论】:

  • 在您的实际情况中,您是否有机会使用正在建模的数据,以便您可以更轻松地预测所选 x- 的 y 值价值?

标签: r ggplot2


【解决方案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,则必须进行插值。

对于所有可用的 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 ~ .)

【讨论】:

    【解决方案2】:
    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")))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-15
      • 2021-10-26
      • 1970-01-01
      • 2020-01-25
      • 2023-02-03
      • 1970-01-01
      相关资源
      最近更新 更多