更新于 

图形功能

高级绘图函数

向日葵花型图

sunflowerplot

以相似坐标的点作为花朵,其花瓣数目为点的个数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
## my understand
x <- rep(2, 10);y <- rep(2, 10)
sunflowerplot(x, y)

x <- rep(2, 10);y <- rep(3, 10)
sunflowerplot(x, y)

x <- rep(1:5, 5); y <- rep(3, 25)
sunflowerplot(x, y)


## 实例
require(stats) # for rnorm
require(grDevices)

## 'number' is computed automatically:
sunflowerplot(iris[, 3:4])
## Imitating Chambers et al, p.109, closely:
sunflowerplot(iris[, 3:4], cex = .2, cex.fact = 1, size = .035, seg.lwd = .8)
## or
sunflowerplot(Petal.Width ~ Petal.Length, data = iris,
cex = .2, cex.fact = 1, size = .035, seg.lwd = .8)

sunflowerplot(x = sort(2*round(rnorm(100))), y = round(rnorm(100), 0),
main = "Sunflower Plot of Rounded N(0,1)")
## Similarly using a "xyTable" argument:
xyT <- xyTable(x = sort(2*round(rnorm(100))), y = round(rnorm(100), 0),
digits = 3)
utils::str(xyT, vec.len = 20)
sunflowerplot(xyT, main = "2nd Sunflower Plot of Rounded N(0,1)")

## A 'marked point process' {explicit 'number' argument}:
sunflowerplot(rnorm(100), rnorm(100), number = rpois(n = 100, lambda = 2),
main = "Sunflower plot (marked point process)",
rotate = TRUE, col = "blue4")

饼图、箱图

饼图不宜多用,一般用于比较各部分的占比情况

箱图常用于同一类数据的比较,可以看到数据分布和数据量,有横向和纵向两种。

对于图像的颜色填充可使用rainbow()设定

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
require(grDevices)
pie(rep(1, 24), col = rainbow(24), radius = 1)

pie.sales <- c(0.12, 0.3, 0.26, 0.16, 0.04, 0.12)
names(pie.sales)<-c("Blueberry","Cherry","Apple", "Boston Cream", "Other", "Vanilla Cream")
pie(pie.sales) # default colours

pie(pie.sales, density = 10, angle = 15 + 10 * 1:6)

pie(pie.sales, clockwise = TRUE, main = "pie(*, clockwise = TRUE)")

segments(0, 0, 0, 1, col = "red", lwd = 2)
text(0, 1, "init.angle = 90", col = "red")

## 另一个例子

par(mfrow = c(2,2))
slices <- c(10,12,4,16,8) # 数据
lbls <- c("US","UK","Australis","Germany","France") # 标签数据
pie(slices,lbls) # 基本饼图

pct <- round(slices/sum(slices)*100) # 数据比例
lbls2 <- paste(lbls," ",pct ,"%",sep = "")
pie(slices,labels = lbls2,col = rainbow(length(lbls2)), # rainbow是一个彩虹色调色板
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")

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
boxplot(mtcars$mpg,main="Box plot",
ylab ="Miles per Gallon") # 标准箱线图

boxplot(mpg ~ cyl,data= mtcars,
main="car milesge data",
xlab= "Number of cylinders",
ylab= "Miles per Gallon")

boxplot(mpg ~ cyl,data= mtcars,
notch=TRUE, # 含有凹槽的箱线图
varwidth = TRUE, # 宽度和样本大小成正比
col= "red",
main="car milesge data",
xlab= "Number of cylinders",
ylab= "Miles per Gallon")

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",
ylxb="Miles per Gallon")


boxplot(len ~ dose, data = ToothGrowth,
boxwex = 0.25, at = 1:3 - 0.2,
subset = supp == "VC", col = "yellow",
main = "Guinea Pigs' Tooth Growth",
xlab = "Vitamin C dose mg",
ylab = "tooth length",
xlim = c(0.5, 3.5), ylim = c(0, 35),
yaxs = "i")


boxplot(len ~ dose, data = ToothGrowth, add = TRUE,
boxwex = 0.25, at = 1:3 + 0.2,
subset = supp == "OJ", col = "orange")
legend(2, 9, c("Ascorbic acid", "Orange juice"),
fill = c("yellow", "orange"))


boxplot(len ~ dose:supp, data = ToothGrowth,
boxwex = 0.5, col = c("orange", "yellow"),
main = "Guinea Pigs' Tooth Growth",
xlab = "Vitamin C dose mg", ylab = "tooth length",
sep = ":", lex.order = TRUE,
ylim = c(0, 35), yaxs = "i")

stripchart() 将x画在一条直线上

对于数据量较小时可以作为箱型图的替代

stripchart(x, data = NULL, dlab = NULL, ...,subset, na.action = NULL)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
x <- stats::rnorm(50)
xr <- round(x, 1)
stripchart(x) ; m <- mean(par("usr")[1:2])
text(m, 1.04, "stripchart(x, \"overplot\")")
stripchart(xr, method = "stack", add = TRUE, at = 1.2)
text(m, 1.35, "stripchart(round(x,1), \"stack\")")
stripchart(xr, method = "jitter", add = TRUE, at = 0.7)
text(m, 0.85, "stripchart(round(x,1), \"jitter\")")

stripchart(decrease ~ treatment,
main = "stripchart(OrchardSprays)",
vertical = TRUE, log = "y", data = OrchardSprays)

stripchart(decrease ~ treatment, at = c(1:8)^2,
main = "stripchart(OrchardSprays)",
vertical = TRUE, log = "y", data = OrchardSprays)

coplot(x~y|z)给定z绘制(x,y)的散点图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
## Tonga Trench Earthquakes
coplot(lat ~ long | depth, data = quakes)
given.depth <- co.intervals(quakes$depth, number = 4, overlap = .1)
coplot(lat ~ long | depth, data = quakes, given.v = given.depth, rows = 1)

## Conditioning on 2 variables:
ll.dm <- lat ~ long | depth * mag
coplot(ll.dm, data = quakes)
coplot(ll.dm, data = quakes, number = c(4, 7), show.given = c(TRUE, FALSE))
coplot(ll.dm, data = quakes, number = c(3, 7),
overlap = c(-.5, .1)) # negative overlap DROPS values

## given two factors
Index <- seq(length = nrow(warpbreaks)) # to get nicer default labels
coplot(breaks ~ Index | wool * tension, data = warpbreaks,
show.given = 0:1)
coplot(breaks ~ Index | wool * tension, data = warpbreaks,
col = "red", bg = "pink", pch = 21,
bar.bg = c(fac = "light blue"))

## Example with empty panels:

win.graph()
with(data.frame(state.x77), {
coplot(Life.Exp ~ Income | Illiteracy * state.region, number = 3,
panel = function(x, y, ...) panel.smooth(x, y, span = .8, ...))
## y ~ factor -- not really sensible, but 'show off':
coplot(Life.Exp ~ state.region | Income * state.division,
panel = panel.smooth)
})

interaction.plot(f1, f2, y, fun=mean)

以f1(因子)为横坐标,fun(y|f2)为纵坐标绘制相应的f2(因子)的图像

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
require(graphics)

with(ToothGrowth, {
interaction.plot(dose, supp, len, fixed = TRUE)
dose <- ordered(dose)
interaction.plot(dose, supp, len, fixed = TRUE, col = 2:3, leg.bty = "o")
interaction.plot(dose, supp, len, fixed = TRUE, col = 2:3, type = "p")
})

with(OrchardSprays, {
interaction.plot(treatment, rowpos, decrease)
interaction.plot(rowpos, treatment, decrease, cex.axis = 0.8)
## order the rows by their mean effect
rowpos <- factor(rowpos,
levels = sort.list(tapply(decrease, rowpos, mean)))
interaction.plot(rowpos, treatment, decrease, col = 2:9, lty = 1)
})

matplot()

二元图,x的第一列对应y的第一列,以此类推绘制图像

1
2
3
4
5
x <- matrix(rep(1:10, 5), ncol = 5)
y <- matrix(seq(50), ncol = 5)

matplot(x, y, type = "l", lty = 1:5, col=rainbow(30), lwd = 2)

dotchar(x)

x为数据框,点图(逐行逐列累加图)

dotchart(x, labels = NULL, groups = NULL, gdata = NULL,cex = par("cex"), pt.cex = cex,pch = 21, gpch = 21, bg = par("bg"),color = par("fg"), gcolor = par("fg"),lcolor = "gray",xlim = range(x[is.finite(x)]), main = NULL, xlab = NULL, ylab = NULL, ...)

具体可参见:

https://blog.csdn.net/moxigandashu/article/details/53383041

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
## 例1
dotchart(VADeaths, main = "Death Rates in Virginia - 1940")
op <- par(xaxs = "i") # 0 -- 100%
dotchart(t(VADeaths), xlim = c(0,100),
main = "Death Rates in Virginia - 1940")
par(op)


## 例2
dotchart(mtcars$mpg,labels = row.names(mtcars),cex= .7,
main = "Gas Mileage for Car Models",
xlab = "Miles Per gallon")

x <- mtcars[order(mtcars$mpg),] #按照mpg排序
x$cyl <-factor(x$cyl) #将cyl变成因子数据结构类型
x$color[x$cyl==4] <-"red" #新建一个color变量,油缸数cyl不同,颜色不同
x$color[x$cyl==6] <-"blue"
x$color[x$cyl==8] <-"darkgreen"
dotchart(x$mpg, #数据对象
labels = row.names(x), #标签
cex = .7,#字体大小
groups = x$cyl, #按照cyl分组
gcolor = "black", #分组颜色
color = x$color, #数据点颜色
pch = 19,#点类型
main = "Gas Mileage for car modes \n grouped by cylinder", #标题
xlab = "miles per gallon") #x轴标签

pairs(x)

1
2
3
4
## 基础用法
pairs(iris[1:4], main = "Anderson's Iris Data -- 3 species",
pch = 21, bg = c("red", "green3", "blue")[unclass(iris$Species)])

直方图

hist(x, ...)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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 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() # 添加方框

条形图

barplot()

1
2
3
4
5
6
7
8
9
10
11
12
library(vcd)
counts <- table(Arthritis$Improved)
## 引入vcd包只是想要Arthritis中的数据
barplot(counts,main = "bar plot",xlab = "improved",ylab = "counts")

barplot(counts,main = " horizontal bar plot",
xlab = "frequency",
ylab = "improved",
horiz = TRUE)
## horizon值默认是FALSE,为TRUE的时候表示图形变为水平的


星图 stars()

stars(x,full=TRUE,scale=TRUE,key.loc=NULL,draw.segments=FALSE,…)

参数x是矩阵或者是数据框,按照矩阵的行变量进行绘制。对每个标准量单独标准化之后绘制星图。draw.segments=TRUE制定画出弧形

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
x <- c(-1.9,-12.7,5.7,6.6,0.3,4.2,15.8,18.5,7.8,10.8,
-0.9,-8.1,5.6,6.5,3.9,5.81,7.3,20.5,9.0,13.2,
8.0,0.5,11.1,12.7,11.5,12.8,17.9,21.8,13.3,15.9,
13.5,8.0,16.6,19.3,17.1,19.0,23.6,26.7,19.2,18.0,
20.4,18.3,20.8,22.7,21.8,23.9,25.3,28.3,22.9,18.0,
25.9,21.6,25.6,26.0,27.8,28.4,27.8,29.4,25.4,20.4,
25.9,24.2,29.4,30.0,27.1,30.2,29.8,30.0,31.0,21.3,
26.4,24.3,30.2,30.0,26.1,29.7,29.4,28.5,32.4,20.6,
21.8,17.5,23.9,24.3,21.2,24.0,27.0,27.4,24.8,18.3,
16.1,11.6,22.1,22.1,19.0,21.0,26.4,27.1,20.6,16.9,
6.7,0.8,15.7,15.0,10.8,14.0,21.9,25.3,14.6,13.2,
1.0,6.7,8.2,8.1,3.0,6.8,16.0,20.8,9.4,9.8)
x <- matrix(x, ncol = 10, nrow = 12, byrow = T)
cnames <- c("北京","沈阳","上海","南昌","郑州","武汉","广州","海口","重庆","昆明")
rnames <- paste0(1:12,"月",seq="")
colnames(x) <- cnames
rownames(x) <- rnames

stars(x)
stars(x,key.loc=c(10,2,4),cex=0.8)

stars(t(x),full=FALSE,draw.segments=TRUE,key.loc=c(10,3,5),cex=0.8)

绘图选项

  1. add=FALSE :若为TRUE则叠加一个图形在前一个图上(注意坐标系的位置和尺度可能不一样)

  2. axes=TRUE :若为FALSE则不绘制轴和边框

  3. type="p" :制定图形类型(plot),“P”:点、“l”:线、“b”:点连线、“o”:点连线,线在点上、“h”:垂直线、“s”:阶梯式,垂直线顶端显示数据、“S”:阶梯式,垂直线低端显示数据

  4. xlim=,ylim=:指定轴的上下限

  5. xlab=,ylab=:坐标轴标签,必须为字符型值

  6. main=:主标题,字符型值

  7. sub: 副标题(小字体)