gpt4 book ai didi

r - 如何将ggplot图标题居中

转载 作者:行者123 更新时间:2023-12-02 01:31:10 29 4
gpt4 key购买 nike

在 ggplot 中居中对齐绘图标题的“lege artis”方式 - plot.title = element_text(hjust = 0.5) - 将标题置于绘图区域的中心不包括轴标签

当轴标签很长时,这可能会变得很难看,例如《欢乐满人间》原声带中的歌曲与字符长度的关系图。

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)")

有没有办法将标题置于整个绘图区域的中心,即包括轴标签占据的区域?

最佳答案

解决该问题的一个简单方法是将以下内容添加到图中:

theme(plot.title.position = 'plot', 
plot.title = element_text(hjust = 0.5))

第一部分告诉ggplot使用整个绘图作为居中的引用,第二部分使标题居中。

关于r - 如何将ggplot图标题居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46287086/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com