1.条形图

1.1 条形图

library(vcd)
## Loading required package: grid
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
str(Arthritis)
## 'data.frame':    84 obs. of  5 variables:
##  $ ID       : int  57 46 77 17 36 23 75 39 33 55 ...
##  $ Treatment: Factor w/ 2 levels "Placebo","Treated": 2 2 2 2 2 2 2 2 2 2 ...
##  $ Sex      : Factor w/ 2 levels "Female","Male": 2 2 2 2 2 2 2 2 2 2 ...
##  $ Age      : int  27 29 30 32 46 58 59 59 63 63 ...
##  $ Improved : Ord.factor w/ 3 levels "None"<"Some"<..: 2 1 1 3 3 3 1 3 1 1 ...
counts <- table(Arthritis$Improved)
counts
## 
##   None   Some Marked 
##     42     14     28
par(mfrow=c(1,2))
barplot(counts,
        main="Simple Bar Plot",
        xlab="Improvement",ylab="Frequency") #简单条形图
barplot(counts,
        main="Horizontal Bar Plot",
        xlab="Frequency",ylab="Improvement",
        horiz=TRUE)                          #水平条形图

小提示:若要绘制的类别型变量是一个因子或有序型因子,就可以使用函数plot()快速创建一幅垂直条形图。由于Arthritis$Improved是一个因子,所以无需使用table()函数将其表格化:

par(mfrow=c(1,2))
plot(Arthritis$Improved,
     main="Simple Bar Plot",
     xlab="Improvement",ylab="Frequency")
plot(Arthritis$Improved,
     main="Horizontal Bar Plot",
     xlab="Frequency",ylab="Improvement",
     horiz=TRUE)

1.2 堆砌条形图和分组条形图

counts <- table(Arthritis$Improved,Arthritis$Treatment)
counts
##         
##          Placebo Treated
##   None        29      13
##   Some         7       7
##   Marked       7      21
par(mfrow=c(1,2))
barplot(counts,
        main="Stacked Bar Plot",
        xlab="Treatment",ylab="Frequency",
        col=c("red","yellow","green"),
        legend=rownames(counts))                 #堆砌条形图
barplot(counts,
        main="Grouped Bar Plot",
        xlab="Treatment",ylab="Frequency",
        col=c("red","yellow","green"),
        legend=rownames(counts),beside=TRUE)     #分组条形图

1.3 均值条形图

states <- data.frame(state.region,state.x77)
str(states)
## 'data.frame':    50 obs. of  9 variables:
##  $ state.region: Factor w/ 4 levels "Northeast","South",..: 2 4 4 2 4 4 1 2 2 2 ...
##  $ Population  : num  3615 365 2212 2110 21198 ...
##  $ Income      : num  3624 6315 4530 3378 5114 ...
##  $ Illiteracy  : num  2.1 1.5 1.8 1.9 1.1 0.7 1.1 0.9 1.3 2 ...
##  $ Life.Exp    : num  69 69.3 70.5 70.7 71.7 ...
##  $ Murder      : num  15.1 11.3 7.8 10.1 10.3 6.8 3.1 6.2 10.7 13.9 ...
##  $ HS.Grad     : num  41.3 66.7 58.1 39.9 62.6 63.9 56 54.6 52.6 40.6 ...
##  $ Frost       : num  20 152 15 65 20 166 139 103 11 60 ...
##  $ Area        : num  50708 566432 113417 51945 156361 ...
means <- aggregate(states$Illiteracy, by=list(state.region), FUN=mean)
means
##         Group.1        x
## 1     Northeast 1.000000
## 2         South 1.737500
## 3 North Central 0.700000
## 4          West 1.023077
means <- means[order(means$x),]
means
##         Group.1        x
## 3 North Central 0.700000
## 1     Northeast 1.000000
## 4          West 1.023077
## 2         South 1.737500
barplot(means$x, names.arg=means$Group.1)
title("Mean Illiteracy Rate")

1.4 条形图的微调

par(mar=c(10,8,4,2))
par(las=2)
counts <- table(Arthritis$Improved)
barplot(counts,main="Treatment Outcome",
        horiz=TRUE,cex.names=0.8,
        names.arg=c("No Improvement","Some Improvement","Marked Improvement"))

las=2旋转了条形的标签,names.arg修改了标签文本,mar增加了边界的大小,cex.names改变字体大小。

1.5 棘状图

library(vcd)
attach(Arthritis)
counts <- table(Treatment, Improved)
spine(counts, main = "Spinogram Example")

detach(Arthritis)
2.饼图

2.1 饼图

par(mfrow=c(2,2))

slices <- c(10,12,4,16,8)
lbls <- c("US","UK","Australia","Germany","France")
pie(slices,labels=lbls,main="Simple Pie Chart")

pct <- round(slices/sum(slices)*100)
lbls2 <- paste(lbls," ",pct,"%",sep="")
pie(slices,labels=lbls2,col=rainbow(length(lbls2)),
    main="Pie Chart With Percentages")

library(plotrix)
pie3D(slices,labels=lbls,explode=0.1,
      main="3D Pie Chart")

mytable <- table(state.region)
lbls3 <- paste(names(mytable),"\n",mytable,sep="")
pie(mytable,labels=lbls3,
    main="Pie Chart from a Table\n (with sample sizes)")

2.2 扇形图

library(plotrix)
par(mfrow=c(1,1))
fan.plot(slices,labels=lbls,main="Fan Plot")

3.直方图
par(mfrow=c(2,2))
hist(mtcars$mpg)

hist(mtcars$mpg,breaks=12,col="red",xlab="Miles Per Gallon",
     main="colored histogram with 12 bins")

hist(mtcars$mpg,freq=FALSE,breaks=12,col="red",xlab="Miles Per Gallon",
     main="Histogram, rug plot, density curve")
rug(jitter(mtcars$mpg))
lines(density(mtcars$mpg),col="blue",lwd=2)

x <- mtcars$mpg
h <- hist(x,breaks=12,col="red",xlab="Miles Per Gallon",
          main="Histogram with normal curve and box")
xfit <- seq(min(x),max(x),length=40)
yfit <- dnorm(xfit,mean=mean(x),sd=sd(x))
yfit <- yfit*diff(h$mids[1:2])*length(x)
lines(xfit,yfit,col="blue",lwd=2)
box()

4.核密度图
par(mfrow=c(1,2))
d <- density(mtcars$mpg)
plot(d)

plot(d,main="Kernel Density of Miles Per Gallon")
polygon(d,col="red",border="blue")  #多边形
rug(mtcars$mpg,col="brown")         #轴须图

#可比较的核密度图
par(mfrow=c(1,1))
par(lwd=2)
library(sm)
## Package 'sm', version 2.2-5.6: type help(sm) for summary information
attach(mtcars)
cyl.f <- factor(cyl,levels=c(4,6,8),labels=c("4 cylinder","6 cylinder","8 cylinder")) #创建分组因子
sm.density.compare(mpg,cyl,xlab="Miles Per Gallon")
title(main="MPG Distribution by Car Cylinders")
colfill <- c(2:(1+length(levels(cyl.f))))
legend("topright",levels(cyl.f),fill=colfill)#legend(locator(1),levels(cyl.f),fill=colfill) 通过鼠标单击添加图例

detach(mtcars)
5.箱线图
par(mfrow=c(1,2))
boxplot(mpg~cyl,data=mtcars,
        main="Car Mileage Data",
        xlab="Number of Cylinders",
        ylab="Miles Per Gallon")

#含凹槽的箱线图
boxplot(mpg~cyl,data=mtcars,
        notch=TRUE,     #带凹槽的箱线图
        varwidth=TRUE,  #宽度与各自的样本大小成正比
        col="red",
        main="Car Mileage Data",
        xlab="Number of Cylinders",
        ylab="Miles Per Gallon")
## Warning in bxp(list(stats = structure(c(21.4, 22.8, 26, 30.4, 33.9, 17.8, :
## some notches went outside hinges ('box'): maybe set notch=FALSE

#两个交叉因子的箱线图
par(mfrow=c(1,1))
mtcars$cyl.f <- factor(mtcars$cyl,
                       levels=c(4,6,8),
                       labels=c("4","6","8"))
mtcars$am.f <- factor(mtcars$am,
                      levels=c(0,1),
                      labels=c("auto","standard"))
boxplot(mpg~am.f*cyl.f,
        data=mtcars,
        varwidth=TRUE,
        col=c("gold","darkgreen"),
        main="MPG Distribution by Auto Type",
        xlab="Auto Type")

6.小提琴图
library(vioplot)
x1 <- mtcars$mpg[mtcars$cyl==4]
x2 <- mtcars$mpg[mtcars$cyl==6]
x3 <- mtcars$mpg[mtcars$cyl==8]
vioplot(x1,x2,x3,names=c("4 cyl","6 cyl","8 cyl"),col="gold")
title("Violin Plots of Miles Per Gallon")

7.点图
dotchart(mtcars$mpg,labels=row.names(mtcars),cex=0.7,
         main="Gas Mileage for Car Models",
         xlab="Miles Per Gallon")

#分组、排序、着色后的点图
x <- mtcars[order(mtcars$mpg),]
x$cyl <- factor(x$cyl)
x$color[x$cyl==4] <- "red"
x$color[x$cyl==6] <- "blue"
x$color[x$cyl==8] <- "darkgreen"
dotchart(x$mpg,labels=row.names(x),
         cex=0.7,
         groups=x$cyl,
         gcolor="black",
         color=x$color,
         pch=19,
         main="Gas Mileage for Car Models\ngrouped by cylinder",
         xlab="Miles Per Gallon"
         )