基于ggplot2在两个不同位置的不同数据集的两个图例

时间:2017-06-20 18:19:55

标签: r 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")的线条和虚线?

我看过ThisThisThis,但我仍无法解决。

谢谢,

1 个答案:

答案 0 :(得分:1)

您可以先移动linetype内的aes,然后为其创建guide

然后,由于独立移动传说并不容易,我们可以使用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值,并且可能会使其units具有一致且良好的结果。