ggplot2:顶部图例键符号大小随图例键标签而变化 [英] ggplot2: Top legend key symbol size changes with legend key label

查看:105
本文介绍了ggplot2:顶部图例键符号大小随图例键标签而变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题

我想将情节的图例放在情节上方.我还想将图例键符号(彩色正方形)放置在图例键标签(图例文本)上方.不幸的是,当我这样做时,图例键符号会拉伸"以适合标签的大小.我以为ggplot2可以正常工作,但是如何手动覆盖此功能?

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 labels (legend text). Unfortunately, when I do this, the legend key symbol "stretches" to fit the size of the label. I imagine ggplot2 is working fine, but how could I manually override this feature?

如何在顶部使用长度可变的标签使图例键符号保持一致?

How do I keep a consistent legend key symbol across the top with labels of variable lengths?

可复制示例

(这不一定是一个最小的示例,以防万一我的实际代码结构(如coord_flipfill调用具有影响力)

(It's not necessarily a minimal example, just in case the structure of my actual code, like the coord_flip and fill calls, has an impact)

library(dplyr)
library(ggplot2)

dataFrame <- diamonds %>%
              group_by(color, cut) %>%
              summarise(count = n()) %>%
              group_by(color) %>%
              mutate(percent = count/sum(count),
                    pretty_label = paste0(round(percent*100, 1), "%")) %>%
              ungroup()

p <- ggplot(data = dataFrame, mapping = aes(x=color, y = percent, group = cut))+
      geom_bar(aes(fill = cut), stat = "identity", position = "fill")+
      geom_text(aes(label = pretty_label), position=position_fill(vjust=0.5), colour="white", stat = "identity")+
      coord_flip()+
      theme(legend.position="top")+
      guides(fill = guide_legend(label.position = "bottom", reverse = TRUE))

plot(p)

请注意,每个图例符号的大小如何不同,具体取决于标签的长度.

Notice how each of the legend symbols are different sizes, depending on the length of the label.

我已经尝试过的东西

我认为它与指南有关,但是我似乎无法正确地做到这一点.使用上面的图(p),我尝试了以下操作:

I imagine it has something to do with guides, but I can't seem to get it right. Using the plot above (p), I have tried the following and more:

  1. 此处来自此处:p + guides(colour = guide_legend(keywidth = .5, keyheight = .5))p + guides(colour = guide_legend(keywidth = unit(.5, "cm"), keyheight = unit(.5, "cm")))

    此处 :(尝试包装标签)p + guides(color = guide_legend(nrow = 2))

    From here: (Trying to wrap labels) p + guides(color = guide_legend(nrow = 2))

    我只是因为其他原因尝试了一些不太合乎逻辑的尝试.没有一个起作用.

    I've tried other, less "logical" attempts just because. None of which worked.

    最终想法

    我可能很难知道要搜索什么.如果您能够指出正确的方向,我总是愿意亲自解决问题.任何其他资源都值得欢迎.

    I could just be having a difficult time knowing what to search for. I am always open to figuring out the problem myself, if you are able to point me in the right direction. Any additional resources are more than welcome.

    先谢谢了!

    会话输出

    > sessionInfo()
    R version 3.5.1 (2018-07-02)
    Platform: x86_64-w64-mingw32/x64 (64-bit)
    Running under: Windows >= 8 x64 (build 9200)
    
    Matrix products: default
    
    locale:
    [1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252    LC_MONETARY=English_United States.1252
    [4] LC_NUMERIC=C                           LC_TIME=English_United States.1252    
    
    attached base packages:
    [1] stats     graphics  grDevices utils     datasets  methods   base     
    
    other attached packages:
    [1] bindrcpp_0.2.2 ggplot2_3.0.0  dplyr_0.7.6   
    
    loaded via a namespace (and not attached):
     [1] Rcpp_0.12.18      bindr_0.1.1       magrittr_1.5      tidyselect_0.2.4  munsell_0.5.0     colorspace_1.3-2  viridisLite_0.3.0
     [8] R6_2.2.2          rlang_0.2.1       plyr_1.8.4        tools_3.5.1       grid_3.5.1        gtable_0.2.0      withr_2.1.2      
    [15] yaml_2.1.19       lazyeval_0.2.1    assertthat_0.2.0  digest_0.6.17     tibble_1.4.2      purrr_0.2.5       glue_1.2.0       
    [22] labeling_0.3      compiler_3.5.1    pillar_1.2.3      scales_0.5.0      pkgconfig_2.0.1  
    

    推荐答案

    我不知道是否有一种方法可以独立于文本来控制图例颜色框的宽度(除了破解图例杂项之外).但是,如果在主题语句中添加legend.key.width=unit(1.5, "cm"),则所有颜色框都将扩展为相同的宽度(您可能需要向上或向下调整1.5来获得所需的框宽).

    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)
    

    您可以通过将Very Good放在两行上来节省一些空间:

    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)
    

    这篇关于ggplot2:顶部图例键符号大小随图例键标签而变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆