将图例分成两列,同时保持形状覆盖

时间:2019-02-12 12:34:13

标签: r ggplot2 legend

我遇到一个ggplot问题。这是示例数据:

df <- data.frame(x = rep(1:5,5),
                 type2 = c(rep(letters[1:2],each = 10),rep("c",5)),
                 type1 = rep(LETTERS[1:5],each = 5), 
                 value = unlist(lapply(-2:2,function(a){rnorm(5,mean = a, sd = 1)})))

library(ggplot2)

plotcolor <- c( "#99d8c9","#2ca25f","#cbc9e2","#9e9ac8","#e34a33")
p <- ggplot(df,aes(x,value,color = type1,fill = type1,shape = type2))+
  geom_point(size = 5)+
  theme_light()+
  labs(title =  "",
       color = "Method",
       fill = "Method",
       shape = "")+
  geom_hline(yintercept = 0)+
  guides(colour = guide_legend(override.aes = list(shape =  c(21,21,24,24,22),
                                                   linetype = c(rep("blank",5)),
                                                   fill = plotcolor,
                                                   color = plotcolor)))+
  scale_shape(guide = FALSE)+
  scale_colour_manual(values = plotcolor)
p

给出 enter image description here

出于空间原因,现在我想将图例分成两列。我尝试过

p + guides(color=guide_legend(ncol=2))

但它删除了我图例中的override部分,只说明了一点:

enter image description here

p + guides(color=guide_legend(ncol=2),
           fill =guide_legend(ncol=2) ,
           shape = guide_legend(ncol=2))

也不起作用。有谁知道如何处理这个特定问题?

1 个答案:

答案 0 :(得分:3)

您可以在现有ncol中指定guide_legend(不要多次使用):

  guides(colour = guide_legend(override.aes = list(shape = c(24,24,22,22,21),
                                                   linetype = c(rep("blank",5)),
                                                   fill = plotcolor,
                                                   color = plotcolor),
                               ncol = 2))+

enter image description here