2017-06-20 22 views
0

我有以下的小例子:兩種傳說基於不同的數據集與GGPLOT2兩個不同的位置

df1 <- data.frame(x=1:10, y=rnorm(10)) 
df2 <- data.frame(x=11:20, y=rnorm(10)) 
df3 <- data.frame(x=1:10, y=rnorm(10,3,1)) 
df4 <- data.frame(x=11:20, y=rnorm(10,3,1)) 

ggplot() + 
    geom_line(data = df1, aes(x = x, y = y, color = "red")) + 
    geom_line(data = df2, aes(x = x, y = y, color = "red"), linetype="dashed") + 
    geom_line(data = df3, aes(x = x, y = y, color = "blue")) + 
    geom_line(data = df4, aes(x = x, y = y, color = "blue"), linetype="dashed") + 
    theme_bw() + 
    theme(legend.title=element_blank()) + 
    theme(legend.text=element_text(size=12)) + 
    theme(legend.position = c(.9,.89)) 

我怎麼能有另一個傳奇在圖形的線左上角和虛線與標籤線c("Fitted values", Predicted Values")

我讀This,ThisThis,但我仍然無法解決它。

感謝,

回答

1

你可以先移動了linetypeaes內,然後爲它創建一個guide

然後,圍繞傳說移動indipendetly是不容易的,我們可以用legend.*主題的設置玩得到你想要的東西:

library(ggplot2) 

ggplot() + 
    geom_line(data = df1, aes(x = x, y = y, 
          color = "red", 
          linetype = "Fitted values")) + 
    geom_line(data = df2, aes(x = x, y = y, 
          color = "red", 
          linetype = "Predicted Values")) + 
    geom_line(data = df3, aes(x = x, y = y, 
          color = "blue", 
          linetype = "Fitted values")) + 
    geom_line(data = df4, aes(x = x, y = y, 
          color = "blue", 
          linetype = "Predicted Values")) + 
    scale_linetype_manual(values = c('solid', 'dashed')) + 
    scale_colour_manual(values = c('red', 'blue')) + 
    theme_bw() + 
    theme(legend.title=element_blank(), 
     legend.text=element_text(size=12), 
     legend.position = c(.5,.89), 
     legend.box = 'horizontal', 
     legend.margin = margin(r = 125, l = 125), 
     legend.background = element_rect(fill = NA)) 

你將不得不與margin值打,並有可能使其arg units具有一致和良好的結果。

+0

非常感謝。它適用於我,它比其他人在[鏈接]中提到的解決方案容易得多(https://stackoverflow.com/questions/13143894/how-do-i-position-two-legends-independently-in- ggplot)。繼續做好:) – Alirsd