0
votes

I'm working on a contour plot where I'm using both size and colour of the contour lines to depict relevant information. Here's an equivalent minimal example based on the documentation for stat_contour:

require(ggplot2)

volcano3d <- melt(volcano) 
names(volcano3d) <- c("x", "y", "z") 
v <- ggplot(volcano3d, aes(x, y, z = z)) 
TransBinary = Trans$new("TransBinary",f=function(x){ifelse(x>124,1,0)})
# under 2.15: TransBinary = trans_new("TransBinary",transform=function(x){ifelse(x>0,1,0)},inverse=FALSE)

v + 
  stat_contour(aes(colour=..level..,size=..level..)) + 
  scale_colour_gradient(high="black",low="grey",trans=TransBinary,legend=FALSE) + 
  scale_size("size")

This generates exactly what I'm looking for: a contour plot in which higher values of z are shown as bigger lines and there is a threshold at some value of z (here the median) below which the lines are coloured grey, and above which they're coloured black.

The only wrinkle is that the resulting legend shows the line sizes, but all the lines in the legend are black (unsurprisingly).

Is there a way to get ggplot to plot the lines as grey / black in the legend as well?

1
I do not know whether something in the answer to the following similar question might help you: stackoverflow.com/questions/6050510/…Mark Miller
Unfortunately at the moment this is impossible with an elegant way.kohske

1 Answers

2
votes

You can use arbitral palette, so what you need is:

th <- rescale(c(124, volcano3d$z))[1]
sc <- continuous_scale("colour", "", palette = function(x) {ifelse(x > th, "black", "grey")})

v + 
 stat_contour(aes(colour=..level..,size=..level..)) + 
 sc+
 scale_size("size") + labs(colour = "size")

enter image description here

note that this only works with ggplot2 0.9, probably.