2017-10-07 131 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