R绘制多线时间序列图

时间:2020-09-23 18:52:44

标签: r plotly r-plotly

请给我一个包含三个简单列的数据框:cusip(它是一个标识符,类似于股票名称),日期,价格。对于每个日期,我们都应该为(几乎)daframe中的所有股票定价。 默认情况下,我不知道“股票”列中可以有多少种不同的股票,可能是2,也可能是最大20。 例如:

CUSIP <- c("cusip1","cusip2","cusip3","cusip1","cusip2","cusip3","cusip1","cusip2","cusip3","cusip1","cusip2", "cusip1","cusip2","cusip3")
  DATE <- c("2020-09-01","2020-09-01","2020-09-01","2020-09-02","2020-09-02","2020-09-02","2020-09-03","2020-09-03",
            "2020-09-03","2020-09-04","2020-09-04","2020-09-05","2020-09-05","2020-09-05")
  PRICE <- c(100, 90, 85, 102, 88, 80, 97, 81, 83, 85, 84, 88, 81, 91)
  df = data.frame(CUSIP, DATE, PRICE, check.rows = F, check.names = F, stringsAsFactors = F)

我的简单目标是创建一个时间序列图,其中x轴对应于DATE列,然后为在数据框中找到的每个唯一的cusip创建一条具有不同颜色的线。 我读了https://plotly.com/r/line-charts/,但是他们的出发点是一个数据框,其中有一个列用于他们要绘制的每个唯一项,而我只有3列,包含所有数据。 感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

尝试一下:

library(plotly)
library(tidyverse)
#Data
CUSIP <- c("cusip1","cusip2","cusip3","cusip1","cusip2","cusip3","cusip1","cusip2","cusip3","cusip1","cusip2", "cusip1","cusip2","cusip3")
DATE <- c("2020-09-01","2020-09-01","2020-09-01","2020-09-02","2020-09-02","2020-09-02","2020-09-03","2020-09-03",
          "2020-09-03","2020-09-04","2020-09-04","2020-09-05","2020-09-05","2020-09-05")
PRICE <- c(100, 90, 85, 102, 88, 80, 97, 81, 83, 85, 84, 88, 81, 91)
df = data.frame(CUSIP, DATE, PRICE, check.rows = F, check.names = F, stringsAsFactors = F)
#Code
plotly::plot_ly(data = df, x = ~DATE, y = ~PRICE,
                color = ~CUSIP,type = 'scatter', mode = 'lines')

输出:

enter image description here