2017-10-07 62 views
0

默认情况下,图例框/键与图例标题的左侧对齐。由于我有很长的传奇头衔,我想将它与中心对齐。我试过themeguide_legend没有任何成功。任何建议,将不胜感激。谢谢!如何将图例框对齐ggplot2中的图例标题中间?

  • 数据

    df <- structure(list(Flow = c(0.992762, 0.802408, 0.9826, 0.754863, 
         0.174542, 0.056777), Coef = c(0.62, 0.49, 0.38, 0.59, 0.25, 0.67 
         ), VeryLongLegendTitle = c(4.47680710313542, 18.8500193246859, 
         5.82742564783431, 23.3217237977105, 13.0155332302148, 88.4960885143824 
         )), class = "data.frame", row.names = c(NA, -6L), .Names = c("Flow", 
         "Coef", "VeryLongLegendTitle")) 
    
  • 代码

    library(ggplot2) 
    p1 <- ggplot(df, aes(x = Flow, y = Coef, color = VeryLongLegendTitle)) + 
        xlab(NULL) + scale_x_continuous(limits = c(0.0, 1.0), breaks = c(0.25, 0.75)) + 
        geom_point(size = 2, alpha = 0.8) + 
        theme_bw(base_size = 14) + 
        theme(axis.text.x = element_text(angle = 0, vjust = 0.5)) 
    p1 
    
    p1 + theme(legend.title.align = 0.5) 
    p1 + theme(legend.title = element_text(hjust = 0.5)) 
    p1 + guides(color = guide_legend(title.hjust = 0.5)) 
    
  • 情节 enter image description here

+2

你会考虑一个水平的传说吗?看起来像试图垂直这将是不必要的复杂,更不用说浪费图表空间。 – www

+0

@www:我会,如果我只需要一个情节。然而,我的最终情节由大约16个(4x4)个人小块组成。剧情的每一行都有不同的传说。把传说放在正确的位置是我唯一的选择。谢谢! – Tung

回答

1

我同意@www,但你可以试试p1 + guides(color = guide_legend(keywidth = 5, keyheight = 2))。它会产生这样的事情: enter image description here

看看Legend guide也是不错的。

+0

感谢您的链接!我已经看过那个和['theme'](http://ggplot2.tidyverse.org/reference/theme.html)了。奇怪的是'ggplot2'中有这样的选项 – Tung

+0

不客气!你也可以[把标题放在两行](https://stackoverflow.com/questions/42154922/align-two-line-legend-title-to-the-left-with-expression)。 – ANG

+0

再次感谢!不幸的是,这个传说只是一个很长的单词 – Tung