如何对齐多行标题
我有ggplot标题定位问题。当我使用hjust参数将标题向右滑动时,两行都会向左和向右滑动。我想要它们一个在另一个下面。drawlabel(),annototations对我的情况没有用,因为它们取决于 x 和 y 轴及其单位(日期、货币、公斤),这意味着每次我必须调整它们时。我想要独特的坐标系,无论我在绘制什么,我都可以轻松地将相同的位置用于不同的绘图。
下面显示了一个不受欢迎的代码示例。
set.seed(10)
df <- data.frame(x=1:10,y=round(rnorm(10)*1:10,2))
ggplot(df,aes(x=x,y=y))+
geom_line(size=0.75)+
labs(title = 'Here comes my title like that some wordsnand my second line title')+
theme(
plot.title.position = 'plot',
plot.title = element_text(hjust = 0.075)
)
不受欢迎的情节
合意的情节
回答
我同意@stefan 在评论中的观点,即似乎无法使用theme.
一种黑客方法是删除您的hjust更改并通过编辑网格布局手动移动标题的位置。
library(ggplot)
library(grid)
p <- ggplot(df,aes(x=x,y=y)) +
geom_line(size=0.75) +
labs(title = 'Here comes my title like that some wordsnand my second line title') +
theme(plot.title.position = 'plot')
grob <- ggplotGrob(p)
grob$layout[grob$layout$name == "title","l"] <- 4.5
grid.newpage()
grid.draw(grob)
您可以4.5根据需要进行更改以获得所需的效果。
回答
ggtext提供了一些工具,可以更轻松地处理文本。在下面的示例中,使用<br>来添加换行符,然后我们可以使用主题参数element_textbox_simple(在文本周围有一点填充)来渲染它。
library(ggplot2)
library(ggtext)
set.seed(10)
df <- data.frame(x=1:10,y=round(rnorm(10)*1:10,2))
ggplot(df,aes(x=x,y=y))+
geom_line(size=0.75)+
labs(title = 'Here comes my title like that some words <br> and my second line title') +
theme(
plot.title.position = "plot",
plot.title = element_textbox_simple(padding = margin(5.5, 5.5, 5.5, 5.5))
)