Skip to content
Prev 275018 / 398506 Next

Scatterplot with the 3rd dimension = color?

AFAIK, you can't 'add' two ggplot2 graphs together; the problem in
this case is that the two color scales would clash. If you're willing
to discretize the z values, then you could pull it off. Here's an
example:

d <- data.frame(x = rnorm(100), y = rnorm(100), z = factor(1 +
(rnorm(100) > 0)))
d1 <- data.frame(x = rnorm(100), y = rnorm(100), z = factor(3 +
(rnorm(100) > 0)))
dd <- rbind(d, d1)

In each data frame, I'm assigning two factor levels depending on
whether z > 0 or not. The factor levels are 1, 2 in d and 3, 4 in d1;
when rbinded together, z has four distinct levels. Now call ggplot():

ggplot(dd, aes(x = x, y = y, colour = z)) + geom_point() +
   scale_colour_manual(values = c('1' = 'red', '2' = 'blue', '3' = 'green',
                                  '4' = 'yellow'))

This may be coarser than you like, so you could always use the cut()
function to discretize z in each data frame; you'll want to assign the
levels so that they are distinct in the combined data frame. Example:

d3 <- data.frame(x = rnorm(100), y = rnorm(100),
                 z = cut(rnorm(100), breaks = c(-Inf, -0.5, 0.5, Inf),
labels = 1:3))
d4 <- data.frame(x = rnorm(100), y = rnorm(100),
                 z = cut(rnorm(100), breaks = c(-Inf, -0.5, 0.5, Inf),
labels = 4:6))
dd2 <- rbind(d3, d4)

mycols <- c('red', 'maroon', 'blue', 'green', 'cyan', 'yellow')
ggplot(dd2, aes(x = x, y = y, colour = z)) + geom_point() +
   scale_colour_manual(breaks = levels(dd2$z),
                       values = mycols)

You can always use the labels = argument of scale_colour_manual() to
assign more evocative legend values, or equivalently, you can assign
the labels in the cut() function within d3 and d4 to those you want in
the legend and leave the plot code as is.

BTW, there is a dedicated ggplot2 list to which you can subscribe
through http://had.co.nz/ggplot2/ (look for the ggplot2 mailing list
near the top of the page). The list archives are accessible through
the same link.

HTH,
Dennis
On Thu, Oct 20, 2011 at 12:25 PM, Kerry <kbrownk at gmail.com> wrote: