使用direct.labels标记两个轮廓

时间:2016-11-08 23:35:24

标签: r ggplot2 direct-labels

我试图比较两个标量字段,并希望使用使用直接标记标记其值的轮廓在同一图中绘制它们。 问题是,我无法在同一个图中使用两个直接标签。

示例:

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")

只标记了一个变量。

另一种方式:

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")

任何解决方案?

谢谢!

1 个答案:

答案 0 :(得分:2)

一种解决方案是为第二次geom_dl()调用提供不同的method =参数。

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