2017-06-20 25 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