benedict
benedict

Reputation: 3

R: combine barplot and lineplot; line-dots and ticks on the x-axis not aligned to barplot

I want to plot two outcomes of a behavioral psychological experiment in one plot: performance (as measured by % of correct answers) through a marplot and reaction times (in ms) through a line plot.

I've figured everything out except one thing: the ticks on the x-axis and the dots in the line plot don't align with the center of the bars. Someone suggested to save the barplot as an object and then use "at=" which works for the ticks on the x-axis but not for the dots in the line plot. I also wasn't able to make it work by using the "lines" function since the scales are different (.7-1.0 on the left for the barplot and 400-900 on the right for the line plot).

par(mar=c(6, 4, 4, 4))
m<-barplot(c(0.87,0.83,0.79),ylim=c(0.7,1),xpd=FALSE,ylab="% correct")
axis(1,at=m,labels=c("cond. A", "cond. B", "cond. C"))
par(new=T)
plot(c(720, 800, 830), pch=15, ,ylim=c(400,900), xlab="", ylab="",      
      axes=F, type="b")
mtext("reaction time [ms]",side=4,line=2.5)
axis(4, ylim=c(400,900))

Thank you for any kind of help

Upvotes: 0

Views: 1296

Answers (1)

mathematical.coffee
mathematical.coffee

Reputation: 56915

On your second plot, set the xlims equal to those of the barplot. Use par('usr') to get the current limits (vector of length 4; xmin, xmax, ymin, ymax). Then when you plot the line, you can use m as the x location and it will line up because your xlims also line up.

par(mar=c(6, 4, 4, 4))
m<-barplot(c(0.87,0.83,0.79),ylim=c(0.7,1),xpd=FALSE,ylab="% correct")
axis(1,at=m,labels=c("cond. A", "cond. B", "cond. C"))
xlims <- par('usr')[1:2] # <-- get xlims
par(new=T)
plot(m, c(720, 800, 830), # <-- supply x coords
     pch=15, ,ylim=c(400,900), xlab="", ylab="",      
      axes=F, type="b", xlim=xlims) # <-- supply xlims
mtext("reaction time [ms]",side=4,line=2.5)
axis(4, ylim=c(400,900))

Upvotes: 1

Related Questions