2017-09-18 67 views
1

「lege artis」以居中證明陰謀標題的方式 - ggplot - plot.title = element_text(hjust = 0.5) - 居中標題在陰謀區域排除軸標籤如何居中ggplot陰謀標題

當軸標籤非常長時,如Mary Poppins Soundtrack中的這首歌曲曲線與其字符長度相比,這會變得很難看。

length of songs in Mary Poppins Soundrack

library(tidyverse) 

mary_poppins <- data_frame(song = c("Overture", "Sister Suffragette", "The Life I Lead", "The Perfect Nanny", "A Spoonful of Sugar", "Pavement Artist", "Jolly Holiday", "Supercalifragilisticexpialidocious", "Stay Awake", "I Love to Laugh", "A British Bank", "Feed the Birds ", "Fidelity Fiduciary Bank", "Chim Chim Cher-ee", "Step in Time", "A Man Has Dreams", "Let's Go Fly a Kite" 
)) 

mary_poppins <- mary_poppins %>% 
    mutate(len = nchar(song)) 

ggplot(data = mary_poppins, aes(x = reorder(song, len), y = len)) + 
    geom_col(fill = "firebrick") + 
    coord_flip() + 
    theme_light() + 
    theme(axis.title.y = element_blank(), 
     axis.text = element_text(size = rel(1.5)), 
     plot.title = element_text(size = rel(2.5), face = "bold", hjust = 0.5, 
            margin = margin(t = 10, b = 20, unit = "pt"))) + 
    ggtitle("Mary Poppins") + 
    ylab("Lenght of title (characters)") 

有沒有辦法在總用地面積,即居中標題。包括軸標籤佔用的區域?

回答

4

或者,您可以使用gridExtra::grid.arrange和​​來創建標題,而不需要直觀地填充標題。這基本上會爲您的標題創建一個單獨的繪圖對象,並將其粘貼在頂部,與您的ggplot調用的內容無關。

首先將您的整個ggplot調用存儲爲變量,例如, p1

grid.arrange(textGrob("Mary Poppins", 
       gp = gpar(fontsize = 2.5*11, fontface = "bold")), 
      p1, 
      heights = c(0.1, 1)) 

你有你的theme()設置轉換爲gpar()theme_light的基本大小是11,這是2.5 * 11的來源(和您的rel(2.5)的2.5)。

enter image description here

這裏的好處是,你知道你的標題纔會真正中心,不只是用眼睛足夠接近。

+0

謝謝 - 這確實是一個比填充空間更簡潔的解決方案! –

1

解決方案加入白色空間中心標題:

的冠軍後添加空格:

ggtitle(paste0("Mary Poppins", paste0(rep("", 30), collapse = " "))) 

對於輸出是這樣的:

enter image description here

不完美的解決方案,但作品。