常用的图形,这里给出案例:
barplot
条形图、单向量条形图
> attach(mtcars)
The following object is masked from package:ggplot2:
mpg
> names(mtcars)
[1] "mpg" "cyl" "disp" "hp" "drat" "wt"
[7] "qsec" "vs" "am" "gear" "carb" "manuf"
> barplot(table(cyl),
+ main="main",xlab="x",ylab="y")
barplot(table(cyl),horiz = TRUE)
plot(as.factor(cyl))
plot(factor(cyl,levels = c(6,4,8)))
堆砌与分组条形图
counts = table(cyl,gear)
counts
gear
cyl 3 4 5
4 1 8 2
6 2 4 1
8 12 0 2
barplot(counts,
xlab="gear",ylab="frequency",
col = c("red","yellow","green"),
legend=rownames(counts))
barplot(counts,
xlab="gear",ylab="frequency",
col = c("red","yellow","green"),
legend=rownames(counts),
beside=TRUE)
添加标签
legend(locator(1),title("title"),
rownames(counts),
lty=c(1,2),pch=c(15,17),
col=c("red","yellow","green"))
均值条形图
means = aggregate(mpg,by=list(cyl),mean)
means
Group.1 x
1 4 26.66364
2 6 19.74286
3 8 15.10000
means = means[order(means$x,decreasing = TRUE),]
means
Group.1 x
1 4 26.66364
2 6 19.74286
3 8 15.10000
barplot(means$x,names.arg=means$Group.1)
title("Mean Rate")
lines(means$x,)
opar = par(no.readonly=TRUE)
par(mar=c(5,8,4,2))
par(las=1)
counts = table(cyl)
barplot(counts,
main="mtcars cyl",
horiz=TRUE,
cex.names=2,
names.arg=names(table(cyl)))
par(opar)
棘状图
library(vcd)
counts = table(cyl,gear)
counts
gear
cyl 3 4 5
4 1 8 2
6 2 4 1
8 12 0 2
spine(counts,main="Spinogram Example")
饼图
par(mfrow=c(2,2))
slices = c(10,12.4,16,8)
labels = c("1","2","3","4")
pie(slices,labels)
pct = round(slices/sum(slices)*100)
pct
[1] 22 27 34 17
labels = paste(labels," ",pct,"%",sep="")
labels
[1] "1 22%" "2 27%" "3 34%" "4 17%"
pie(slices,labels,col=rainbow(length(pct)))
library(plotrix)
pie3D(slices,labels=labels,explode=0.1)
counts = table(cyl)
counts
cyl
4 6 8
11 7 14
lbls = paste(names(counts),"\n",counts,sep="")
lbls
[1] "4\n11" "6\n7" "8\n14"
pie(counts,labels=lbls)
par(opar)
扇形图
library(plotrix)
fan.plot(slices,labels=labels)
par(opar)
直方图
par(mfrow=c(2,2))
#1
hist(mpg)
#2 add breaks and color
hist(mpg,
breaks=12,
col="red",
)
#3 add jitter, plot according to density rather than frequency
hist(mpg,
breaks=12,
col="red",
freq=FALSE
)
rug(jitter(mpg))
lines(density(mpg),col="blue",lwd=2)
#4 add norm curve and framework
x = mpg
h = hist(mpg,
breaks=12,
col="red",
)
xfit = seq(min(x),max(x),length=40)
yfit = dnorm(xfit,mean=mean(x),sd=sd(x))
yfit1 = yfit*diff(h$mids[1:2])*length(x)
lines(xfit,yfit1,col="blue",lwd=2)
box()
par(opar)
核密度图
plot(density(mpg))
par(mfrow=c(2,1))
d = density(mpg)
plot(d)
plot(d)
polygon(d,