Adjusting location of the points in barplot

When I tried to add lines to my graph, I became confused of how to get correct index to draw the line so that the points can be located right in the middle of the bar,below are the graph and the code I used to plot it. I wonder how to adjust the codes to make the positioning of the points better.

cupbp<-read.xlsx("Go.xlsx",sheet=2)
 

cupbp2<-subset(cupbp,PValue<0.05)
cupbp2$P.value<-log(cupbp2$PValue,base=2)
cupbp2$P.value<-abs(cupbp2$P.value)
cupbp2$bp<-substr(cupbp2$Term,12,nchar(cupbp2$Term))  
opar<-par(no.readonly=T)
#
par(mar=c(5,25,7,10)+0.1) 
par(cex.axis=0.6)


#This part is used to plot the bars
mybar<-barplot(height=cupbp2$P.value,names=cupbp2$bp,horiz=TRUE,las=1,xaxt="n",col="red",xlab="-log2 P value",xlim=c(0,ceiling(max(cupbp2$P.value))))
title("control vs AD up Bioprocess",line=4,adj=0.5)
axis(side=1,at=axTicks(1))
par(new=T)

#This part is used to plot the lines
plot(cupbp2$Count,mybar,type="o",pch=19,lwd=2,col="yellow",cex=1.2,ann=F,xaxt="n",yaxt="n",xlab="Gene number",)
#axis(side=3,at=c(0,pretty(max(Count),n=4)))
axis(side=3,at=axTicks(3))
mtext("Gene number",3,line=2)
par(opar)

I can get the points to line up with the bars by spreading the ylim of the second plot a little beyond the limits of 1 and 20 that it would have judging from the data. Unfortunately, I do not know a formula for doing this, I just try different values. Obviously, this is not an elegant solution.

opar<-par(no.readonly=T)

DF <- data.frame(A = LETTERS[1:20], B = seq(1.5, 20.5), C = 1:20)

par(mar=c(5,5,7,10)+0.1)
par(cex.axis=0.6)
mybar <- barplot(height = DF$B, names = DF$A,horiz=TRUE, las=1, xaxt="n", col="red", xlab="A",
        xlim = c(0,21))
title("control vs AD up Bioprocess",line=4,adj=0.5)
axis(side=1,at=1:21)
par(new=T)

plot(DF$C, DF$A, type="o", pch=19, lwd=2, col="yellow", cex=1.2, ann=F,
     xaxt="n", yaxt="n", xlab="Gene number", ylim = c(0.6, 20.4))
#axis(side=3,at=c(0,pretty(max(Count),n=4)))
axis(side=3,at=1:20)
mtext("Gene number",3,line=2)

par(opar)

Created on 2019-09-23 by the reprex package (v0.2.1)

1 Like

Thanks for your reply,
Barplot function provided the midpoint value, stored in "mybar" in my example,
however, plot function was not suitable to plot the lines, for a reason I don't quite understand right now, changing plot(count, mybar) to lines(count, mybar) solves the problem of the points location, but this time the axis of the graph goes wrong. Maybe using lines() will cause R to consider the second graph not a new graph, so the axis was contained as the original one. See this modified example, in which the gene number axis should be 0 to 7, but it was kept as 0 to 14 as the original one.

I wonder why plot function didn't work as expected and how to fix the code based on this.
Thanks for your response, it gave me many inspirations.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.