ggplot2: Divide Legend into Two Columns, Each with Its Own Title

前端 未结 6 623
谎友^
谎友^ 2020-11-27 16:55

I have these factors

require(ggplot2)
names(table(diamonds$cut))
# [1] \"Fair\"      \"Good\"      \"Very Good\" \"Premium\"   \"Ideal\" 

w

6条回答
  •  情歌与酒
    2020-11-27 17:40

    Following the idea of @eipi10, you can add the name of the titles as labels, with white values:

    diamonds$cut = factor(diamonds$cut, levels=c("Title 1           ","Fair","Good"," ","Title 2","Very Good",
                                             "Premium","Ideal"))
    
    ggplot(diamonds, aes(color, fill=cut)) + geom_bar() + 
       scale_fill_manual(values=c("white",hcl(seq(15,325,length.out=5), 100, 65)[1:2], 
                                  "white","white",
                                  hcl(seq(15,325,length.out=5), 100, 65)[3:5]),
                         drop=FALSE) +
       guides(fill=guide_legend(ncol=2)) +
       theme(legend.position="bottom", 
             legend.key = element_rect(fill=NA),
             legend.title=element_blank())
    

    I introduce some white spaces after "Title 1 " to separate the columns and improve the design, but there might be an option to increase the space.

    The only problem is that I have no idea how to change the format of the "title" labels (I tried bquote or expression but it didn't work).

    _____________________________________________________________

    Depending on the graph you are attempting, a right alignment of the legend might be a better alternative, and this trick looks better (IMHO). It separates the legend into two, and uses the space better. All you have to do is change the ncol back to 1, and "bottom" (legend.position) to "right":

    diamonds$cut = factor(diamonds$cut, levels=c("Title 1","Fair","Good"," ","Title 2","Very Good","Premium","Ideal"))
    
    
    ggplot(diamonds, aes(color, fill=cut)) + geom_bar() + 
       scale_fill_manual(values=c("white",hcl(seq(15,325,length.out=5), 100, 65)[1:2], 
                                  "white","white",
                                  hcl(seq(15,325,length.out=5), 100, 65)[3:5]),
                         drop=FALSE) +
       guides(fill=guide_legend(ncol=1)) +
       theme(legend.position="bottom", 
             legend.key = element_rect(fill=NA),
             legend.title=element_blank())
    

    In this case, it might make sense to leave the title in this version, by removing legend.title=element_blank()

提交回复
热议问题