Basically the question is the same as this one: How can I plot with 2 different y-axes? except that I have a date on the x axis and pretty(range()) doesn't work for me using dates.
(sorry I don't have enough "reputation" to comment the above question to ask for more info so I need to start a new question).
I wrote the following function:
PvsRef<-function(id,feature){
ymax= max(data[[feature]], na.rm=TRUE)
plotdata = data[data$ID==id,]
plot(plotdata$date,plotdata$ref, type="l", col="red", axes=FALSE, ylim=c(0,48), main=paste0("Reference vs.",feature), sub=as.character(id), xlab="", ylab="")
axis(2, ylim=c(0,48),col="red",las=1)
mtext("Reference",side=2,col="red",line=2.5)
box()
par(new=TRUE)
plot(plotdata$date,plotdata[[feature]], type="b", col="blue", axes=FALSE, ylim=c(0,ymax), xlab="", ylab="")
mtext(feature,side=4,col="blue",line=4)
axis(4, ylim=c(0,ymax), col="blue",col.axis="blue",las=1)
axis(1,pretty(range(plotdata$date),10))
mtext("Date",side=1,col="black",line=2.5)
axis(1,pretty(range(plotdata$date),10))
mtext("Date",side=1,col="black",line=2.5)
}
the x-axis however shows weird numbers instead of dates.
example data:
data = data.frame(ID=c(1,1,1,1,1,1), date=as.Date(c("2000-01-01","2000-02-01","2000-03-01","2000-04-01","2000-05-01","2000-06-01")), ref=c(30,23,43,12,34,43), other=c(120,140,230,250,340,440))
then I want to run the function using
PvsRef(1,"other")
but no proper x-axis appears.
EDIT:
if instead I use
axis.Date(1,pretty(range(plotdata$date),10))
mtext("Date",side=1,col="black",line=2.5)
proper dates show up, but there isn't 10 ticks as demanded by pretty.