[R] combination of scatterplot and image graph

Jim Lemon bitwrit at ozemail.com.au
Sat Dec 25 09:26:48 CET 2004


bogdan romocea wrote:
> Dear R users,
>
> I'm interested in a combination of a scatterplot and an image graph.
> I have two large vectors. Because in the scatterplot some areas are
> sparsely and others densely populated, I want to see the points, and
> I also want their color to be changed based on their density (similar
> to a heat map). Is there a function that can do that?
>
This looked much like a function in the "plotrix" package, and I found it was 
quite easy to modify one of the functions to do what I think you want. Try 
installing "plotrix" and sourcing this function.

color.scale<-function(x,redrange,greenrange,bluerange){
 ncolors<-length(x)
 if(length(redrange) > 1) reds<-rescale(x,redrange)
 else reds<-rep(redrange,ncolors)
 if(length(greenrange) > 1) greens<-rescale(x,greenrange)
 else greens<-rep(greenrange,ncolors)
 if(length(bluerange) > 1) blues<-rescale(x,bluerange)
 else blues<-rep(bluerange,ncolors)
 colormatrix<-cbind(reds,greens,blues)
 colvec<-apply(colormatrix,1,rgb.to.hex,scale.up)
 return(colvec)
}

Then:

x<-rnorm(20)
y<-rnorm(20)
densities<-apply(as.matrix(dist(cbind(x,y))),mean))
plot(x,y,col=color.scale(densities,c(0,255),0,c(255,0))

I've made up the color endpoints, of course. This looks so useful that I will 
include it in the next version of plotrix.

Jim




More information about the R-help mailing list