3

I'm trying to compare two scalar fields and want to draw them in the same plot using contours labeling their values with directlabels. The thing is, I'm not able to use two direct labels in the same plot.

Example:

library(ggplot2)
library(data.table)
library(directlabels)
grid <- expand.grid(lon = seq(0, 360, by = 2), lat = seq(-90, 0, by = 2))
grid$z <- with(grid, cos(lat*pi/180))
grid$z2 <- with(grid, sin(lat*pi/180))
grid.long <- melt(grid, id.vars = c("lon", "lat"))

# Manually adding two geom_dl's
ggplot(grid, aes(lon, lat)) +
  geom_contour(aes(z = z), color = "black") +
  geom_contour(aes(z = z2), color = "red") +
  geom_dl(aes(z = z2, label = ..level..), stat = "contour", method = "top.pieces", color = "red") +
  geom_dl(aes(z = z, label = ..level..), stat = "contour", method = "top.pieces", color = "black")

Only one variable is labeled.

Another way:

ggplot(grid.long, aes(lon, lat)) +
  geom_contour(aes(z = value, color = variable)) +
  geom_dl(aes(z = value, label = ..level.., color = variable), 
          stat = "contour", method = "top.pieces")

Any solution?

Thanks!

Elio Campitelli
  • 1,408
  • 1
  • 10
  • 20

1 Answers1

2

One solution is to provide different method= argument for the second geom_dl() call.

ggplot(grid, aes(lon, lat)) +
      geom_contour(aes(z = z), color = "black") +
      geom_contour(aes(z = z2), color = "red") +
      geom_dl(aes(z = z2, label = ..level..), stat = "contour", method = "top.pieces", color = "red") +
      geom_dl(aes(z = z, label = ..level..), stat = "contour", method = "bottom.pieces", color = "black")

enter image description here

Didzis Elferts
  • 95,661
  • 14
  • 264
  • 201
  • I guess that's a somewhat workable workaround. Although I smell trouble with more complex datasets in which one of the two are not ideal and, of course, it can't be done for 3 variables. Thanks! – Elio Campitelli Nov 10 '16 at 15:23