0

Say that I want to produce a barplot for the following data (counts):

 A     B     C     D 
3030  3049  3104  3018 

But I also want to put a line plot overlapying the bar plot of the following data(lg):

A 2.485294117647059
B 2.465160980297934
C 2.414123006833713
D 2.457267020762916

This has been my code so far:

b<-barplot(counts,col='black',border=FALSE,axes=FALSE,cex.names = 0.75)

left.axis.pos<-c(quantile(counts))
axis(2,at=left.axis.pos,labels=left.axis.pos,las=2,cex.axis=0.75)
mtext("Number",side=2,line=3,cex=1)

right.axis.ticks<-c(quantile(as.numeric(lg[,2])))
axis(4,at=right.axis.ticks,labels = right.axis.ticks,las=2,cex.axis=0.75)
mtext("ratio",side=4,line=2,cex=1)

lines(lg[,1],as.numeric(lg[,2]), col='grey',lwd=2)
dev.off()

However, the y-axis is either too far up (on left) or too far down (on right).

enter image description here

The original PDF is also available on Dropbox.

nograpes
  • 18,623
  • 1
  • 44
  • 67
user2726449
  • 607
  • 4
  • 11
  • 23

2 Answers2

2

It is doing exactly what you are telling it to. Have you looked at the values of left.axis.pos and right.axis.ticks?

It is very unusual to use quantile to choose tick positions, it is giving values corresponding to the minimum, maximum, and the 3 quartiles (since you are using the default arguments). More common is to use values that span the entire range of the plot (include 0 for the barplot) and are equally spaced. Look at the pretty function and possibly range or max.

Greg Snow
  • 48,497
  • 6
  • 83
  • 110
  • Thanks for the suggestion. I've been doing a lot of graphing with factors using ggplot2 so going back to basics takes a bit of getting used to. – user2726449 Apr 28 '14 at 01:54
2

You probably have to play with settings a little to combine things as intended:

oldmar <- par("mar")
par(mar=c(5.1,4.1,4.1,3.1))

b <- barplot(counts,col='black',border=FALSE,axes=FALSE,cex.names = 0.75)
axis(2,cex.axis=0.75, las=2)
mtext("Number",side=2,line=3,cex=1)

par(new=TRUE)
barplot(rep(NA,4),ylim=range(as.numeric(lg[,2])),axes=FALSE)
axis(4, cex.axis=0.75, las=2)
lines(b, as.numeric(lg[,2]),col="grey",lwd=2)

box()
par(mar=oldmar)
par(new=FALSE)

enter image description here

thelatemail
  • 91,185
  • 12
  • 128
  • 188