[R] matching two plots

Marc Schwartz (via MN) mschwartz at mn.rr.com
Wed Oct 19 22:16:34 CEST 2005


On Wed, 2005-10-19 at 18:27 +0100, Rui Cardoso wrote:
> Hi,
> 
> I have a problem about graphics. I would like to plot two graphs: a barplot 
> and curve. Here is the code:
> 
>  > barplot(dpois(0:45,20),xlim=c(0,45),names=0:45)
>  > curve(dnorm(x,20,sqrt(20)),from=0,to=45,add=T)
> 
> Both graphs are drawn in the same figure, however the scale in both graphs 
> dooes not match. For some reason the second plot is shifted to left. I 
> think there is a problem concerning the axis scale.
> 
> Thanks a lot.
> 
> Rui


This came up this past summer and Gabor and I had a couple of different
approaches to the solution. You can see the posts here:

http://finzi.psych.upenn.edu/R/Rhelp02a/archive/57431.html

and

http://finzi.psych.upenn.edu/R/Rhelp02a/archive/57432.html


Using my approach with barplot(), what you need to do is to set the
'space' argument to 0 so that there is no space between the bars. This
will then place the bar centers at increments of 0.5, in your case
seq(0.5, 45.5, 5).

Knowing this, you can then adjust the x axis position in curve() by +0.5
to coincide with the bars. So you end up with this:

barplot(dpois(0:45, 20), names = 0:45, space = 0, ylim = c(0, .1))
curve(dnorm(x, 20 + 0.5, sqrt(20)), add = TRUE)

HTH,

Marc Schwartz




More information about the R-help mailing list