【问题标题】:How to draw a line between two points when holding one axis fixed (time series)固定一个轴时如何在两点之间画一条线(时间序列)
【发布时间】:2019-01-28 23:20:05
【问题描述】:

我正在尝试使用 ggplot2 在同时观察到的两个变量的每个点之间画一条直线。 我查看了 geom_segment,但我很难让它适用于我的情况。

这是我的最小工作示例和我想要实现的绘图(我缺少的部分是蓝色)

我将不胜感激!

set.seed(1234)
y <- rnorm(10,0,0.01)
Date <- seq(as.Date("2000/1/1"), by = "day", length.out = 10)

example_df <- tibble(Date,y) %>% mutate(avg = mean(y))
ggplot(example_df, mapping = aes(x = Date)) + geom_point(mapping = aes(y = y)) +
  geom_line(aes(y = y)) + 
  geom_line(aes(y = avg), col = "red")

【问题讨论】:

  • 这些线路背后的逻辑是什么?
  • @NelsonGon 他们应该代表黑点和红线的距离。

标签: r ggplot2


【解决方案1】:

geom_segment 可以工作:

ggplot(example_df, aes(x = Date)) + 
    geom_point(aes(y = y)) +
    geom_line(aes(y = y)) + 
    geom_line(aes(y = avg), col = "red")+
    geom_segment(aes(xend = Date, y = y, yend = avg), col = 'blue')

【讨论】:

  • 太棒了,通过查看 geom_segment 的帮助,我永远不会明白如何做到这一点。我想我必须提供 x1 (这里是日期)、xend 和 y 和 yend 总是在 2 个变量的坐标之间。现在我明白了,非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-16
  • 2013-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多