[R] Why does smoothScatter clip when xlim and ylim increased?

Jennifer Lyon jennifer.s.lyon at gmail.com
Mon Feb 8 00:29:08 CET 2010

On Sat, Feb 6, 2010 at 6:15 AM, Duncan Murdoch <murdoch at stats.uwo.ca> wrote:
> On 06/02/2010 7:51 AM, Jennifer Lyon wrote:
>> Hi:
>> Is there a way to get smoothScatter to not clip when I increase the xlim
>> and
>> ylim parameters?
>> Consider the following example:
>> set.seed(17)
>> x1<-rnorm(100)
>> x2<-rnorm(100)
>> smoothScatter(x1,x2)
>> #Now if I increase xlim and ylim notice that the plot seems to be clipped
>> at
>> the former xlim, and ylim boundaries:
>> smoothScatter(x1,x2, xlim=c(-5,5), ylim=c(-5,5))
> If you follow the links on the help page, you'll see that smoothScatter uses
> bkde2D, which has a range.x argument to control the range of the smoothing.
>  The smoothScatter function never passes the xlim and ylim values to bkde2D,
> only to the plotting functions, presumably because the author expected you
> to use them to limit the range, not extend it.
> You can get the behaviour you want with specified xlim and ylim by modifying
> one line in smoothScatter:
> map <- grDevices:::.smoothScatterCalcDensity(x, nbin, bandwidth)
> should become
> map <- grDevices:::.smoothScatterCalcDensity(x, nbin, bandwidth, list(xlim,
> ylim))
> (You can use fix(smoothScatter) to edit your own local copy of smoothScatter
> and make this change.)
> However, this messes up the default plot, so a better patch would be needed
> to permanently fix this.
> Duncan Murdoch
Ah. A very helpful explanation. Further exploration led to the
realization that if I passed in par("usr") instead of xlim and ylim
that both the case I care about and the default case display without
clipping. Of course I discovered (very reasonably) that par("usr")
doesn't exist until plot() is called, so I ended up calling plot and
then modifying the image call with add=T. Along the lines of:
 plot(NA,NA, xlab = xlab, ylab = ylab, xlim = xlim, ylim = ylim, xaxs
= xaxs, yaxs = yaxs, type="n", ...)
map <- grDevices:::.smoothScatterCalcDensity(x, nbin, bandwidth,
image(xm, ym, z = dens, col = colramp(256), xlab = xlab,
 ylab = ylab, xlim = xlim, ylim = ylim, xaxs = xaxs, yaxs = yaxs,
add=T, ...)

This is somewhat wasteful, as bkde2D is computing densities at grid
points well away from where the data is located, so I'll just have to
increase the number of grid points.

Thank you for your help.


More information about the R-help mailing list