R可视化03|ggplot2图层-几何对象图层(geom layer)
"pythonic生物人"的第101篇分享
前面简单介绍ggplot2是基于图层图形语法(the Grammar of Graphics),一张完整图由不同图层叠加而成,本文介绍几何对象图层(geom layer),续前篇:
ggplot2中geom可分为个体几何对象(Individual geoms)及群组几何对象(Collective geoms),二者区别:
1、个体几何对象(Individual geoms)
An individual geom draws a distinct graphical object for each observation (row).【一个观测值对应一个图形】
Each of these geoms is two dimensional and requires both x
and y
aesthetics,these geoms are the fundamental building blocks of ggplot2.
library('ggplot2')
library('gridExtra')
options(repr.plot.width = 7, repr.plot.height = 6, repr.plot.res = 250)#设置图形渲染参数
df <- data.frame(
x = c(3, 1, 5),
y = c(2, 4, 6),
label = c("a","b","c")
)
p1 <- ggplot(df, aes(x, y, label = label)) +
labs(x = NULL, y = NULL) + #隐藏坐标轴名称
theme(plot.title = element_text(size = 12))
p2 <- p + geom_point() + ggtitle("point")
p3 <- p + geom_text() + ggtitle("text")
p4 <- p + geom_bar(stat = "identity") + ggtitle("bar")
p5 <- p + geom_tile() + ggtitle("raster")
p6 <- p + geom_line() + ggtitle("line")
p7 <- p + geom_area() + ggtitle("area")
p8 <- p + geom_path() + ggtitle("path")
p9 <- p + geom_polygon() + ggtitle("polygon")
grid.arrange(p1, p2, p3, p4, p5, p6, p7, p8,p9, nrow = 4)
2、 群组几何对象(Collective geoms)
A collective geom displays multiple observations with one geometric object.【多个观测值对应一个图形】
该部分使用到数据集Oxboys
, 来自 nlme package. It records the heights (height
) and centered ages (age
) of 26 boys (Subject
), measured on nine occasions (Occasion
). Subject
and Occassion
are stored as ordered factors.以下以几个例子帮助理解Collective geom:
#一张图展示每个Subject的身高height随年龄age变化情况
options(repr.plot.width = 7, repr.plot.height = 4, repr.plot.res = 250)#设置图形渲染参数
ggplot(Oxboys, aes(age, height, group = Subject)) + geom_point() + geom_line()#按照Subject分组绘制散点和折线图
# 不同图层不同分组
ggplot(Oxboys, aes(age, height)) +
geom_line(aes(group = Subject)) + #折线图层按照Subject分组
geom_smooth(method = "lm", size = 2, se = FALSE)#添加一个拟合线图层
ggplot(Oxboys, aes(Occasion, height)) +
geom_boxplot() +
geom_line(aes(group = Subject), colour = "#3366FF", alpha = 0.5)#设置line图层的属性,如颜色、透明度
# 个体图形属性与整体图像属性匹配
ggplot(mpg, aes(class, fill = drv)) +
geom_bar()
df <- data.frame(x = 1:3, y = 1:3, colour = c(1, 3, 5))
ggplot(df, aes(x, y, colour = factor(colour))) + geom_line(aes(group = 1), size = 2) +
geom_point(size = 5)
https://ggplot2-book.org/individual-geoms.html https://ggplot2-book.org/collective-geoms.html
往期精彩: