2016-05-03 42 views
3

我正在做一個有兩個不同映射的圖(「組」被映射到顏色和線型,「to」被映射到形狀)。我想將這兩個映射合併到一個圖例中,但無法在圖例中正確顯示。
這裏是我的嘗試:ggplot2:有兩個映射的一個圖例

set.seed(123) 
plotdata = cbind.data.frame(x = rep(1:5, times = 4), 
          y = rnorm(20), 
          from = rep(c("1","2"), each = 10), 
          to = rep(c("1","2"), times= 10)) 
plotdata = cbind.data.frame(plotdata, group = paste0(plotdata$from, "to", plotdata$to)) 

library(ggplot2) 

plot1 = ggplot(plotdata, aes(x = x, y = y, group = group, color = group, lty = group, shape = to)) + 
    geom_point() + geom_line() + theme_bw() + 
    scale_color_discrete(name = "", 
         breaks = c("1to1", "1to2", "2to1", "2to2"), 
         labels = c("1to1", "1to2", "2to1", "2to2")) + 
    scale_linetype_discrete(name = "", 
          breaks = c("1to1", "1to2", "2to1", "2to2"), 
          labels = c("1to1", "1to2", "2to1", "2to2")) + 
    scale_shape_manual(name = "", 
        values = c(1, 2, 1, 2), 
        breaks = c("1to1", "1to2", "2to1", "2to2"), 
        labels = c("1to1", "1to2", "2to1", "2to2")) 
print(plot1) 

plot

正如你可以在劇情看,我有一個傳說,但形狀始終是一個圓。
期望的行爲:在圖例中,圖例中的形狀在圓圈和金字塔之間交替變化。

我到目前爲止所嘗試的是手動指定形狀,但沒有幫助,因爲你可以看到上面。我也看着我的陰謀對象希望能夠操縱它,但無濟於事。

回答

5

你可以得到一個沒有override.aes的傳說。只需設置shape=group,並使用scale_shape_manual來設置重複的形狀值。在這種情況下,你並不需要映射到to任何東西,因爲它包含的信息是多餘的:

ggplot(plotdata, aes(x = x, y = y, group = group, color = group, lty = group, 
        shape = group)) + 
    geom_point() + geom_line() + theme_bw() + 
    scale_color_discrete(name = "") + 
    scale_linetype_discrete(name = "") + 
    scale_shape_manual(name = "", values=c(1,2,1,2)) 

enter image description here

3

This Q&A幫了我:你需要用「override.aes」明確指定的顏色圖例形狀:

plot1 = ggplot(plotdata, aes(x = x, y = y, group = group, color = group, lty = group, shape = to)) + 
    geom_point() + geom_line() + theme_bw() + 
    scale_color_discrete(name = "", 
         breaks = c("1to1", "1to2", "2to1", "2to2"), 
         labels = c("1to1", "1to2", "2to1", "2to2"), 
         guide = guide_legend(override.aes = list(shape = rep(c(1, 2), 2)))) + 
    scale_linetype_discrete(name = "", 
          breaks = c("1to1", "1to2", "2to1", "2to2"), 
          labels = c("1to1", "1to2", "2to1", "2to2")) + 
    scale_shape_discrete(guide = F) 
plot1 

enter image description here

不過請注意,你需要找出正確的塑造你自己。 A reference might come handy.

相關問題