一、什么是茎叶图
茎叶图(Stem-and-Leaf display)又称“枝叶图”,是在20世纪早期由英国统计学家阿瑟·鲍利(Arthur Bowley)设计,1977年统计学家约翰托奇(John Tukey)在其著作《探索性数据分析》(exploratory data analysis)中将这种绘图方法介绍给大家,从此这种作图方法变得流行起来1。
茎叶图的具体优缺点介绍大家参考参考文献[1].这篇博客主要讲述R语言里的茎叶图的画法。主要介绍stem的四个参数。
二、stem函数
2.1函数体
下面是stem的函数参数和函数体。一共四个参数。
function (x, scale = 1, width = 80, atom = 1e-08)
{
if (!is.numeric(x))
stop("'x' must be numeric")
x <- x[is.finite(x)]
n <- as.integer(length(x))
if (is.na(n))
stop("invalid length(x)")
if (n == 0)
stop("no finite and non-missing values")
if (scale <= 0)
stop("'scale' must be positive")
.Call(C_StemLeaf, as.double(x), scale, width, atom)
invisible(NULL)
}
2.2画图例子
# 数据准备
> (x = runif(50, 1, 100)) # 从1到100生成随机数。
[1] 87.302052 47.510844 54.385072 92.482549 76.148508 73.216987 7.444404
[8] 38.662258 53.138103 71.069201 24.455214 64.735297 37.253457 81.262954
[15] 61.864699 83.330179 32.041227 19.243838 95.310140 41.995248 68.512872
[22] 93.324107 4.705462 74.491219 32.373659 79.872579 60.137169 88.045087
[29] 18.558294 16.113912 3.392578 79.314849 45.329222 93.484869 51.172555
[36] 43.875062 21.172103 79.907137 66.764898 95.802397 72.305633 55.206484
[43] 46.622734 23.428576 73.880924 45.940560 85.286627 9.383284 85.885653
[50] 14.402983
茎叶图的数据是整数,所以对向量x
进行取整数更新x
。
> (x = round(x)) # 取整并输出
[1] 87 48 54 92 76 73 7 39 53 71 24 65 37 81 62 83 32 19 95 42 69 93 5 74
[25] 32 80 60 88 19 16 3 79 45 93 51 44 21 80 67 96 72 55 47 23 74 46 85 9
[49] 86 14
最后一步就是画茎叶图了。
> stem(x)
The decimal point is 1 digit(s) to the right of the |
0 | 3579
1 | 4699
2 | 134
3 | 2279
4 | 245678
5 | 1345
6 | 02579
7 | 1234469
8 | 00135678
9 | 23356
2.3参数调整
从2.2中还看到了这个函数中还有三个参数是干啥的呢,下面一一解答。
function (x, scale = 1, width = 80, atom = 1e-08)
2.3.1scale
scale
控制茎叶图的间隔默认是1。为了具体展示函数效果我们把参数更改为0.5和2如下:
> stem(x = x, scale = 0.5)
The decimal point is 1 digit(s) to the right of the |
0 | 35794699
2 | 1342279
4 | 2456781345
6 | 025791234469
8 | 0013567823356
> stem(x = x, scale = 2)
The decimal point is 1 digit(s) to the right of the |
0 | 3
0 | 579
1 | 4
1 | 699
2 | 134
2 |
3 | 22
3 | 79
4 | 24
4 | 5678
5 | 134
5 | 5
6 | 02
6 | 579
7 | 12344
7 | 69
8 | 0013
8 | 5678
9 | 233
9 | 56
2.3.2 width
width
控制茎叶图的宽默认是80。当参数为0-8时则显示长度大于设置宽度统计个数,为了具体展示函数效果我们把参数更改为1000,0,5如下:
> stem(x = x, scale = 0.5, width = 1000)
The decimal point is 1 digit(s) to the right of the |
0 | 35794699
2 | 1342279
4 | 2456781345
6 | 025791234469
8 | 0013567823356
> stem(x = x, scale = 0.5, width = 0)
The decimal point is 1 digit(s) to the right of the |
0 | +4
1 | +4
2 | +3
3 | +4
4 | +6
5 | +4
6 | +5
7 | +7
8 | +8
9 | +5
> stem(x = x, scale = 0.5, width = 5)
The decimal point is 1 digit(s) to the right of the |
0 |
1 |
2 |
3 |
4 | +1
5 |
6 |
7 | +2
8 | +3
9 |
2.3.2 atom
atom
是一个精度,一般用的不多,大家接受默认参数即可。
三、总结
本文讲解了R语言中的stem函数画茎叶图,希望能够帮助到各位小伙伴。如有问题,评论区见。
四、参考资料
https://baike.baidu.com/item/茎叶图/10840752?fr=aladdin#reference-[1]-634970-wrap ↩︎