Why the range of my contour plot is so small?

Viewed 66

I'm tried to contour plot a density of multiple normal distribution in R, my code is as follow

set.seed(123)
x<-seq(-20,20,by=0.1)
y<-seq(-20,20,by=0.1)
n=length(x)
zz<-matrix(0,n,n)
for(i in 1:n){
  for(j in 1:n){
  zz[i,j]=exp(-x[i]^2/10-y[j]^2/5-2*0.3*x[i]*y[j]/(50^0.5))
  }
}
contour(x,y,zz,nlevels =10)

And the plot is looks like enter image description here

My question is that why it the range looks so small, most of the area is blank. I want the contour plot cover wilder area like the range I set for xlim and ylim.

1 Answers

The levels determine the range to be plot, in your example the z values are very small as you move away from the centre:

barplot(colMeans(zz))

enter image description here

And if you look at the levels created by default:

pretty(range(zz), 20)
 [1] 0.00 0.05 0.10 0.15 0.20 0.25 0.30 0.35 0.40 0.45 0.50 0.55 0.60 0.65 0.70
[16] 0.75 0.80 0.85 0.90 0.95 1.00

I am not quite familiar with what you need to use this plot for, so hope the below makes sense.

To cover a wider area, you need to expand the levels to cover your lower values:

RN = quantile(zz,prob=c(0.5,1))
N = 10

contour(x,y,zz,nlevels=N,
levels=exp(pretty(log(RN), 10)))

enter image description here

Related