1

I am trying to create a plot with dual Y-axis. I modified this wonderful answer given HERE by Ben Bolker and it worked perfectly. enter image description here Now, I want to replace one line plot with barplot but for some reason, my barplot and line plots are not aligning together well. enter image description here

My code looks like this

## set up some fake test data
time <- seq(0,72,12)
betagal.abs <- c(0.05,0.18,0.25,0.31,0.32,0.34,0.35)
cell.density <- c(500,1000,2000,3000,4000,5000,6000)
se1 <- c(0.01,0.02,0.03,0.04,0.05,0.06,0.07)
se2 <- c(50,100,200,300,400,500,300)
## Plot first set of data and draw its axis
barCenters <- barplot(height = cell.density, 
                      beside = TRUE, 
                      las = 1,
                      ylim = c(0, 7000),
                      axes=FALSE,
                      type="b"
)
## a little farther out (line=4) to make room for labels
mtext("Relative expression",side=4,col="black",line=4, las=0) 
axis(4, ylim=c(0,7000), col="black",col.axis="black",las=1)
segments(barCenters, cell.density  - se2 * 2, barCenters,
         cell.density + se2 * 2, lwd = 1.5)
arrows(barCenters, cell.density - se2 * 2, barCenters,
       cell.density + se2 * 2, lwd = 1.5, angle = 90,
       code = 3, length = 0.05)
## Allow a second plot on the same graph
par(new=TRUE)
plot(time, betagal.abs, pch=16, axes=FALSE, ylim=c(0,1), xlab="", ylab="", 
     type="b",col="black", main="Test data")
arrows(time, betagal.abs, time, betagal.abs  + se1, length= 0.05,angle=90)
arrows(time, betagal.abs, time, betagal.abs  - se1, length= 0.05,angle=90)
axis(2, ylim=c(0,1),col="black",las=1)  ## las=1 makes horizontal labels
mtext("Relative activity",side=2,line=2.5)
box()

## Draw the time axis
axis(1,pretty(range(time),10))
mtext("Time (Hours)",side=1,col="black",line=2.5)  

## Add Legend
legend("topleft",legend=c("Relative activity","Relative expression"),
       text.col=c("black","black"),pch=c(16,15),col=c("black","black"))

Any suggestion will be helpful. Thanks

pali
  • 195
  • 2
  • 14

0 Answers0