i trying draw lines in same plot. x factor determined date , y factor number. load data, store in list , save min , max values date:
stocks <- list() stocks.min <- 0 stocks.max <- 0 stocks.min.date <- null stocks.max.date <- null (name in names(files)) { stocks[[name]] <- read.csv(files[[name]], sep=";") # convert date in r stocks[[name]]$date <- as.date(stocks[[name]]$date, "%d/%m/%y") # sets max value ylim in plotting if (stocks.max < max(stocks[[name]]$close)) { stocks.max <- max(stocks[[name]]$close) } # sets date value xlim in plot if (is.null(stocks.min.date) || min(stocks[[name]]$date) < stocks.min.date) { stocks.min.date <- min(stocks[[name]]$date) } if (is.null(stocks.max.date) || max(stocks[[name]]$date) > stocks.max.date) { stocks.max.date <- max(stocks[[name]]$date) } }
after create empty plot using values above:
plot(0, xlab="time", ylab="closing prices", main="stock values", xlim=c(stocks.min.date, stocks.max.date), ylim=c(stocks.min, stocks.max))
and add lines data:
for (name in names(stocks)) { lines(x=stocks[[name]]$date, y=stocks[[name]]$close, col=colors[[name]], type="l", lwd=2) }
when graph plotted, data correctly displayed, shows date numbers instead of dates in x axis seen in image below:
how can correct issue?
i suggest using normalized series plot stocks data have. quantmod
helps lot here. solves 2 purposes -
- get x-axis labels dates.
- normalize series can view number of series without worrying orders of absolute values (~67 inr, ~1120 krw, on...)
this use purposes.
library(quantmod) tickers <- c('goog', 'msft', 'aapl', 'amzn') getsymbols(tickers, src = 'yahoo', = '2015-01-01') normalise <- function(x) x/as.numeric(x)[1] - 1 chart_theme <- chart_theme() chart_theme$col$line.col <- "red" chart_series(normalise(cl(goog)), theme = chart_theme) add_ta(normalise(cl(msft)), on = 1, col = "black", lty = 1) add_ta(normalise(cl(amzn)), on = 1, col = "blue", lty =1) add_ta(normalise(cl(aapl)), on = 1, col = "darkgreen", lty =2)
hope helps.
Comments
Post a Comment