【问题标题】:R Plotly multiple line timeseries plotR Plotly多线时间序列图
【发布时间】:2021-01-10 01:02:21
【问题描述】:

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

【问题讨论】:

    标签: r plotly r-plotly


    【解决方案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')
    

    输出:

    【讨论】: