R Plotly多线时间序列图

R Plotly multiple line timeseries plot

请给我一个包含三个简单列的数据框: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 列包含所有数据。 感谢您的帮助。

试试这个:

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')

输出: