1

How can I write R code that will take all columns from a single xts object and plot them on a single chart?

My xts object looks like screenshot below and I don't know while writing a code what will be the number of columns there: screenshot of xts object

I want R to take each of the columns and plot them as one of the lines on a single chart. Ideally, it should be some fancy quantmod charts (as each of columns is a price for a particular investment instrument) but even simple plot will be okay.

Additional comments.

Here is a datafile I use (csv): One Drive sharepoint link to zip file

And this is the code I have so far:

etfs_history_input <- read.zoo(file = "etfs_history.csv", sep = ",", index.column = 1, header = TRUE, FUN=as.POSIXct, tz = "Europe/Moscow", format = "%Y-%m-%d")
etfs_h <- as.xts(coredata(etfs_history_input), order.by = index(etfs_history_input))

The closest thing I managed to achieve in meeting my target output is writing this:

apply(etfs_h, 2, plot)

But result:

  • plots different instruments on different charts
  • doesn't show the instrument names (column titles)
Egor_RU
  • 15
  • 4
  • 1
    May we see whatever code you have at present? You will find you are much more likely to get help if you make a start on the problem. – halfer Jan 09 '18 at 20:07

2 Answers2

0

you can try something like melting and then plotting with ggplot

library(data.table)
library(ggplot2)
d <- melt(object, measures.var = patterns("^FX"))
ggplot(d, aes(date,value, col=variable)) + 
  geom_point() 

but without an example to test that is just a blind try

denis
  • 5,580
  • 1
  • 13
  • 40
  • Thanks for your help! I tried this (with changing "object" to my xts object name. It doesn't work, unfortunately: Error in eval(expr, envir, enclos) : object 'variable' not found. Was I supposed to change "variable" to smth else as well? – Egor_RU Jan 10 '18 at 06:18
0

Read ?plot.xts if you'd like to plot using xts. Example:

library(quantmod)
syms <- c("AAPL","MSFT", "NQ", "SSRM")
getSymbols(syms)

x <- lapply(syms, function(x) Cl(get(x)))
m <- do.call(cbind, x)

plot(m, main = "stocks")
addLegend("topleft", on=1, 
          legend.names = colnames(m), lty = 1)

enter image description here

FXQuantTrader
  • 6,821
  • 3
  • 36
  • 67
  • If you want to chart using quantmod as another alternative, doing something like this might be helpful https://stackoverflow.com/questions/38136008/adding-multiple-chart-series-in-quantmod-r/38136305#38136305 – FXQuantTrader Jan 14 '18 at 02:50