r - 如何将标题与换行符左对齐?
问题描述
我正在 ggplot2 中制作图表,我想通过左对齐来节省图表的自由标题中的空间。问题是,使用hjust
不正常。
library(ggplot2)
chart <- ggplot(
data = cars,
aes(
x = speed,
y = dist
)
) +
geom_point() +
labs(
title = "Here is a very long title that will need a\nlinebreak here",
subtitle = "This subtitle will also have\na linebreak"
) +
theme(
plot.title = element_text(
hjust = -0.1
)
)
chart
ggsave(
filename = "~/Desktop/myplot.png",
plot = chart,
# type = "cairo",
height = 4,
width = 6,
dpi = 150)
我希望“这里”和“换行符”与 y 轴标题对齐。单独使用 ggplot2 可以吗?
解决方案
您可以geom_text
与 which 一起使用coord_cartesian(clip = "off")
允许在绘图面板之外绘制绘图元素
library(ggplot2)
ggplot(
data = cars,
aes(x = speed,
y = dist)) +
geom_point() +
labs(subtitle = "This subtitle will also have\na linebreak") +
geom_text(
x = 1,
y = 160,
inherit.aes = FALSE,
label = "Here is a very long title that will need a\nlinebreak here",
check_overlap = TRUE,
hjust = 0,
size = 6
) +
coord_cartesian(clip = "off") +
theme(plot.margin = unit(c(4, 1, 1, 1), "lines"))
另一种方法是ggarrange
从具有可用于标题egg
的参数的包中使用top
chart <- ggplot(
data = cars,
aes(
x = speed,
y = dist)) +
geom_point() +
labs(subtitle = "This subtitle will also have\na linebreak")
library(grid)
# devtools::install_github('baptiste/egg')
library(egg)
#> Loading required package: gridExtra
ggarrange(chart,
ncol = 1,
top = textGrob(
"Here is a very long title that will need a\nlinebreak here",
gp = gpar(fontface = 1, fontsize = 14),
hjust = 0,
x = 0.01)
)
由reprex 包(v0.2.1.9000)于 2018 年 9 月 18 日创建