r - ggplot - 添加垂直线

标签 r ggplot2

下面是我正在使用的 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"))

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

最佳答案

你可以试试这个:

# 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")

plot

关于r - ggplot - 添加垂直线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53604723/

相关文章:

r - 用离散轴注释 ggplot(带有可重复的示例)

r - 使用坐标点格式化数据框

r - 以分组方式将 data.frame/tibble 转换为列表

r - 如何在 R 中为函数添加红线

r - R 中 ggplot2 yaxis 标签中的 "Squared"上标

r - 如何用 ggplot 绘制过零的离散填充轮廓?

r - 在 R 中绘制具有级别的 netcdf 文件

r - 匹配R正则表达式中的字母

r - ggplot `scale_fill_manual()` 无限交替颜色

r - ggplot2:将颜色固定为因子水平