问题描述
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 words\nand 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 words\nand 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,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))
)
,
我可能会错过明显的,但一个简单的选择是使用副标题 :)
现在,hjust 与 title 和 subtitle 的缩进也不一样,但是,它似乎是一个常量!奇怪的是,这完全取决于您的设备。例如,在我的 RStudio 查看器中,我需要一个 ~2.1 的常量,对于 ggsave ~1.49,我需要 1.525(参见示例)。但是,一旦找到常数,它实际上是相当一致的。 至少 - 对我来说。
也适用于负平衡!
library(ggplot2)
set.seed(10)
df <- data.frame(x = 1:10,y = round(rnorm(10) * 1:10,2))
p <- ggplot(df,aes(x,y)) +
labs(
title = "Here comes my title like that some words",subtitle = "and my second line title"
)
hjusttitle <- 0.175
p +
theme(
plot.title = element_text(hjust = hjusttitle,size = 14),plot.subtitle = element_text(hjust = hjusttitle / 1.525,size = 14)
)
hjusttitle <- -0.15
p +
theme(
plot.title = element_text(hjust = hjusttitle,size = 14)
)
hjusttitle <- 1
p +
theme(
plot.title = element_text(hjust = hjusttitle,size = 14)
)
由 reprex package (v0.3.0) 于 2021 年 1 月 4 日创建