Strange behaviour of plot.xts when adding vertical lines to a plot - r

I am experiencing a really strange issue when trying to add vertical lines to an existing plot of an xts object. The following code should allow you to reproduce my problem.
require(xts)
data("sample_matrix")
test <- xts(coredata(sample_matrix)[,1], order.by = as.Date(index(sample_matrix)))
plot.xts(test)
addEventLines(events = xts(x = '', order.by = as.Date('1970-04-01')), lty = 2, col = 'red', lwd = 1.5)
What happens is that when I run the first four lines code up to the last line, everything works fine and the plot looks exactly as I want it to be. Still, after running the last line of code, magics happens and the background vertical lines, for no apparent reason, get cut at both ends. Here are the two plots before and after running the last line of code:
Can someone help me solve this problem?

Related

"Plot.new has not been called yet" issue using plot() [duplicate]

Why does this happen?
plot(x,y)
yx.lm <- lm(y ~ x)
lines(x, predict(yx.lm), col="red")
Error in plot.xy(xy.coords(x, y), type = type, ...) :
plot.new has not been called yet
Some action, very possibly not represented in the visible code, has closed the interactive screen device.
It could be done either by a "click" on a close-button, or it could also be done by an extra dev.off() when plotting to a file-graphics device. (The second possibility might happen if you paste in a multi-line plotting command that has a dev.off() at the end of it, but had errored out at the opening of the external device. So the dangling dev.off() on a separate line accidentally closes the interactive device).
Some (most?) R implementations will start up a screen graphics device open automatically, but if you close it down, you then need to re-initialize it.
On Windows that might be window(); on a Mac, quartz(); and on a Linux box, x11(). You also may need to issue a plot.new() command. I just follow orders. When I get that error I issue plot.new() and if I don't see a plot window, I issue quartz() as well. I then start over from the beginning with a new plot(., ., ...) command and any further additions to that plot screen image.
In my case, I was trying to call plot(x, y) and lines(x, predict(yx.lm), col="red") in two separate chunks in Rmarkdown file. It worked without problems when running chunk by chunk, but the corresponding document wouldn't knit. After I moved all plotting calls within one chunk, problem was resolved.
As a newbie, I faced the same 'problem'.
In newbie terms :
when you call plot(), the graph window gets the focus and you cannot enter further commands into R. That is when you conclude that you must close the graph window to return to R.
However, some commands, like identify(), act on open/active graph windows.
When identify() cannot find an open/active graph window, it gives this error message.
However, you can simply click on the R window without closing the graph window. Then you can type more commands at the R prompt, like identify() etc.
plot.new() error occurs when only part of the function is ran.
Please find the attachment for an example to correct error
With error....When abline is ran without plot() above
Error-free ...When both plot and abline ran together
I had the same problem... my problem was that I was closing my quartz window after plot(x,y). Once I kept it open, the lines that previously resulted in errors just added things to my plot (like they were supposed to). Hopefully this might help some people who arrive at this page.
If someone is using print function (for example, with mtext), then firstly depict a null plot:
plot(0,type='n',axes=FALSE,ann=FALSE)
and then print with newpage = F
print(data, newpage = F)
I had the problem in an RMarkdown, and putting the offending line on the previous line of code helped.
Minimal Reproducible Example
This will error if run line by line in an Rmd:
x <- rbind(matrix(rnorm(100, sd = 0.3), ncol = 2),
matrix(rnorm(100, mean = 1, sd = 0.3), ncol = 2))
colnames(x) <- c("x", "y")
(cl <- kmeans(x, 2))
plot(x, col = cl$cluster)
points(cl$centers, col = 1:2, pch = 8, cex = 2)
but this works:
x <- rbind(matrix(rnorm(100, sd = 0.3), ncol = 2),
matrix(rnorm(100, mean = 1, sd = 0.3), ncol = 2))
colnames(x) <- c("x", "y")
(cl <- kmeans(x, 2))
plot(x, col = cl$cluster); points(cl$centers, col = 1:2, pch = 8, cex = 2)
The only change is that the offending line (the last one) is placed after the last succeeding line (placing a ; in between). You can do it for as many offending lines as desired.

Type "h" plot gives me points instead of vertical lines (R)

Hi my problem is that yesterday i created a plot of type "h" and it gave me a plot with vertical lines which is perfect to plot stock returns. Then today, i try to run it again and now the plot is giving me points instead of vertical lines... any idea?
I know it sounds a little weird but it's not the first time that i try to run code previously saved in R and that it doesn't work anymore! It's really frustrating but i guess that i'm probably missing something...
I tried to restart my computer and running the code again but it still the same and i tried changing type to "l" to see if it would work but i still get points instead of lines
Code:
PSet1_W2019 <- read.table("PSet1_W2019.txt",header = TRUE, skipNul = T )
colnames(PSet1_W2019)[colnames(PSet1_W2019)=="ÿþ"] <- "...1"
PSet1_W2019$TSXr<- c(0, diff(PSet1_W2019$TSX)/PSet1_W2019$`TSX`[-length(PSet1_W2019$`TSX`)])
plot(PSet1_W2019$...1,PSet1_W2019$TSXr,xlab="Trading day", ylab="TSX returns", type = 'h')
legend("topright", legend=c("mean", "median","10e quantiles","25e quantiles","75e quantiles","90e quantiles"),
col=c("red", "orange","darkblue","blue","magenta","darkmagenta"),lty = 1,cex = 0.7)
Datas (PSet1_W2019)
Original datas- https://www.dropbox.com/s/aq7kga9m09du1kh/PSet1_W2019.txt?dl=0
dput(head(PSet1_W2019))-https://www.dropbox.com/s/4huw8ma3wvryh3v/dput%28%20%29.txt?dl=0
Picture: What i get(without the horizontal lines though)

How do I exclude parameters from an RDA plot

I'm still relatively inexperienced manipulating plots in R, and am in need of assistance. I ran a redundancy analysis in R using the rda() function, but now I need to simplify the figure to exclude unnecessary information. The code I'm currently using is:
abio1516<-read.csv("1516 descriptors.csv")
attach(abio1516)
bio1516<-read.csv("1516habund.csv")
attach(bio1516)
rda1516<-rda(bio1516[,2:18],abio1516[,2:6])
anova(rda1516)
RsquareAdj(rda1516)
summary(rda1516)
varpart(bio1516[,2:18],~Distance_to_source,~Depth, ~Veg._cover, ~Surface_area,data=abio1516)
plot(rda1516,bty="n",xaxt="n",yaxt="n",main="1516; P=, R^2=",
ylab="Driven by , Var explained=",xlab="Driven by , Var explained=")
The produced plot looks like this:
Please help me modify my code to: exclude the sites (sit#), all axes, and the internal dashed lines.
I'd also like to either expand the size of the field, or move the vector labels to all fit in the plotting field.
updated as per responses, working code below this point
plot(rda,bty="n",xaxt="n",yaxt="n",type="n",main="xxx",ylab="xxx",xlab="xxx
Overall best:xxx")
abline(h=0,v=0,col="white",lwd=3)
points(rda,display="species",col="blue")
points(rda,display="cn",col="black")
text(rda,display="cn",col="black")
Start by plotting the rda with type = "n" which generates an empty plot to which you can add the things you want. The dotted lines are hard coded into the plot.cca function, so you need either make your own version, or use abline to hide them (then use box to cover up the holes in the axes).
require(vegan)
data(dune, dune.env)
rda1516 <- rda(dune~., data = dune.env)
plot(rda1516, type = "n")
abline(h = 0, v = 0, col = "white", lwd = 3)
box()
points(rda1516, display = "species")
points(rda1516, display = "cn", col = "blue")
text(rda1516, display = "cn", col = "blue")
If the text labels are not in the correct position, you can use the argument pos to move them (make a vector as long as the number of arrows you have with the integers 1 - 4 to move the label down, left, up, or right. (there might be better solutions to this)

Text not appearing on XTS plot

I'm having trouble adding some text to an plot of time series data in R using xts. I've produced a simple example of the problem.
My text() command seems to do nothing, whereas I can add a points to the plot. I've tried to keep the code simple by using defaults where possible
require(quantmod)
# fetch the data and plot it using default options
getSymbols('MKS.L')
plot(MKS.L$MKS.L.Close)
# try to add text - doesn't appear
text(as.Date('2012-01-01'),y=500,"wobble", cex=4)
# add a point - this does appear
testPos <- xts(600, as.Date('2012-01-01'))
points( testPos, pch = 3, cex = 4, col = "red" )
Any help appreciated - I'm pretty new to R and I've spent hours on this!
Not a direct answer, but the plot.xts function that comes with the xts package is not fully developed.
You're much better off using plot.zoo or plot.xts from the xtsExtra package (which was written as a Google Summer of Code project with the intention being to roll it into the xts package)
Either of these will work:
plot(as.zoo(MKS.L$MKS.L.Close))
text(as.Date('2012-01-01'),y=500,"wobble", cex=4)
#install.packages("xtsExtra", repos="http://r-forge.r-project.org")
xtsExtra::plot.xts(MKS.L$MKS.L.Close)
text(as.Date('2012-01-01'),y=500,"wobble", cex=4)

Inconsistent results saving png() and jpeg() in R

I am saving some complicated graphs off in an R program that include plot(), lines(), points() and abline() function calls and have tried using both png() and jpeg(), but both are rendering very inconsistent results. In one run the grid will be saved in the background, in the next it will not. In one run, the points will be added at the correct lwd, in another they will be huge, or maybe not added at all. In another run, a line will added, and then disappear when I run it again. I am looping through hundreds of iterations, and getting different results with almost every run.
png(paste("/someFilePlace/pics/", propIn, ".png", sep = ""))
plot(plotDat$yhat, col = "white", ylim = c(0,max(plotDat$yhat)*1.1),xaxt='n')
fairlylightgray <- rgb(204/255, 204/255, 204/255, alpha=0.4)
abline(v=(seq(0,1700,100)), col=fairlylightgray, lty="dotted")
abline(h=(seq(0,10,0.5)), col=fairlylightgray, lty="dotted")
points(plotDat$y, cex = '*', lwd = 3, col= "gray")
lines(plotDat$yhat, col = "#08519C")
axis(1, at = c(1,500,1000,1500),
labels = c(plotDat$dt[1],plotDat$dt[500],plotDat$dt[1000],plotDat$dt[1500]))
dev.off()
Congratulations, I think you may have found an obscure almost-bug (at least, failure to intercept a user error). Try replacing cex="*" with something sensible in your code (it should be a number -- or maybe you meant pch="*").
I am able to get different results in different PNGs as follows (if I plot in an X11 window I can get funny things to happen as I resize the window).
for (i in 1:10) {
png(paste("tmp",i,"png", sep="."))
plot(1:10,1:10,cex="*");
dev.off()
}

Resources