ggplot2: Top legend key symbol size changes with legend key label

后端 未结 1 677
-上瘾入骨i
-上瘾入骨i 2021-01-13 10:30

The Problem

I want to place the legend of my plot above the plot. I also want to place the legend key symbol (colored squares) above the legend key

相关标签:
1条回答
  • 2021-01-13 10:59

    I don't know if there's a way to control the width of the legend color boxes separately from the text (other than hacking the legend grobs). However, if you add legend.key.width=unit(1.5, "cm") in your theme statement, all of the color boxes will be expanded to the same width (you may have to tweak the 1.5 up or down a bit to get the desired box widths).

    library(scales)
    
    ggplot(dataFrame, aes(x=color, y = percent))+
      geom_bar(aes(fill = cut), stat = "identity") +
      geom_text(aes(label = pretty_label), position=position_fill(vjust=0.5), 
                colour="white", size=3)+
      coord_flip()+
      theme(legend.position="top",
            legend.key.width=unit(1.5, "cm"))+
      guides(fill = guide_legend(label.position = "bottom", reverse = TRUE)) +
      scale_y_continuous(labels=percent)
    

    You can save a little space by putting Very Good on two lines:

    library(forcats)
    
    ggplot(dataFrame, aes(x=color, y = percent, fill = fct_recode(cut, "Very\nGood"="Very Good")))+
      geom_bar(stat = "identity") +
      geom_text(aes(label = pretty_label), position=position_fill(vjust=0.5), 
                colour="white", size=3)+
      coord_flip()+
      theme(legend.position="top",
            legend.key.width=unit(1.2, "cm"))+
      guides(fill = guide_legend(label.position = "bottom", reverse = TRUE)) +
      labs(fill="Cut") +
      scale_y_continuous(labels=percent)
    

    0 讨论(0)
提交回复
热议问题