[R] two graphs in one figure?

Jim Lemon jim at bitwrit.com.au
Fri Apr 11 10:45:14 CEST 2008


Anne-Katrin Link wrote:
> Dear all,
> 
> how can I plot a line graph and a bar graph in one single figure? I tried 
> to combine "barplot" and "plot". Even though they both have the same 
> x-values (1 to 55),  it just doesnt look as if they match in their scale 
> (the barplot is much wider than the "plot"....even though I tried to put 
> limits on the x-axis).
> Here is an example of what I did:
> 
> barplot(y, xaxt="n",yaxt="n",ylim=c(-1,45), xlim=c(1,55))
> ...
> par(new=TRUE)
> plot(x, ynew, lty=2, type="l", ylim=c(0,15), xlim=c(1,55))
> 
> Another question: how can I make sure that the "0"-values from the barchart 
> are displayed as well?
> 
Hi Anne-Katrin,
This can be tricky, particularly getting the line plot positioned nicely 
relative to the bars. The barp function in plotrix may be useful, as it 
centers the bars on integer values, thereby lining up with the default 
integer x values when none are specified. Try:

library(plotrix)
par(mar=c(5,4,4,4))
barp(y,width=0.5,ylim=c(-1,65),...)
lines(ynew+45,col="red")
axis(4,at=c(40,50,60),labels=c(0,10,20),col="red")

This puts your line plot over the bars with a separate axis. I'm not 
sure exactly what you mean by the "0" values (x or y axis?), but it can 
be done.

Jim



More information about the R-help mailing list