参考自《R Graphics Cookbook》
本节针对怎么在作图后添加整体(全局、全图)标题的问题。
1、 直接添加标题的语法:1. ggtitle("") 或 2. labs(title = ""), 本文不展示labs方法
2、 间接添加标题的语法:使用annotate添加标签,让其起到标题效果
library(ggplot2)
library(gcookbook)
#底图
hw_plot <- ggplot(heightweight, aes(x = ageYear, y = heightIn)) +
geom_point()
![c287438434189314d24e236e429fa542.png](https://img-blog.csdnimg.cn/img_convert/c287438434189314d24e236e429fa542.png)
一、ggtitle加标题
#默认是在图的左上方显示,而非中间,这个问题需要解决,后文涉及
hw_plot +
ggtitle("Age and Height of Schoolchildren")
![4d847e387fedf9ec644a0eaf33668b5c.png](https://img-blog.csdnimg.cn/img_convert/4d847e387fedf9ec644a0eaf33668b5c.png)
#使用反斜杠加n换行
hw_plot +
ggtitle("Age and Heightnof Schoolchildren")
![f6c62c4f020796cbcfe6f7a479b1d7c1.png](https://img-blog.csdnimg.cn/img_convert/f6c62c4f020796cbcfe6f7a479b1d7c1.png)
#若传递给ggtitle两个参数,则第二个默认为次标题,且字体相对较小
hw_plot +
ggtitle("主标题", "次标题")
![e18db080c66f6a75438adbd2b2b2a304.png](https://img-blog.csdnimg.cn/img_convert/e18db080c66f6a75438adbd2b2b2a304.png)
二、移动坐标轴位置
2.1 ggtitle移动位置
#在theme中移动标题位置,但需注意上方依然给标题留有默认的位置空间
hw_plot +
ggtitle("Age and Height of Schoolchildren") +
#向下微调标题位置
theme(plot.title = element_text(vjust = -8))
![b80a19da58e6a2a4d2694ae756b9613f.png](https://img-blog.csdnimg.cn/img_convert/b80a19da58e6a2a4d2694ae756b9613f.png)
##补充:关于ggtitle下标题横向居中的问题
#由于ggtitle是默认生成在左上方,居中显示是个重要的问题,
#查阅资料后仅发现 theme(plot.title = element_text(hjust = 0.5)可以起到作用,
#但是按说hjust和vjust都是调整绝对位置,怎么给hjust0.5的移动就居中了呢,暂时未解?!
hw_plot +
ggtitle("Age and Height of Schoolchildren") +
#横向居中、纵向向下微调标题位置
theme(plot.title = element_text(hjust = 0.5, vjust = -10))
![f71567753780e666d1436e5b182bc506.png](https://img-blog.csdnimg.cn/img_convert/f71567753780e666d1436e5b182bc506.png)
2. 2 不使用ggtitle,而是使用annotate直接加标签,让其起到是title的作用,并调整位置
hw_plot +
annotate("text",
#使用mean函数设置标签的横向显示位置为在均值处(居中)
x = mean(range(heightweight$ageYear)),
#设置标签的位置在y方向的最上方
y = Inf,
label = "Age and Height of Schoolchildren",
#在y方向微调标签位置
vjust = 1.5, size = 4.5)
![691a841eb219145b6f99b9c37bf09ed1.png](https://img-blog.csdnimg.cn/img_convert/691a841eb219145b6f99b9c37bf09ed1.png)
三、总结
可以使用ggtitle或labs语法直接添加标题,此时的标题是真标题,即使移动,上方也会一直保有显示标题的空间。因为ggplot2在识别到添加标题的语法时,就会默认预留空间。
使用annotate语法添加标签当做标题,但ggplot2没有识别到标题语法,因此不会在上方预留添加标题的空间。需根据具体需求决定方法。
居中问题需要注意。