在 R 中绘制箱线图 - 0x02 使用 ggplot2 软件包
最编程
2024-10-12 07:01:43
...
一、准备工作
# 加载 ggplot2 库,用于数据可视化
library(ggplot2)
# 查看 diamonds 数据集的摘要信息
summary(diamonds)
# 从 diamonds 数据集中随机抽取 1000 个样本,并将结果重新赋值给 diamonds
# sample(1:nrow(diamonds), 1000):生成一个包含从 1 到 diamonds 数据集中行数的随机序列,然后取其中的 1000 个值
# diamonds[sample(1:nrow(diamonds),1000),]:根据随机生成的行索引,从 diamonds 数据集中选取对应的行,创建一个新的数据集
diamonds <- diamonds[sample(1:nrow(diamonds),1000),]
二、绘制基本的箱线图
使用geom_boxplot()
函数绘制箱线图。
ggplot(diamonds,aes(x = cut,y = price)) +
geom_boxplot()
三、绘制分组箱线图
# 使用 ggplot2 绘制图形,以 diamonds 数据集为基础
ggplot(diamonds,aes(x = cut,y = price,fill = color)) +
# 绘制箱线图
geom_boxplot()
四、绘制分面网格图
# 使用 ggplot2 绘制图形,以 diamonds 数据集为基础
ggplot(diamonds,aes(x = cut,y = price,fill = color)) +
# 绘制箱线图
geom_boxplot() +
# 按颜色进行分面,生成一个网格图,每行对应一个颜色类别
facet_grid(.~color) +
# 设置主题,将 x 轴的文本元素(即切割质量的标签)旋转 90 度,以便更好地显示
theme(axis.text.x = element_text(angle = 90))
五、美化和调整
# 使用 ggplot2 绘制图形,以 diamonds 数据集为基础
ggplot(diamonds,aes(x = cut,y = price,fill = color)) +
# 绘制箱线图
geom_boxplot() +
# 手动设置填充颜色,使用 rainbow(7) 生成的七种颜色
scale_fill_manual(values = rainbow(7)) +
# 设置图形标题、x 轴标签和 y 轴标签
labs(title = "boxplot of diamond", x = "cut of diamond", y = "price of diamond") +
# 设置主题,将图形标题居中
theme(plot.title = element_text(hjust = 0.5))