R ggplot中标题行的不相等水平调整
我有一个具有相当宽的y轴标签的绘图,所以我想将标题调整到左侧,使其与标签而不是轴(类似)齐平,但问题是我有一个多行标题。我一直在使用hjust,但它调整两条线的方式不同。 比如说R ggplot中标题行的不相等水平调整,r,ggplot2,R,Ggplot2,我有一个具有相当宽的y轴标签的绘图,所以我想将标题调整到左侧,使其与标签而不是轴(类似)齐平,但问题是我有一个多行标题。我一直在使用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_b
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))
给予
有没有办法在水平调整标题的两行后使其开头齐平?对不起,我误解了你的问题 我想你只是缺少了标题中的一个空格
ggtitle(“图:我的长而曲折的标题\n继续不断”)
hjust
负责空格。
删除它删除第二行上的2个空格
库(ggplot2)
ggplot(mtcars,aes(x=wt,y=mpg))+
几何点()+
ggtitle(“图:我的长而曲折的标题\n继续不断”)+
ylab(“我的长标签”)+
主题_bw()+
主题(plot.title=element_text)(大小=16,
color=“black”,face=“bold”,
),
axis.title.y=元素\文本(角度=0,hjust=1))
编辑1:
如果要自动将标题拆分为多行,可以使用gsub
。下面是一个例子,我将标题拆分为30个字符
long\u title您可以使用以下代码。首先创建绘图并将其分配给g
,然后使用ggplotGrob
将g
转入agrob
。因此,在grob的布局中操纵标题左对齐(从5到2)。最后绘制出改编后的grob
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)
g给你:
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)`
库(ggplot2)
图书馆(网格)
图书馆(“gridExtra”)
pI已在hjust的主题中具有plot.title。这个新的只是覆盖了它。如果我将其设置为原来的-0.33,我会得到相同的问题。为什么您希望它为-0.33?上述输出是否不正确?是否希望标题位于y轴的左侧?是的,“我想将标题调整到左侧,使其与标签而不是轴齐平”,但我想水平调整标题。两行字都一样。@pgcudahy很抱歉误会了。EDIT1根据每行的字符数(这里是30个)将长标题拆分。我认为这是最好/最干净的答案。
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)`