I would like to make a plot with two y axis and customise it, such as colors, axis thickness etc. But some of my data has NA values and I need the plotted lines to be connected, however they are not. I also plot points which show where the lines should be connected. I searched for examples but they do not really work for my case (such as here here and here). Example data:
Dates <- seq(as.Date("2018/03/15"), as.Date("2018/03/21"), "days")
V2=c(5.5,NA,NA,1,80,60,18)
V3=c(-8,NA,NA,-3.8,-14,-9,-6.2)
df <- data.frame(Dates,V2,V3)
Now, using the below code gives me the kind of plot that I need, but the data on the left side is not connected due to the NA entries.
plot(df$Dates, df$V2, axes=F, type="l", xlab="", ylab="",col="blue", main="", lwd=2.5)
points(df$Dates, df$V2, pch=20, col="blue", cex=1.5)
axis(2, col="blue",lwd=2, cex.axis=1.2, col.axis="blue", las=2)
mtext(2,text="V2",line=3, col="blue")
axis.Date(1, at=df$Dates , format="%d/%m/%Y",las=1, cex.axis=1.2, lwd = 1.5, col= "black", col.axis="black")
par(new=T) # to add to the existing plot
plot(df$V3, axes=F, xlab="", ylab="", type="l",lty=2, main="",lwd=2, col="red")
points(df$V3, pch=20, col="red")
axis(4, lwd=2,line=1.5,las=2,cex.axis=1.2, col="red", col.axis="red")
mtext(2,text="V3",line=-30, col="red")
Resulting in this plot which looks good, only it needs the left part to be connected via lines:
After that I kept trying the example from the first link, suggesting to ignore the NA.
xlim <- range(df$Dates) # not sure what this is doing
ylim <- range(df[-1], na.rm = TRUE) # ?
plot(V2 ~ Dates, na.omit(df), axes=F, type = "l", xlab="", ylab="", col="blue",lwd=2, xlim = xlim, ylim = ylim)
points(V2 ~ Dates, df, pch=20, col="blue", cex=1.5)
axis(2, col="blue",lwd=2, cex.axis=1.2, col.axis="blue", las=2)
axis.Date(1, at=df$Dates , format="%d/%m/%Y",las=1, cex.axis=1.2, lwd = 1.5, col= "black", col.axis="black")
mtext(2,text="V2",line=3, col="blue")
par(new=T) # to add to the existing plot
plot(V3 ~ Dates, na.omit(df), axes=F, xlab="", ylab="", type = "l",lty=2, col="red",lwd=2, xlim = xlim, ylim = ylim)
points(V3 ~ Dates, df, pch=20, col="red", cex=1.5)
axis(4, lwd=2,line=1.5,las=2,cex.axis=1.2, col="red", col.axis="red")
mtext(2,text="V3",line=-30, col="red")
However, the plot gets messed up and is not correct. The "blue part" looks ok, just the "red part" is strange. Please see it below. Any ideas how to get it to work? Thanks!