我有一个带有相当宽的y轴标签的图,所以我想将标题调整到左侧,以使其与标签而不是轴齐平(例如this question),但要扭转是我有多行标题。我一直在使用hjust,但是它对两条线的调整不同。 例如
ggplot(mtcars,aes(x=wt,y=mpg))+
geom_point()+
ggtitle("Figure: My long and winding title\nthat goes on and on and on") +
ylab("My long label") +
theme_bw() +
theme(plot.title = element_text(size=16, hjust=-.33, color="black", face="bold")) +
theme(axis.title.y = element_text(angle = 0, hjust = 1))
答案 0 :(得分:2)
您可以使用以下代码。首先创建图并将其分配给g
,然后用g
将grob
变成ggplotGrob
。因此,请在grob的layout
部分中操作标题左对齐(从5到2)。最后绘制改编的格罗布。
g <- ggplot(mtcars,aes(x=wt,y=mpg)) +
geom_point() +
ggtitle("Figure: My long and winding title\nthat goes on and on and on") +
ylab("My long label") +
theme_bw() +
theme(plot.title = element_text(size=16, color="black", face="bold")) +
theme(axis.title.y = element_text(angle = 0, hjust = 1))
grob <- ggplotGrob(g)
# what is the current content
grob$layout$l[grob$layout$name == "title"]
[1] 5
grob$layout$l[grob$layout$name == "title"] <- 2
# plot the new grob
grid::grid.draw(grob)
产生此情节:
请让我知道这是否是您想要的。
答案 1 :(得分:0)
对不起,我误解了你的问题。
我认为您只是在标题中缺少空格。
ggtitle("Figure: My long and winding title\n that goes on and on and on")
答案 2 :(得分:0)
hjust
是空白的负责人。
删除它会删除第二行的2个空格。
library(ggplot2)
ggplot(mtcars,aes(x=wt,y=mpg))+
geom_point()+
ggtitle("Figure: My long and winding title\nthat goes on and on and on") +
ylab("My long label") +
theme_bw() +
theme(plot.title = element_text(size=16,
color="black", face="bold",
),
axis.title.y = element_text(angle = 0, hjust = 1))
编辑1:
如果您要自动将标题分成多行,则可以使用gsub
。这是一个示例,其中标题分割为30个字符。 (source)
long_title <- "Figure: My long and winding title that goes on and on and on"
ggplot(mtcars,aes(x=wt,y=mpg))+
geom_point()+
ggtitle(gsub('(.{1,30})(\\s|$)', '\\1\n', long_title)) +
ylab("My long label") +
theme_bw() +
theme(plot.title = element_text(size=16,
color="black", face="bold",
),
axis.title.y = element_text(angle = 0, hjust = 1))
希望有帮助!
答案 3 :(得分:0)
您在这里:
library(ggplot2)
library(grid)
library("gridExtra")
p<-ggplot(mtcars,aes(x=wt,y=mpg))+
geom_point()+
ggtitle("") +
ylab("My long label") +
theme_bw() +theme(axis.title.y = element_text(angle = 0, hjust = 1))
title.grob <- textGrob(
label = "Figure: My long and winding title\nthat goes on and on and on",
x = unit(0, "lines"),
y = unit(0, "lines"),
hjust = 0, vjust = 0,
gp = gpar(fontsize = 16))
p1 <- arrangeGrob(p, top = title.grob)
grid.draw(p1)`