作图
作图系统
- graphics包, 基础包
- lattice包
- ggplot2包, 重点
基础包graphics作图
- 高级图形函数例子(初始化图形窗口)
- plot 通用绘图
- boxplot 箱线图
- hist 直方图
- qqnorm Q-Q图
- curve 绘制函数图形
- 低级图形函数例子(不能启动新图形, 要先用高级函数做一个图)
- points 添加点
- lines 添加线
- abline 添加直线
- segments 添加线段
- polygon 添加闭合多边形
- text 添加文本
单个变量
一个定类或定序向量: barplot 条形图
1 | gender <- sample(c("m", "f"), 20, replace = T, |
一个定类或定序向量: pie 饼图
1 | pie(table(gender)) |
一个数值型向量: hist 直方图
1 | set.seed(123); height <- rnorm(100, mean=170, sd=10) |
一个数值型向量: boxplot 箱线图
1 | boxplot(height) |
两个变量
两个数值型向量: plot 散点图
1 | x <- seq(-2,2,by = 0.1); y <- x^2 |
plot 函数的参数
plot 函数的若干参数: ?plot, ?plot.default
- type 可以画点, 画线, etc.
- main 标题
- xlab, ylab 横纵轴标题
- xlim, ylim 指定横纵轴的取值范围
- col 颜色
- pch点型, cex点大小, lty线型, lwd线宽, 等等
很多其他高级图形函数也有这些参数
plot函数添加参数的例子
1 | x = (0:100)/20; y = sin(x) |
低级图形函数
使用points添加点
1 | plot(1:5, 1:5); points(1:5, rep(1.5,5), cex = 2, pch = 17) |
使用lines添加线
1 | x <- seq(-4,4,by = 0.1); plot(x, dnorm(x), type = "l") |
使用text添加文字
1 | plot(x, dnorm(x), type = "l") |
其他图形
正态概率图:qqnorm(x)
作用: 判断数据是否服从正态分布
1 | set.seed(123); qqnorm(rnorm(100)) |
使用curve绘制函数
1 | curve(sin, -3, 3) |
图形排版: 在一页中显示N行M列个图形
par(mfrow = c(N, M))
1 | op <- par(no.readonly = T) |
1 | par(op) |
一些可能用得到的基础作图函数
- grid: 给plot图形添加网格, 需要先设置 type = “n”
- legend: 给plot图形添加图例
ggplot2包
包的安装:
1 | install.packages("ggplot2") |
包的加载
1 | library(ggplot2) |
ggplot2包的主要内容
两个基本函数:
- qplot
- ggplot
两个数据集:
- diamonds 约54000颗钻石的信息
- dsmall 随机选出100颗钻石的子数据集
1 | set.seed(1410) |