- 加载包,主要是为了利用里面的数据集Arthritis
> library(vcd)
> head(Arthritis) 数据集的前几行格式
ID Treatment Sex Age Improved
1 57 Treated Male 27 Some
2 46 Treated Male 29 None
3 77 Treated Male 30 None
4 17 Treated Male 32 Marked
5 36 Treated Male 46 Marked
6 23 Treated Male 58 Marked
- 条形图
# table统计数据集列Improved的数据
> counts <- table(Arthritis$Improved)
> counts
None Some Marked
42 14 28
(1)垂直条形图
> barplot(counts, main='Sample Bar Plot', xlab='Improvement', ylab='Frequency')
(2)
水平条形图
> barplot(counts, main='Sample Bar Plot', xlab='Improvement', ylab='Frequency', horiz=TRUE)
(3)
堆砌条形图
> counts <- table(Arthritis$Improved, Arthritis$Treatment)
> counts
Placebo Treated
None 29 13
Some 7 7
Marked 7 21
> barplot(counts, main='Sample Bar Plot', xlab='Improvement', ylab='Frequency')
加颜色图例
> barplot(counts, main='Sample Bar Plot', xlab='Improvement', ylab='Frequency', col=c('red','yellow','green'), legend=rownames(counts))
(4)
分组条形图 beside=TRUE
> barplot(counts, main='Sample Bar Plot', xlab='Improvement', ylab='Frequency', beside=TRUE)
(5)棘状图
spine是vcd里的函数
> library(vcd)
> spine(counts) main="名儿"
- 直方图
来画个四宫格吧
> par(mfrow=c(2,2))
> hist(mtcars$mpg, main="fig1")
> hist(mtcars$mpg, breaks=12, col="#999999", main="fig2")
> hist(mtcars$mpg, breaks=12, freq=FALSE, main="fig3")
> rug(jitter(mtcars$mpg)) 添加轴须图
> lines(density(mtcars$mpg), col="black", lwd=2) 添加密度曲线
> h <- hist(mtcars$mpg, breaks=12, main="fig4")
添加正态密度曲线
> xfit <- seq(min(mtcars$mpg), max(mtcars$mpg), length=40)
> yfit <- dnorm(xfit, mean=mean(mtcars$mpg), sd=sd(mtcars$mpg))
> yfit <- yfit*diff(h$mids[1:2])*length(mtcars$mpg)
> lines(xfit, yfit, col="black", lwd=2)
> box() 添加外框
(6)
核密度图
> library(sm)
> attach(mtcars)
> head(mtcars)
mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
> cyl.f <- factor(cyl, levels=c(4, 6, 8), labels=c("4 cylinder", "6 cylinder", "8 cylinder"))
> sm.density.compare(mpg, cyl, xlab="mpg") 画出核密度图
> title(main="title") 添加标题
> colfill <- c(2: (1+length(levels(cyl.f))))
> legend(locator(1), levels(cyl.f), fill=colfill) 添加图例
(7)
箱线图
> boxplot.stats(mpg)
$stats
[1] 10.40 15.35 19.20 22.80 33.90
$n
[1] 32
$conf
[1] 17.11916 21.28084
$out
numeric(0)
> boxplot(mpg~cyl, data=mtcars)
> boxplot(mpg~cyl, data=mtcars,
+ notch=TRUE, 含凹槽的箱线图
+ varwidth=TRUE) 箱线图的宽度与样本大小成正比
> cyl.f <- factor(cyl, levels=c(4, 6, 8), labels=c("4 cylinder", "6 cylinder", "8 cylinder"))
> am.f <- factor(am, levels=c(0, 1), labels=c("0", "1"))
> boxplot(mpg~am.f *cyl.f, data=mtcars, varwidth=TRUE) 两个交叉因子箱线图
小提琴图
> x1 <- mpg[cyl==4]
> x2 <- mpg[cyl==6]
> x3 <- mpg[cyl==8]
> vioplot(x1, x2, x3, names=c("4", "6", "8"))
(8)
点图
> dotchart(mpg, labels=row.names(mtcars))