ssp3nc3r
ssp3nc3r

Reputation: 3822

geom_contour: select/color only one of the contour lines

How can I make one contour line created by geom_contour a separate color than the others? For example, in the below code how can I keep all contour lines black except the one labeled 0.02, which I'd like to be a color other than used by the rest.

require(directlabels)
p <- ggplot(faithfuld, aes(eruptions, waiting)) + 
     geom_contour(aes(z = density, colour = ..level..))
p <- direct.label(p, list("bottom.pieces", cex = .6))

Upvotes: 1

Views: 2768

Answers (2)

ssp3nc3r
ssp3nc3r

Reputation: 3822

I ended up overlaying two geom_contour as the solution, one tied to the color = ..level.. so that direct.label would work, and the other highlighting a particular contour:

require(directlabels)
p <- ggplot(faithfuld, aes(eruptions, waiting)) + 
  geom_contour(aes(z = density, colour = ..level..)) +
  scale_color_continuous(low = "black", high = "black") +
  geom_contour(aes(z = density, colour = ..level..), breaks = .02, color = "red")
p <- direct.label(p, list("bottom.pieces", cex = .6))

Upvotes: 2

Brian
Brian

Reputation: 8275

ggplot(faithfuld, aes(eruptions, waiting)) + 
  geom_contour(aes(z = density, 
                   colour = factor(..level.. == 0.02, 
                                   levels = c(F, T), 
                                   labels = c("Others", "0.02"))),
               breaks = 0.005*0:10) + 
  scale_colour_manual(values = c("black", "red")) + 
  labs(colour = "Of interest:")

enter image description here

This is a fairly extensible way to do it. All the "FALSE" values for ..level.. == 0.02 will show as black, while the "TRUE" show as red. To get this to work properly, I needed to set the breaks to line up with exactly 0.02 (and other multiples of 0.05), which is what the breaks = does.

Upvotes: 3

Related Questions