Skip to content

matching two plots

3 messages · Rui Cardoso, Romain Francois, Marc Schwartz (via MN)

#
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
#
Le 19.10.2005 19:27, Rui Cardoso a ??crit :
Hello,

The problem is barplot. To see that :

R> (barplot(dpois(0:45,20),xlim=c(0,45),names=0:45))
R> axis(3)

Try something like :

R> plot(0:45, dpois(0:45,20), type="h", lwd=4, col="gray")
R> curve(dnorm(x,20,sqrt(20)),from=0,to=45,add=T)

Romain
#
On Wed, 2005-10-19 at 18:27 +0100, Rui Cardoso wrote:
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