[R] 3D Gaussian with different colors
David Winsemius
dwinsemius at comcast.net
Wed Dec 26 20:37:11 CET 2012
On Dec 25, 2012, at 11:58 PM, Roberto wrote:
> I wrote, finding pieces of code in the web, a simple script to draw
> a 3D
> gaussian plot.
> For the next step, I need that the 2 gaussian distributions have
> different
> colors.
>
> Can someone help me to do this?
>
> fn <- function(x, y, scale, scale2)
> dnorm(x,mean=1,sd=scale)*dnorm(y,mean=-1,sd=scale) +
> dnorm(x,mean=2,sd=scale2)*dnorm(y,mean=1,sd=scale2)
>
> x <- seq(-4,4,len=40)
> y <- seq(-4,4,len=40)
> z <- outer(x, y, fn, scale = 1, scale2 = 0.5)
> nrz <- nrow(z)
> ncz <- ncol(z)
> jet.colors <- colorRampPalette( c("lightblue", "green", "darkgreen") )
> nbcol <- 100
> color <- jet.colors(nbcol)
> zfacet <- z[-1, -1] + z[-1, -ncz] + z[-nrz, -1] + z[-nrz, -ncz]
> # Recode facet z-values into color indices
> facetcol <- cut(zfacet, nbcol)
> persp(x,y,z, theta = 30, phi = 30, expand = 0.2, col =
> color[facetcol],
> ltheta = 120, shade = 0.75, ticktype = "detailed")
There really is no specific division since both distributions
contribute something at each point, so I took this to mean that you
wanted something that might arise in an effort to divide the plane
into two regions where their contributions were greatest. This effort
was done by eyeball:
persp(x,y,z, theta = 30, phi = 30, expand = 0.2, col = c("blue", "red")
[1+(row(z[-1,-1])+col(z[-1,-1]) <= 47)],
ltheta = 120, shade = 0.75, ticktype = "detailed")
Need to construct an index matrix to the color vector that matches the
dimensions of the facets which are one less than the dimensions of z
(adding 1 since R indices need to start at 1 and logical FALSE is 0) .
This constructs a matrix of conditions based on
David Winsemius, MD
Alameda, CA, USA
More information about the R-help
mailing list