将两个不同的图例放在ggplot2中的两列中

时间:2015-11-16 14:20:40

标签: r ggplot2

我有以下可重现的代码,它让我得到下面列出的情节:

require(ggplot2)
set.seed(123)
ChickWt <- data.frame(ChickWeight, AR = sample(c("p=0", "p=1", "hat(p)"), size = 578, replace = T))

exprvec <- expression( p==hat(p), p==0, p==1)
p1 <-  ggplot(ChickWt, aes(x=Time, y=weight, colour=Diet, Group = Chick, linetype = AR)) + geom_line()
p1 <- p1 + scale_linetype_manual(values=c(2,4,1), labels = exprvec,name="AR order") + theme_bw() + theme(legend.justification=c(1,-0.2), legend.position=c(0.3,0.2), legend.text=element_text(size=10), legend.title=element_text(size=10), axis.title.x=element_text(size=10), axis.title.y=element_text(size = 10), legend.key = element_blank(), legend.background = element_rect(color="black",size = 0.1)) + ylim(c(0,400)) + guides(fill=guide_legend(ncol=2)) 

enter image description here

但我希望在两个单独的专栏中关于Diet和AR订单的传说。我如何让它工作?显然,guides(fill=guide_legend(ncol=2))没有效果,也许是因为这是两个不同的传说。

感谢您的建议!

1 个答案:

答案 0 :(得分:2)

guides(fill=guide_legend(ncol=2))不起作用的原因是因为它仅引用fill - 图例而不引用linetype - 图例。您可以使用legend.box = "horizontal"

将图例放在彼此旁边
ggplot(ChickWt, aes(x=Time, y=weight, colour=Diet, Group = Chick, linetype = AR)) + 
  geom_line() + 
  scale_linetype_manual(values=c(2,4,1), labels = exprvec,name="AR order") + 
  theme_bw() + 
  theme(legend.justification=c(1,-0.2),
        legend.position=c(0.3,0.2),
        legend.text=element_text(size=10),
        legend.title=element_text(size=10),
        axis.title.x=element_text(size=10),
        axis.title.y=element_text(size = 10),
        legend.key = element_blank(),
        legend.background = element_rect(color="black",size = 0.1),
        legend.box = "horizontal") + 
  ylim(c(0,400))

给出:

enter image description here