本文介绍了ggplot中标题行的水平调整不相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有相当宽的y轴标签的图,所以我想将标题调整到左侧,以便它与标签而不是轴齐平(例如在水平调整标题后,是否可以使标题的两行的开头齐平?

解决方案

您可以使用以下代码.首先创建图并将其分配给 g ,然后使用 ggplotGrob g 转换为 grob .因此,请在grob的 layout 部分中操作标题的左对齐(从5到2).最后绘制改编的格罗布.

  g<-ggplot(mtcars,aes(x = wt,y = mpg))+geom_point()+ggtitle(图:我的冗长而曲折的标题\ n不断地在不断,")+ylab(我的长标签")+theme_bw()+主题(plot.title = element_text(size = 16,color ="black",face ="bold"))+主题(axis.title.y = element_text(角度= 0,高度= 1))grob<-ggplotGrob(g)#当前内容是什么grob $ layout $ l [grob $ layout $ name ==标题"][1] 5grob $ layout $ l [grob $ layout $ name =="title"]<-2#绘制新的grob网格:: grid.draw(grob) 

产生此情节:

请让我知道这是否是您想要的.

I've got a plot with a fairly wide y-axis label, so I want to adjust the title to the left so that it's flush with the label rather than the axis (like this question) but the twist is that I have a multiline title. I've been using hjust, but it adjusts the two lines differently.For example

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))

GivesIs there a way to make the start of the two lines of the title flush after adjusting them horizontally?

解决方案

You could use the following code. First create the plot and assign it to g, then turn g in to a grob with ggplotGrob. Consequently, manipulate the title left alignment in the layout part of the grob (from 5 to 2). And Finally plot the adapted 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)

yielding this plot:

Please let me know whether this is what you want.

这篇关于ggplot中标题行的水平调整不相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 15:45