8.1 直方图和密度图
8.1.1 问题
你想要绘制一个直方图或密度图。
8.1.2 方案
样例数据:两个分别包含200个数据点的向量:
set.seed(1234)
rating <- rnorm(200)
head(rating)
#> [1] -1.2071 0.2774 1.0844 -2.3457 0.4291 0.5061
rating2 <- rnorm(200, mean = 0.8)
head(rating2)
#> [1] 1.2852 1.4968 0.9855 1.5007 1.1117 1.5605
当可视化含多个组别的数据时,一些绘图方法通常需要一个数据框:一列给分组变量,一列给测量值。
# 创建一列用于显示数据的组别
cond <- factor(rep(c("A", "B"), each = 200))
data <- data.frame(cond, rating = c(rating, rating2))
head(data)
#> cond rating
#> 1 A -1.2071
#> 2 A 0.2774
#> 3 A 1.0844
#> 4 A -2.3457
#> 5 A 0.4291
#> 6 A 0.5061
# 直方图
hist(rating)
# 使用8个箱子(这仅仅是近似 -
# 它会把边界放在一个比较好的近似值上) 让箱子呈现淡蓝色
# #CCCCFF
# 相比于计数,这里让面积为1,即显示比例(freq=FALSE)
hist(rating, breaks = 8, col = "#CCCCFF", freq = FALSE)
# 每0.6一个刻度
boundaries <- seq(-3, 3.6, by = 0.6)
boundaries
#> [1] -3.0 -2.4 -1.8 -1.2 -0.6 0.0 0.6 1.2 1.8 2.4
#> [11] 3.0 3.6
hist(rating, breaks = boundaries)
# 核密度图
plot(density(rating))
8.1.2.1 多个组别的核密度图
代码来自: http://onertipaday.blogspot.com/2007/09/plotting-two-or-more-overlapping.html
plot.multi.dens <- function(s) {
junk.x = NULL
junk.y = NULL
for (i in 1:length(s)) {
junk.x = c(junk.x, density(s[[i]])$x)
junk.y = c(junk.y, density(s[[i]])$y)
}
xr <- range(junk.x)
yr <- range(junk.y)
plot(density(s[[1]]), xlim = xr, ylim = yr, main = "")
for (i in 1:length(s)) {
lines(density(s[[i]]), xlim = xr, ylim = yr, col = i)
}
}
# 下面函数的输入必须是一个数值列表
plot.multi.dens(list(rating, rating2))
sm 包也引入了一种绘制多个密度图的方式,输入数据必须是数据框。
library(sm)
#> Warning in fun(libname, pkgname): couldn't connect to
#> display "/private/tmp/com.apple.launchd.aGFOp8QcsU/
#> org.macosforge.xquartz:0"
#> Package 'sm', version 2.2-5.6: type help(sm) for summary information
sm.density.compare(data$rating, data$cond)
# 添加一个图例 (颜色编号从2往上升)
legend("topright", levels(data$cond), fill = 2 + (0:nlevels(data$cond)))