1
votes

I have to plot some plot(x,y) scatters, but i would like the points to be color coded based on the value of a continuous variable z.

I would like a temperature palette (from dark blue to bright red). I tried with Rcolorbrewer however the the RdBu palette (which resembles the temperature palette) uses white for the middle values which looks very bad.

I would also like to plot a legend explaining the color coding with a sample of colors and corresponding values.

Any ideas if this can be performed easily in R? No ggplot please!

Season greetings to everybody

3
no ggplot...hmm what about lattice ?dickoa
Can give it a try but, I would appreciate an r-base solution.ECII

3 Answers

5
votes

Building off of @BenBolker's answer, you can do the legend if you take a peek at the code for filled.contour. I hacked that function apart to look like this:

    scatter.fill <- function (x, y, z, 
                              nlevels = 20, plot.title, plot.axes, 
                              key.title, key.axes, asp = NA, xaxs = "i", 
                              yaxs = "i", las = 1, 
                              axes = TRUE, frame.plot = axes, ...) 
    {
        mar.orig <- (par.orig <- par(c("mar", "las", "mfrow")))$mar
        on.exit(par(par.orig))
        w <- (3 + mar.orig[2L]) * par("csi") * 2.54
        layout(matrix(c(2, 1), ncol = 2L), widths = c(1, lcm(w)))
        par(las = las)
        mar <- mar.orig
        mar[4L] <- mar[2L]
        mar[2L] <- 1
        par(mar = mar)

        #Some simplified level/color picking
        levels <- seq(min(z),max(z),length.out = nlevels)
  col <- colorRampPalette(c("blue","red"))(nlevels)[rank(z)]

        plot.new()
        plot.window(xlim = c(0, 1), ylim = range(levels), xaxs = "i", 
            yaxs = "i")
  rect(0, levels[-length(levels)], 1, levels[-1L], col = colorRampPalette(c("blue","red"))(nlevels)
        if (missing(key.axes)) {
            if (axes) 
                axis(4)
        }
        else key.axes
        box()
        if (!missing(key.title)) 
            key.title
        mar <- mar.orig
        mar[4L] <- 1
        par(mar = mar)

        #Simplified scatter plot construction
        plot(x,y,type = "n")
        points(x,y,col = col,...)

        if (missing(plot.axes)) {
            if (axes) {
                title(main = "", xlab = "", ylab = "")
                Axis(x, side = 1)
                Axis(y, side = 2)
            }
        }
        else plot.axes
        if (frame.plot) 
            box()
        if (missing(plot.title)) 
            title(...)
        else plot.title
        invisible()
    }

And then applying the code from Ben's example we get this:

x <- runif(40)
y <- runif(40)
z <- runif(40)
scatter.fill(x,y,z,nlevels = 40,pch = 20)

which produces a plot like this:

enter image description here

Fair warning, I really did just hack apart the code for filled.contour. You will likely want to inspect the remaining code and remove unused bits, or fix parts that I rendered non-functional.

5
votes

Here some home-made code to achieve it with default packages (base, graphics, grDevices) :

# Some data
x <- 1:1000
y <- rnorm(1000)
z <- 1:1000

# colorRamp produces custom palettes, but needs values between 0 and 1
colorFunction <- colorRamp(c("darkblue", "black", "red"))
zScaled <- (z - min(z)) / (max(z) - min(z))

# Apply colorRamp and switch to hexadecimal representation
zMatrix <- colorFunction(zScaled)
zColors <- rgb(zMatrix, maxColorValue=255)

# Let's plot
plot(x=x, y=y, col=zColors, pch="+")

For StanLe, here is the corresponding legend (to be added by layout or something similar) :

# Resolution of the legend
n <- 10

# colorRampPalette produces colors in the same way than colorRamp
plot(x=NA, y=NA, xlim=c(0,n), ylim=0:1, xaxt="n", yaxt="n", xlab="z", ylab="")
pal <- colorRampPalette(c("darkblue", "black", "red"))(n)
rect(xleft=0:(n-1), xright=1:n, ybottom=0, ytop=1, col=pal)

# Custom axis ticks (consider pretty() for an automated generation)
lab <- c(1, 500, 1000)
at <- (lab - min(z)) / (max(z) - min(z)) * n
axis(side=1, at=at, labels=lab)
2
votes

This is a reasonable solution -- I used blue rather than dark blue for the starting point, but you can check out ?rgb etc. to adjust the color to your liking.

nbrk <- 30
x <- runif(20)
y <- runif(20)
cc <- colorRampPalette(c("blue","red"))(nbrk)
z <- runif(20)
plot(x,y,col=cc[cut(z,nbrk)],pch=16)