[R] plot with two y axes BUT unaligned x axis

Jim Lemon jim at bitwrit.com.au
Thu Jun 16 10:53:14 CEST 2011


On 06/15/2011 09:51 PM, bjmjarrett wrote:
> Hi all,
>
> I have scoured the archives of this forum but nothing quite seems to fit the
> bill...
>
> I would like to plot a graph displaying two variables (y axes) that share
> date as the x axis. However, the date values for each variable are not the
> same - for example, some parasitoids were not released on days that
> collections from the trap took place, whilst sometimes releases did occur on
> the same day. I would like to align them. My code is:
>
> ####
> CollectionDate<-as.Date(CollectionDate,"%m/%d/%Y") # days that had
> collections
> release.date.Total<-as.Date(release.date.Total,"%m/%d/%Y") # days that had
> releases
>
> par(mar=c(5,4,4,4)+0.1)
>
> plot(CollectionDate[data$Trap=="DPAU1"],TotalP[data$Trap=="DPAU1"],type="n",ylim=c(0,80),xlab="Time",ylab="Number
> of egg masses") # I am using one trap of many
>
> lines(CollectionDate[data$Trap=="DPAU1"],TotalP[data$Trap=="DPAU1"],lwd=2)
>
> par(new=T)
>
> plot(release.date.Total[data$Trap=="DPAU1"],parasitoid.total[data$Trap=="DPAU1"],axes=F,type="h",lty=1,col="red",xlab="",ylab="",lwd=1.2)
>
> axis(4,las=1)
>
> mtext(side=4,line=3,"Total parasitoids released")
> ###
>
> As in the above code, I suppressed the axes for the second plot, but if I
> don't the x axis (date) has two tick marks for each year.
>
> Is there a way to align the date objects to begin with without compromising
> the graphs themselves?
>
Hi Ben,
This might do what you want:

collection_dates<-as.Date(paste(sort(sample(1:30,15)),"05","2011",sep="/"),
  "%d/%m/%Y")
release_dates<-as.Date(paste(sort(sample(1:30,15)),"05","2011",sep="/"),
  "%d/%m/%Y")
release_n<-sample(50:100,15)
collect_n<-sample(50:100,15)
xtickpos<-as.numeric(as.Date(paste(c(1,10,20,30),"05","2011",sep="/"),"%d/%m/%Y"))
xticklab<-format(as.Date(paste(c(1,10,20,30),"05","2011",sep="/"),"%d/%m/%Y"))
library(plotrix)
twoord.plot(sort(collection_dates),collect_n,sort(release_dates),release_n,
  lylim=c(45,105),rylim=c(45,105),xlab="Date",
  ylab="Parasitoids collected",main="Collect/Release",
  rylab="Parasitoids released",xtickpos=xtickpos,xticklab=xticklab)
legend(as.numeric(as.Date("1/5/2011","%d/%m/%Y")),55,
  c("Collection","Release"),lty=1,col=1:2,pch=1:2)

Jim



More information about the R-help mailing list