面向 SAS 用户的 R
Melinda Higgins, PhD
Research Professor/Senior Biostatistician Emory University

ggplot2 是 R 的强大绘图包ggplot 中的"GG"指"图形语法"ggplot2 通过分层构建图形# 创建 x=sex, y=diameter 的图
ggplot(data = abalone, aes(sex, diameter))
ggplot() 定义基础图层data = abalone将 aes 设为 sex 和 diameter
还没有添加几何对象
sexdiameter
# 添加箱线图几何对象(geom)
ggplot(data = abalone,
aes(sex, diameter)) +
geom_boxplot()
+ 添加图层添加箱线图 geom_boxplot()
得到一组箱线图
F 雌性,I 幼体,M 雄性
# 添加黑白主题
ggplot(data = abalone,
aes(sex, diameter)) +
geom_boxplot() +
theme_bw()
theme_bw() 添加"主题"层
# 改为 geom_violin()
ggplot(data = abalone,
aes(sex, diameter)) +
geom_violin() +
theme_bw()
geom_violin 替换 geom_boxplot
# 绘制 shuckedWeight 的直方图
ggplot(abalone, aes(shuckedWeight)) +
geom_histogram()
geom_histogram()aes() 设为 shuckedWeight
# 线条设为黑色,填充浅蓝
ggplot(abalone, aes(shuckedWeight)) +
geom_histogram(color = "black",
fill = "lightblue")
colorfill 颜色() 内设置
# 添加坐标轴标签和标题
ggplot(abalone, aes(shuckedWeight)) +
geom_histogram(color = "black",
fill = "lightblue") +
xlab("Shucked Weight") +
ylab("Frequency Counts") +
ggtitle("Shucked Weights Histogram")
xlab() 和 ylab()ggtitle()
# 用 geom_point() 绘制散点图
ggplot(abalone,
aes(rings, shellWeight)) +
geom_point()
aes 需两个变量geom_point() 添加点
# 添加平滑拟合线
ggplot(abalone,
aes(rings, shellWeight)) +
geom_point() +
geom_smooth()
geom_smooth() 线
# 用 facet_wrap() 添加分面
ggplot(abalone,
aes(rings, shellWeight)) +
geom_point() +
geom_smooth() +
facet_wrap(vars(sex))
facet_wrap() 层vars(sex) 指定分面变量
ggplot2 绘图基础面向 SAS 用户的 R