[R] trying to plot function using curve

Uwe Ligges ligges at statistik.uni-dortmund.de
Wed Apr 16 09:00:49 CEST 2003

Faheem Mitha wrote:
> Dear People,
> I hope someone can help me with this. I have a function (density) which I
> am trying to plot using curve. I am calling mg.hist(3,2,1), and getting
> the following errors.
> Error in xy.coords(x, y, xlabel, ylabel, log) :
> 	x and y lengths differ
> In addition: There were 50 or more warnings (use warnings() to see the
> first 50)
> 1: longer object length
> 	is not a multiple of shorter object length in: x * y
> and more of the same.
> I'm not sure where the problem is. I assume it has something to do with me
> incorrectly vectorising my functions(s). However, it seems to me that
> density() is vectorised.
> By the way, if anyone would like to suggest a better way to plot density
> plots, please let me know. curve() was suggested to me, which is why I am
> using it. Actually, I want to plot a density curve on top of a histogram.
> I was thinking of trying to use trellis graphics for this, but I'm not
> sure it has any advantages for this purpose.
>                                                      Faheem.

[Code snipped]

Some comments:
- Indeed, I'd use curve(), but of course you can do it "manually"
   with plot(.., type="l") as well.
- In your usage of curve() you rely heavily on R's scoping rules
   (should work, from my point of view, but always looks a bit
       densityfn <- function(x) density(x,theta,pos,len) # No defaults!
       # Now curve() grabs theta, pos, len from any environment before:
- I would not use that many functions as in your code,
   but that's a matter of taste.
- It's not that amusing to debug all that code - try it yourself,
   R has many nice debugging tools (debug(), browser(), etc.).

Uwe Ligges

More information about the R-help mailing list