Angelo
Angelo

Reputation: 1785

R Plotly multiple line timeseries plot

please I have a dataframe with three simple columns: cusip (it's an identifier, similar to a stock name), date, price. For every date we should have a price for (almost) all the stocks in the daframe. By default, I don't know how many different stocks I could have in column "stock", it could be 2 or it could be max 20. For example:

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)

My simple goal is to create a time series plot where the x-axis correspond to the DATE column, and then a line with a different color for each unique cusip found in the dataframe. I read https://plotly.com/r/line-charts/ however their starting point is a dataframe that has a column for each unique item that they want to plot, whereas I only have 3 columns containing all the data. Thanks for your help.

Upvotes: 0

Views: 535

Answers (1)

Duck
Duck

Reputation: 39623

Try this:

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

Output:

enter image description here

Upvotes: 1

Related Questions