写在前面。
在本文中将讨论如何控制 ggplot2 图形的整体外观,例如字体、背景颜色等问题。
和数据所映射的图形元素不同,主题系统为控制非数据元素的外观提供了可能。
设置图形的标题
如何设置一幅图形的标题?
示例数据需要加载 gcookbook 包,其中的 heightweight 数据集:
> library(gcookbook)
> str(heightweight)
'data.frame': 236 obs. of 5 variables:
$ sex : Factor w/ 2 levels "f","m": 1 1 1 1 1 1 1 1 1 1 ...
$ ageYear : num 11.9 12.9 12.8 13.4 15.9 ...
$ ageMonth: int 143 155 153 161 191 171 185 142 160 140 ...
$ heightIn: num 56.3 62.3 63.3 59 62.5 62.5 59 56.5 62 53.8 ...
$ weightLb: num 85 105 108 92 112 ...
使用 ggtitle 设置标题或者 labs进行设置。
p <- ggplot(data = heightweight, aes(x = ageYear, y = heightIn)) + geom_point()
p + ggtitle("Age and Height \nof Schoolchildren")
[图片上传失败...(image-2559fe-1699922015360)]
使用labs:
p <- ggplot(data = heightweight, aes(x = ageYear, y = heightIn)) + geom_point()
p + labs(title = "Age and Height of Schoolchildren")
[图片上传失败...(image-a636b5-1699922015360)]
以上。