adding a vertical line to a chartSeries graphic - r

I hope this isn't redundant as I've googled extensively and still have not found an answer. I'm plotting intraday data and want to place a vertical line at a specific point in time. It seems I have to use the function addTA but it always plots below my graph in some weird empty white space. Here's some sample code and data. Thanks for any help.
Data:
date,value
29-DEC-2010:00:02:04.000,99.75
29-DEC-2010:00:03:44.000,99.7578125
29-DEC-2010:00:05:04.000,99.7578125
29-DEC-2010:00:07:53.000,99.7421875
29-DEC-2010:00:07:57.000,99.71875
29-DEC-2010:00:09:20.000,99.7421875
29-DEC-2010:00:11:04.000,99.75
29-DEC-2010:00:12:56.000,99.7421875
29-DEC-2010:00:13:05.000,99.7421875
Code:
#set up data
data = read.csv("foo.csv")
values = data[,2]
time = c(strptime(data[,1],format="%d-%b-%Y:%H:%M:%S",tz="GMT"))
dataxts = xts(values, order.by=time,tzone="GMT")
# chart data
chartSeries(dataxts)
# add vertical line - this is where I have no clue what's going on.
addTA(xts(TRUE,as.POSIXlt("2010-12-29 00:11:00",tz="GMT"),on=1))
What ends up happening is that I get a vertical line where I want it, 2010-12-29 00:11:00, but it sits in a new section below the graph instead of overlaid on it. Any ideas?

You're passing on as an argument to xts, but you should be passing it to addTA.
I think you mean to be doing this:
addTA(xts(TRUE,as.POSIXlt("2010-12-29 00:11:00",tz="GMT")),on=1)
That said, it still doesn't work for me with your sample data. However, if what you had works with your real data except it puts the line in a new panel, then this should work and not open a new panel.
I have an addVLine function in my qmao package that is essentially the same thing.
Edit
Aside from the typo with the parenthesis, the xts object also needs a column name in order for addTA to work (I think... at least in this case anyway). Also, you must give an x value that exists on your chart (i.e. 11:04, not 11:00)
colnames(dataxts) <- "x"
chartSeries(dataxts)
addTA(xts(TRUE,as.POSIXlt("2010-12-29 00:11:04",tz="GMT")),on=1, col='blue')
# or
# library(qmao)
# addVLine(index(dataxts[7]))
Edit 2
Perhaps a better approach is to use the addLines function
addLines(v=7)
Or, if you know the time, but don't know the row number, you could do this
addLines(v=which(index(dataxts) == as.POSIXlt("2010-12-29 00:11:04", tz="GMT")))
which gives

Related

plot function type=ā€œnā€ is ignored for plot(y~x)?

I am trying to plot a graph of certain values against time using the plot function.
I am simply trying to change the representation of the dots, using the pch= function. However R is simply ignoring me! I have also tried removing the dots so that I can place labels instead, but when I type in type="n" it ignores that too!
I am using the exact same format of code that I have used for other plots but this time it just isn't cooperating.
If I specify other features such as the title or the x/y axis labels, it will add those in but it simply ignores the pch or type commands.
This is my basic code:
plot(Differences ~ Time, data=subsetH)
But if I run
plot(Differences ~ Time, type="n", data=subsetH)
or
plot(Differences ~ Time, pch=2, data=subsetH)
it keeps plotting the same thing.
Is there something obvious I have missed?
I just came across your question because I encountered the same thing - creating an empty plot did not work, as type='n' was always ignored (as well as other type specifications).
With the help of this entry: Plotting time-series with Date labels on x-axis
I realized that my date format needed to be assigned as "date" class (as.Date()).
I know your entry dates back a little bit already, but maybe it's still useful.

not enough horizontal space to display frequencies

I am attempting to use the aggr() function of the VIM package to plot missing data patterns. My plots don't show the frequencies/proportions of missing data patterns to the outside of the right-side axis. Should look like this. I'm getting an error that there is "not enough horizontal space to display frequencies".
library(VIM)
aggr(sleep, prop = T, numbers = T)
I don't do much base R plotting. I think this has something to do with margins. I reviewed this informative tutorial on margins, but I did not find my way to a solution.
I had two problems: one localized and one related to aggr().
1) This function helped me to reset par("pin"). Resetting made the toy example work.
resetPar <- function() {
dev.new()
op <- par(no.readonly = TRUE)
dev.off()
op
}
par(resetPar())
2) My actual use case was still failing with the same horizontal space error. I realized I needed to set the cex.numbers parameter of aggr() to something less than 1.

Graphing multiple variables in R

I am currently attempting to graph multiple columns in a matrix in R. So far, I have figured things out, but here is my problem- when I submit a matrix with 5 columns, I only get a graph with 4 lines. I've noticed that the missing line is always the line closest to the x-axis. I've been working on this for several hours now, and I have tried several different things. Any advice or help on how to get R to produce that 5th line (with a corresponding color filling the space between the x-axis and the line) would be greatly appreciated.
gender=cbind(matrix(malepop),matrix(femalepop))
plotmat(year,gender)
#a sample set
biggen=cbind(malepop,femalepop,malepop,femalepop)
#start of the function
plotmat2=function(years,m,colors){
n=m/1000000
#create a plot with the base line
plot(years,n[,1],type='l',ylim=c(0,10))
##create a for loop to generate all other lines and fill in the spaces
for (i in ncol(n):2) {
newpop=matrix(rowSums(n[,1:i]))
lines(year,newpop)
cord.xmat=c(min(years),years,max(years))
cord.ymat=c(-1,newpop[,1],-1)
polygon(cord.xmat,cord.ymat,col=clrs[i])
next
cord.xmat=c(min(years),years,max(years))
cord.ymat1=c(-1,n[,1]/1000000,-1)
polygon(cord.xmat,cord.ymat,col="purple")
}
}
#sample color set
clrs=c("red","blue","yellow","pink","purple", "cyan", "hotpink")
#run the function
plotmat2(year,biggen,clrs)
Thanks for any and all help you can provide!
It might be that you are unintentionally covering up your first line with the other colored sections, and that you may be skipping the creation of the polygon for n[,1].
From the way you tried to graph the columns in descending order, I am assuming you know that your columns are in ascending size order (the section that is pink in your example plot would be the final column in the matrix "biggen"). In case I am wrong about this, it might be a good idea to change your polygon shading using the density argument, which may help you see if you are covering up other sections by accident.
## plotmat2 function
plotmat2=function(years,m,colors){
n=m/1000000
#create a blank plot based on the baseline
plot(years,n[,1],type='n',ylim=c(0,10))
##create a for loop to generate all other lines and fill in the spaces
for (i in ncol(n):1) {
newpop=matrix(rowSums(n[,1:i]))
lines(year,newpop)
cord.xmat=c(min(years),years,max(years))
cord.ymat=c(-1,newpop[,1],-1)
polygon(cord.xmat,cord.ymat,col=colors[i], density=10)
}
}
P.S. If this doesn't help fix the problem, it might help if you provided a portion of your dataset. I am still learning about R and about StackOverflow, but that seems to be sensible advice that is given on a lot of the threads I have read on here. Good luck!

Force starting point of lines()

Perhaps because the question is so basic, the keywords that I can think up for this question all directs me to other things. I am trying to draw a graph with spiky curve lines that connect the medians. The real data is very big, but the starting values are duplicates of (0,0):
DATA<-data.frame(time<-c(sort(rep(c(0,2,4,8,12),4))),
conc<-c(rep(0,4),rnorm(n=4,mean=30),
rnorm(n=4,mean=10),
rnorm(n=4,mean=35),
rnorm(n=4,mean=15)))
# Create blank graph
plot(NULL,NULL,xlab="Time",ylab="Conc",
xlim=c(0,15),ylim=c(0,40),main="Example")
# Add line
require(quantreg)
require(plyr)
require(MatrixModels)
DATA<-plyr::arrange(DATA,time)
fit3<-rqss(DATA$conc~qss(DATA$time,constraint="N"),tau=0.5,data = DATA)
lines(unique(DATA$time)[-1],fit3$coef[1] + fit3$coef[-1],lwd=2)
As you can see, the line does not connect to the starting (0,0) values and instead start at the next lowest level.
I was tempted to cheat, but it does not connect to the lines and I would really prefer to work it out with the rest of the code instead of trying to pass off two lines as one:
# Cheating getaway but does not work well, segments are not connected
segments(x0=0,y0=0,x1=2,y1=30,lwd=2)
Some relevant answers that I found were not appropriate for my situation.
Line in R plot should start at a different timepoint for example suggest modifying the data, which would not help to extend my line and plus my actual data is too big that I would be wary to do this kind of manipulation. I would not want to use plot(x,y,type="l") even though it goes through the (0,0) point, because 1) it looks bad on the huge data, and 2) I would have to overlay another similar line using lines(). I wonder whether it has more to do with rqss and less with lines?
I apologize if this has already been asked before.

how to parse tick data with quantmod?

I want to generate daily candle bars using quantmod, but what I got is GBPJPY.csv tick data, like
Symbol,Time,Bid,Ask
GBP/JPY,2013-12-29 17:01:06.000,173.319,173.544
GBP/JPY,2013-12-29 17:01:07.000,173.319,173.459
GBP/JPY,2013-12-29 17:01:08.000,173.319,173.459
GBP/JPY,2013-12-29 17:01:08.000,173.319,173.544
I want to know how to parse it and generate daily candle bar.
First step is to load the ticks into an xts object; second step is to make bars from that xts object.
I will assume your csv file only contains GBP/JPY data (i.e. the first column is redundant). If not, you just need to do a bit more work to use the first column. (Or, better, pre-process your data using unix tools to give you one file per symbol.)
You also didn't say if you want both bid and ask bars, or just one, or mid. The below code assumes bid, as it is simpler.
d=try(read.table(source_fname,sep=',',header=T,stringsAsFactors=F),silent=T)
if(inherits(d,"try-error")){
print(d);quit() #Or some kind of error-handling
}
timestamps = as.POSIXct(d$Time)
bids = xts(d$Bid,timestamps)
Because we only have one column, making daily bars is easy:
to.daily(bids)
It gives:
bids.Open bids.High bids.Low bids.Close
2013-12-29 173.319 173.319 173.319 173.319
If you need to do something more complicated (e.g. make OHLC for both bid and ask), this answer shows how to use period.apply() to apply a custom function to any sized block of ticks: https://stackoverflow.com/a/19896834/841830 (that question also shows how you could use read.zoo() to read the ticks; it is a wrapper around the read.table() function).

Resources