2016-11-08 49 views
1

我試圖比較兩個標量字段,並且想要使用等值線將它們的值用直接標籤標記在同一個繪圖中。 問題是,我無法在同一個地塊中使用兩個直接標籤。使用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

一個解決方案是爲第二個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

+0

我想這是一個有點可行的解決方法。儘管我對更復雜的數據集感到困惑,但其中兩個數據集中的一個並不理想,當然,對於3個變量卻無法完成。 謝謝! –