【问题标题】:ggplot - adding vertical linesggplot - 添加垂直线
【发布时间】:2019-05-05 09:28:15
【问题描述】:

下面是我正在使用的 data.table。每当 longSignal 列为 1 时,我都想绘制垂直线。

data.frame(
        index = c("2011-09-09 17:00:00", 
                    "2011-09-12 17:00:00",
                    "2011-09-13 17:00:00", "2011-09-14 17:00:00",
                    "2011-09-15 17:00:00", "2011-09-16 17:00:00", "2011-09-19 17:00:00",
                    "2011-09-20 17:00:00", "2011-09-21 17:00:00",
                    "2011-09-22 17:00:00", "2011-09-23 17:00:00", "2011-09-26 17:00:00",
                    "2011-09-27 17:00:00", "2011-09-28 17:00:00", "2011-09-29 17:00:00",
                    "2011-09-30 17:00:00", "2011-10-03 17:00:00",
                    "2011-10-04 17:00:00", "2011-10-05 17:00:00", "2011-10-06 17:00:00",
                    "2011-10-07 17:00:00"),
   EURUSD.Close = c(1.36534, 1.367895, 1.36783, 1.37546, 1.38764, 1.38005,
                    1.36849, 1.37009, 1.35722, 1.346385, 1.35002, 1.353255,
                    1.35825, 1.35425, 1.359705, 1.33876, 1.31759, 1.33489, 1.33482,
                    1.34374, 1.33771),
     longSignal = c(0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,
                    0)
)

这是我试图在 ggplot 中使用的代码

ggplot(RSI_data, aes(index, EURUSD.Close)) +
  geom_line() + 
  geom_vline(aes(xintercept = as.numeric(RSI_data$index[which(RSI_data$longSignal == 1)]), 
             size = 2, colour = "red"))

我遇到了错误。谁能告诉我我该怎么做?一世 提前致谢!

【问题讨论】:

  • 您能否通过分享您的数据样本来让您的问题可重现,以便其他人可以提供帮助(请不要使用str()head() 或屏幕截图)?您可以使用 reprexdatapasta 包来帮助您。另见Help me Help you & How to make a great R reproducible example?
  • 我会说“欢迎来到 SO”,但你有 353 分,所以应该已经知道图片既不是代码也不是数据,除非主题是图像处理。是时候重新访问stackoverflow.com/questions/tagged/r 提供的指南了
  • 对不起,这是我第一次在问题中添加数据。

标签: r ggplot2


【解决方案1】:

你可以试试这个:

# convert index to date-time format; this makes x-axis continuous rather than
# categorical, so you don't have to specify the group for geom_line.
RSI_data$index <- as.POSIXct(as.character(RSI_data$index))

ggplot(RSI_data,
       aes(x = index, y = EURUSD.Close)) +
  geom_line() +
  geom_vline(data = subset(RSI_data, longSignal == 1), # filter data source
             aes(xintercept = index),
             size = 2, colour = "red")

【讨论】:

    【解决方案2】:

    如果您将 xintercept 术语放在 aes() 之外,那么它可以工作。此外,您可能会收到另一个错误提示 geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic?,所以 group=1 可以阻止该错误

     ggplot(RSI_data, aes(index,EURUSD.Close)) +
          geom_line(group=1) +
          geom_vline(xintercept = as.numeric(RSI_data$index[which(RSI_data$longSignal == 1)]), 
                     size = 2, colour = "red")
    

    【讨论】: