首页 文章

如何集中ggplot情节 Headers

提问于
浏览
3

"lege artis"以中心方式证明ggplot中的绘图 Headers - plot.title = element_text(hjust = 0.5) - 将 Headers 置于绘图区域的中心,不包括轴标签 .

当轴标签非常长时,这可能会变得很难看,例如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)")

有没有办法将 Headers 集中在总的情节区域,即 . 包括轴标签占用的区域?

4 回答

  • 1

    或者,您可以使用 gridExtra::grid.arrangegrid::textGrob 来创建 Headers ,而无需在视觉上填充它 . 这基本上会创建一个单独的绘图对象与您的 Headers 并将其粘贴在顶部,不同于 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

    这里的优点是你知道你的 Headers 将真正居中,而不仅仅是靠近眼睛 .

  • 4

    添加空格到中心 Headers 的解决方案:

    在 Headers 后添加空格:

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

    对于像这样的输出:

    enter image description here

    不是完美的解决方案,但有效 .

  • 1

    我找到的简短解决方案:

    theme(plot.title = element_text(hjust = -0.2))
    

    hjust参数控制从左对齐到y轴的距离 . 负值将文本向左移动

  • 0

    如果你赶时间,在ggtitle中 Headers 之后添加空格也会有效......

    ggtitle("Mary Poppins                                 ") +
    

    输出:
    Center Mary Poppins Title

相关问题