在R中,该如何绘制一组数据的概率分布图像呢?用下面这个数据举例说明:
- et.seed(1234)
- dat <- data.frame(cond = factor(rep(c("A","B"), each=200)),
- rating = c(rnorm(200),rnorm(200, mean=.8)))
- # 简单看一下数据的前几行 View first few rows
- head(dat)
- #> cond rating
- #> 1 A -1.2070657
- #> 2 A 0.2774292
- #> 3 A 1.0844412
- #> 4 A -2.3456977
- #> 5 A 0.4291247
- #> 6 A 0.5060559
-
- library(ggplot2)
1、直方图与密度图
函数qplot有着与函数ggplot类似的绘图功能,但相比之下,其语法更为简单。然而有时候我们在实际使用中会觉得ggplot更好上手,因为在qplot里,对参数的使用常常更为复杂。
- ## 根据变量"rating"作传统的直方图,窗宽为0.5
- ggplot(dat, aes(x=rating)) + geom_histogram(binwidth=.5)
- ## 下面这行代码也能达到同样的效果:
- # qplot(dat$rating, binwidth=.5)
-
- # 白色填充,黑色轮廓
- ggplot(dat, aes(x=rating)) +
- geom_histogram(binwidth=.5, colour="black", fill="white")
-
- # 密度曲线
- ggplot(dat, aes(x=rating)) + geom_density()
-
- # 带核密度曲线的概率分布直方图
- ggplot(dat, aes(x=rating)) +
- geom_histogram(aes(y=..density..), # y轴刻度对应的为概率密度而非计数
- binwidth=.5,
- colour="black", fill="white") +
- geom_density(alpha=.2, fill="#FF6666") # 设置附加半透明的密度图
添加均值线:
- ggplot(dat, aes(x=rating)) +
- geom_histogram(binwidth=.5, colour="black", fill="white") +
- geom_vline(aes(xintercept=mean(rating, na.rm=T)), # Ignore NA values for mean
- color="red", linetype="dashed", size=1)
- # 叠加直方图
- ggplot(dat, aes(x=rating, fill=cond)) +
- geom_histogram(binwidth=.5, alpha=.5, position="identity")
-
- # 交错直方图
- ggplot(dat, aes(x=rating, fill=cond)) +
- geom_histogram(binwidth=.5, position="dodge")
-
- # 密度图
- ggplot(dat, aes(x=rating, colour=cond)) + geom_density()
-
- # 带半透明填充的密度图
- ggplot(dat, aes(x=rating, fill=cond)) + geom_density(alpha=.3)
在有多组数据的情况下,添加均值时我们需要先构建一个单独的均值数据框:
- # 找到每组数据的均值
- library(plyr)
- cdat <- ddply(dat, "cond", summarise, rating.mean=mean(rating))
- cdat
- #> cond rating.mean
- #> 1 A -0.05775928
- #> 2 B 0.87324927
-
- # 带均值线的叠加直方图
- ggplot(dat, aes(x=rating, fill=cond)) +
- geom_histogram(binwidth=.5, alpha=.5, position="identity") +
- geom_vline(data=cdat, aes(xintercept=rating.mean, colour=cond),
- linetype="dashed", size=1)
-
- # 带均值线的密度图
- ggplot(dat, aes(x=rating, colour=cond)) +
- geom_density() +
- geom_vline(data=cdat, aes(xintercept=rating.mean, colour=cond),
- linetype="dashed", size=1)
本内容转自数析学院,原文后面还有画布分区和箱线图的绘制。


雷达卡






京公网安备 11010802022788号







