 # 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))
#
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))))
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))
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