R语言之数据可视化

1. 绘图函数:

  - lattice 包:

    · xyplot / bwplot / histogram / stripplot / dotplot / splom / levelplot / contourplot

    · 格式:xyplot ( y ~ x | f * g , data )

    · panel 函数,用于控制每个面板内的绘图

  - grid 包:

    · 实现了独立于base的绘图系统

    · lattice包是基于grid创建的;很少直接从grid包调用函数

2. Lattice 与 Base 的重要区别

  - Base 绘图函数直接在图形设备上绘图

  - 而Lattice 绘图函数返回 trellis 类对象

    · 打印函数真正执行了在设备上绘图

    · 命令执行时,trellis 类对象会被自动打印,所以看起来就像是 lattice 函数直接完成了绘图

3. 实践

  - 安装 lattice 包:install.packages("lattice")

  - 查询帮助文档:如 ?xyplot 

library(lattice) 
# 引入lattice包
xyplot(Temp~Ozone, data=airquality)
# 考察Temp和Ozone之间的关系
airquality$Month <- factor(airquality$Month)
# Month变量转换成factor,即分类变量
xyplot(Temp~Ozone | Month, data=airquality, layout=c(5,1))
# Temp和Ozone 与月份之间的关系(lattice体现交互作用)

q <- xyplot(Temp~Wind, data=airquality)
# xyplot存到变量里,生成类对象
print(q)
# 打印类对象,若xyplot不存入变量,则会直接打印出来

set.seed(1)
# 设置种子点,意义在于每次产生的随机数是一样的(使用随机数时切记使用种子点)
x <- rnorm(100)
# 从变准正态分布中抽取100个随机数,赋值给x
f <- rep(0:1, each=50)
# f变量只包含0和1这两个值,每个值出现50次,所以f变量内有100个数
y <- x + f - f*x + rnorm(100, sd=0.5)
# 让x与y之间的关系与f变量有交互
f <- factor(f, labels=c("Group1","Group2"))
# f变量转换成factor,即分类变量
xyplot(y~x | f, layout=c(2,1))
# x和y 与f之间的关系
xyplot(y~x | f, panel=function(x, y){
  panel.xyplot(x,y)
  panel.abline(v=mean(x), h=mean(y), lty=2)
  panel.lmline(x,y,col="red")
})
# abline:添加x平均直线,添加y平均直线
# lmline:拟合线性模型

原文地址:https://www.cnblogs.com/wnzhong/p/6426899.html