Xizam Xizam - 3 months ago 13
R Question

Plotting on both sides of the X-axis on a barplot in R

I'm currently trying to plot on both sides of the X axis of a barplot, so I can easily compare the two different vectors at various Y points

I have most of it figured out, I just can't add the second vector somehow. I think the easiest way to make it more clear what I want is to show you the image below.

What I want is for cleanvector2 to be plotted "flipped" from the X axis down, so starting at 0 and expanding downwards. Preferably also with positive values on the Y axis.

image1

and code as currently used:

naam=" "
filenaam=paste(t, ".png", sep="")
bitmap(filenaam, type="png16m", res=300)
cleanvector1=c(1.29 1.93 1.71 1.35 1.54 0.73 1.41 1.52 1.43 1.09 0.96 0.87 2.29 1.50 0.67)
cleanvector2=c(1.29 1.93 1.71 1.35 1.54 0.73 1.41 1.52 1.43 1.09 0.96 0.87 2.29 1.50 0.67)
cleanvector2=cleanvector2*-1
barplot(rollapply(cleanvector1, 2,mean, by=1, fill=NA), main=naam, ylim=c(max(cleanvector1)*-1,max(cleanvector1)), xlab="200 basepair bins")
# barplot(rollapply(cleanvector2, 2,mean, by=1, fill=NA))
abline(h=1, col="darkred")
abline(h=-1, col="darkred")
axis(side=1)
dev.off()

Answer

Here's a minimal working example. Two things to note: cleanvector* in your code is missing commas, which makes it difficult for people to reproduce the results; you should copy and paste the output from e.g. dput(cleanvector1). Second, since rollapply comes (I assume) from the zoo package, the example should have loaded the package, or use zoo::rollapply.

To add the second vector to the barplot, use barplot(..., add = TRUE):

cleanvector1 <- c(1.29, 1.93, 1.71, 1.35, 1.54, 0.73, 1.41, 1.52, 1.43, 1.09, 
0.96, 0.87, 2.29, 1.5, 0.67)
cleanvector2 <- cleanvector1 * -1
barplot(zoo::rollapply(cleanvector1, 2, mean, fill = NA), 
        ylim=c(max(cleanvector1) * -1, max(cleanvector1)), 
        xlab="200 basepair bins")
barplot(zoo::rollapply(cleanvector2, 2, mean, fill = NA), 
        add = TRUE)
abline(h = 1, col = "darkred")
abline(h = -1, col = "darkred")