R绘图基础(6)各类图型

1、点,线,面

点:points,线:abline,lines,segments,面:box,polygon,polypath,rect,特殊的:arrows,symbols

points不仅仅可以画前文中pch所设定的任意一个符号,还可以以字符为符号。

  1. > ## ------------ test code for various pch specifications -------------
  2. > # Try this in various font families (including Hershey)
  3. > # and locales. Use sign=-1 asserts we want Latin-1.
  4. > # Standard cases in a MBCS locale will not plot the top half.
  5. > TestChars <- function(sign=1, font=1, ...)
  6. + {
  7. + if(font == 5) { sign <- 1; r <- c(32:126, 160:254)
  8. + } else if (l10n_info()$MBCS) r <- 32:126 else r <- 32:255
  9. + if (sign == -1) r <- c(32:126, 160:255)
  10. + par(pty="s")
  11. + plot(c(-1,16), c(-1,16), type="n", xlab="", ylab="",
  12. + xaxs="i", yaxs="i")
  13. + grid(17, 17, lty=1)
  14. + for(i in r) try(points(i%%16, i%/%16, pch=sign*i, font=font,...))
  15. + }
  16. > TestChars()
  17. > try(TestChars(sign=-1))

R绘图基础(6)各类图型-图片1

画点

abline可以由斜率和截距来确定一条直线,lines可以连接两个或者多个点,segments可以按起止位置画线。

  1. > require(stats)
  2. > sale5 <- c(6, 4, 9, 7, 6, 12, 8, 10, 9, 13)
  3. > plot(sale5,new=T)
  4. > abline(lsfit(1:10,sale5))
  5. > abline(lsfit(1:10,sale5, intercept = FALSE), col= 4)
  6. > abline(h=6, v=8, col = "gray60")
  7. > text(8,6, "abline( h = 6 )", col = "gray60", adj = c(0, -.1))
  8. > abline(h = 4:8, v = 6:12, col = "lightgray", lty=3)
  9. > abline(a=1, b=2, col = 2)
  10. > text(5,11, "abline( 1, 2 )", col=2, adj=c(-.1,-.1))
  11. > segments(6,4,9,5,col="green")
  12. > text(6,5,"segments(6,4,9,5)")
  13. > lines(sale5,col="pink")

R绘图基础(6)各类图型-图片2

线段

box画出当前盒子的边界,polygon画多边形,polypath画路径,rect画距形。

  1. > x <- c(1:9,8:1)
  2. > y <- c(1,2*(5:3),2,-1,17,9,8,2:9)
  3. > op <- par(mfcol=c(3,1))
  4. > for(xpd in c(FALSE,TRUE,NA)) {
  5. + plot(1:10, main = paste("xpd =", xpd))
  6. + box("figure", col = "pink", lwd=3)
  7. + polygon(x,y, xpd=xpd, col="orange", lty=2, lwd=2, border="red")
  8. + }
  9. > par(op)
  10. > plotPath <- function(x, y, col = "grey", rule = "winding") {
  11. + plot.new()
  12. + plot.window(range(x, na.rm = TRUE), range(y, na.rm = TRUE))
  13. + polypath(x, y, col = col, rule = rule)
  14. + if (!is.na(col))
  15. + mtext(paste("Rule:", rule), side = 1, line = 0)
  16. + }
  17. >
  18. > plotRules <- function(x, y, title) {
  19. + plotPath(x, y)
  20. + plotPath(x, y, rule = "evenodd")
  21. + mtext(title, side = 3, line = 0)
  22. + plotPath(x, y, col = NA)
  23. + }
  24. >
  25. > op <- par(mfrow = c(5, 3), mar = c(2, 1, 1, 1))
  26. >
  27. > plotRules(c(.1, .1, .9, .9, NA, .2, .2, .8, .8),
  28. + c(.1, .9, .9, .1, NA, .2, .8, .8, .2),
  29. + "Nested rectangles, both clockwise")
  30. > plotRules(c(.1, .1, .9, .9, NA, .2, .8, .8, .2),
  31. + c(.1, .9, .9, .1, NA, .2, .2, .8, .8),
  32. + "Nested rectangles, outer clockwise, inner anti-clockwise")
  33. > plotRules(c(.1, .1, .4, .4, NA, .6, .9, .9, .6),
  34. + c(.1, .4, .4, .1, NA, .6, .6, .9, .9),
  35. + "Disjoint rectangles")
  36. > plotRules(c(.1, .1, .6, .6, NA, .4, .4, .9, .9),
  37. + c(.1, .6, .6, .1, NA, .4, .9, .9, .4),
  38. + "Overlapping rectangles, both clockwise")
  39. > plotRules(c(.1, .1, .6, .6, NA, .4, .9, .9, .4),
  40. + c(.1, .6, .6, .1, NA, .4, .4, .9, .9),
  41. + "Overlapping rectangles, one clockwise, other anti-clockwise")
  42. >
  43. > par(op)
  44. > require(grDevices)
  45. > ## set up the plot region:
  46. > op <- par(bg = "thistle")
  47. > plot(c(100, 250), c(300, 450), type = "n", xlab="", ylab="",
  48. + main = "2 x 11 rectangles; 'rect(100+i,300+i, 150+i,380+i)'")
  49. > i <- 4*(0:10)
  50. > ## draw rectangles with bottom left (100, 300)+i
  51. > ## and top right (150, 380)+i
  52. > rect(100+i, 300+i, 150+i, 380+i, col=rainbow(11, start=.7,end=.1))
  53. > rect(240-i, 320+i, 250-i, 410+i, col=heat.colors(11), lwd=i/5)
  54. > ## Background alternating ( transparent / "bg" ) :
  55. > j <- 10*(0:5)
  56. > rect(125+j, 360+j, 141+j, 405+j/2, col = c(NA,0),
  57. + border = "gold", lwd = 2)
  58. > rect(125+j, 296+j/2, 141+j, 331+j/5, col = c(NA,"midnightblue"))
  59. > mtext("+ 2 x 6 rect(*, col = c(NA,0)) and col = c(NA,\"m..blue\"))")

R绘图基础(6)各类图型-图片3

多边形

R绘图基础(6)各类图型-图片4

路径

R绘图基础(6)各类图型-图片5

矩形

arrows用于画箭头,symbols用于画符号

  1. > ## Note that example(trees) shows more sensible plots!
  2. > N <- nrow(trees)
  3. > with(trees, {
  4. + ## Girth is diameter in inches
  5. + symbols(Height, Volume, circles = Girth/24, inches = FALSE,
  6. + main = "Trees' Girth") # xlab and ylab automatically
  7. + ## Colours too:
  8. + op <- palette(rainbow(N, end = 0.9))
  9. + symbols(Height, Volume, circles = Girth/16, inches = FALSE, bg = 1:N,
  10. + fg = "gray30", main = "symbols(*, circles = Girth/16, bg = 1:N)")
  11. + palette(op)
  12. + })

R绘图基础(6)各类图型-图片6

符号

画圆

  1. > library(plotrix)
  2. > plot(1:5,seq(1,10,length=5),type="n",xlab="",ylab="",main="Test draw.circle")
  3. > draw.circle(2,4,c(1,0.66,0.33),border="purple",
  4. + col=c("#ff00ff","#ff77ff","#ffccff"),lty=1,lwd=1)
  5. > draw.circle(2.5,8,0.6,border="red",lty=3,lwd=3)
  6. > draw.circle(4,3,0.7,border="green",lty=1,lwd=1)
  7. > draw.circle(3.5,7,0.8,border="blue",lty=2,lwd=2)

R绘图基础(6)各类图型-图片7

2、散点图及趋势线

一维点图使用dotchart函数。

  1. > # Dotplot: Grouped Sorted and Colored
  2. > # Sort by mpg, group and color by cylinder
  3. > x <- mtcars[order(mtcars$mpg),] # sort by mpg
  4. > x$cyl <- factor(x$cyl) # it must be a factor
  5. > x$color[x$cyl==4] <- "red"
  6. > x$color[x$cyl==6] <- "blue"
  7. > x$color[x$cyl==8] <- "darkgreen"
  8. > dotchart(x$mpg,labels=row.names(x),cex=.7,groups= x$cyl,
  9. + main="Gas Milage for Car Models\ngrouped by cylinder",
  10. + xlab="Miles Per Gallon", gcolor="black", color=x$color)

R绘图基础(6)各类图型-图片8

一维点图

二维散点图使用plot函数。直趋势线使用abline函数,拟合曲线在拟合后使用line函数绘制。

  1. > attach(mtcars)
  2. > plot(wt, mpg, main="Scatterplot Example",
  3. + xlab="Car Weight ", ylab="Miles Per Gallon ", pch=19)
  4. > # Add fit lines
  5. > abline(lm(mpg~wt), col="red") # regression line (y~x)
  6. > lines(lowess(wt,mpg), col="blue") # lowess line (x,y)

R绘图基础(6)各类图型-图片9

点阵图

3、曲线

曲线使用lines函数。其type参数可以使用”p”,”l”,”o”,”b,c”,”s,S”,”h”,”n”等。

  1. > x <- c(1:5); y <- x # create some data
  2. > par(pch=22, col="blue") # plotting symbol and color
  3. > par(mfrow=c(2,4)) # all plots on one page
  4. > opts = c("p","l","o","b","c","s","S","h")
  5. > for(i in 1:length(opts)){
  6. + heading = paste("type=",opts[i])
  7. + plot(x, y, main=heading)
  8. + lines(x, y, type=opts[i])
  9. + }

R绘图基础(6)各类图型-图片10

曲线

4、柱状图

普通的柱状图使用barplot函数。其参数horiz=TRUE表示水平画图,beside=TRUE表示如果是多组数据的话,在并排画图,否则原位堆叠画图。

  1. > par(mfrow=c(1,2))
  2. > counts <- table(mtcars$vs, mtcars$gear)
  3. > barplot(counts, main="Car Distribution by Gears and VS",
  4. + xlab="Number of Gears", col=c("darkblue","red"),
  5. + legend = rownames(counts),horiz=TRUE)
  6. > barplot(counts, main="Car Distribution by Gears and VS",
  7. + xlab="Number of Gears", col=c("darkblue","red"),
  8. + legend = rownames(counts), beside=TRUE)

R绘图基础(6)各类图型-图片11

bar图

柱状统计图使用hist函数。其breaks参数设置每组的范围。使用density函数可以拟合曲线。

  1. > hist(mtcars$mpg, breaks=12)
  2. > dens<-density(mtcars$mpg)
  3. > lines(dens$x,dens$y*100,col="red")

R绘图基础(6)各类图型-图片12

柱状图

5、饼图

饼图使用pie函数。

  1. > x<-table(mtcars$gear)
  2. > pie(x,label=paste("gear=",rownames(x),sep=""))

R绘图基础(6)各类图型-图片13

饼图

3维饼图使用plotrix库中的pie3D函数。

  1. > x<-table(mtcars$gear)
  2. > pie3D(x,labels=paste("gear=",rownames(x),sep=""),explode=0.1)

R绘图基础(6)各类图型-图片14

3D饼图

6、箱线图

箱线图使用boxplot函数。boxplot中参数x为公式。R中的公式如何定义呢?最简单的 y ~ x 就是y是x的一次函数。好了,下面就是相关的符号代表的意思:

符号示例意义
++x包括该变量
-x不包括该变量
:x:z包括两变量的相互关系
*x*z包括两变量,以及它们之间的相互关系
/x/znesting: include z nested within x
|x|z条件或分组:包括指定z的x
^(u+v+w)^3include these variables and all interactions up to three way
polypoly(x,3)polynomial regression: orthogonal polynomials
ErrorError(a/b)specify the error term
II(x*z)as is: include a new variable consisting of these variables multiplied
1-1截距:减去该截距
  1. > boxplot(mpg~cyl,data=mtcars, main="Car Milage Data",
  2. + xlab="Number of Cylinders", ylab="Miles Per Gallon")
  3. > boxplot(len~supp*dose, data=ToothGrowth, notch=TRUE,
  4. + col=(c("gold","darkgreen")),
  5. + main="Tooth Growth", xlab="Suppliment and Dose")

R绘图基础(6)各类图型-图片15

箱线图

如果我想在箱线图上叠加样品点,即所谓的蜂群图,如何做呢?

  1. > source("http://bioconductor.org/biocLite.R")
  2. > biocLite(c("beeswarm","ggplot2"))
  3. > library(beeswarm)
  4. > library(ggplot2)
  5. > data(breast)
  6. > beeswarm <- beeswarm(time_survival ~ event_survival,
  7. + data = breast, method = 'swarm',
  8. + pwcol = ER)[, c(1, 2, 4, 6)]
  9. > colnames(beeswarm) <- c("x", "y", "ER", "event_survival")
  10. >
  11. > beeswarm.plot <- ggplot(beeswarm, aes(x, y)) +
  12. + xlab("") +
  13. + scale_y_continuous(expression("Follow-up time (months)"))
  14. > beeswarm.plot2 <- beeswarm.plot + geom_boxplot(aes(x, y,
  15. + group = round(x)), outlier.shape = NA)
  16. > beeswarm.plot3 <- beeswarm.plot2 + geom_point(aes(colour = ER)) +
  17. + scale_colour_manual(values = c("black", "red")) +
  18. + scale_x_continuous(breaks = c(1:2),
  19. + labels = c("Censored", "Metastasis"), expand = c(0, 0.5))
  20. > print(beeswarm.plot3)

R绘图基础(6)各类图型-图片16

蜂群图

  1. > require(beeswarm)
  2. > data(breast)
  3. >
  4. > beeswarm(time_survival ~ event_survival, data = breast,
  5. + method = 'swarm',
  6. + pch = 16, pwcol = as.numeric(ER),
  7. + xlab = '', ylab = 'Follow-up time (months)',
  8. + labels = c('Censored', 'Metastasis'))
  9. >
  10. > boxplot(time_survival ~ event_survival,
  11. + data = breast, add = T,
  12. + names = c("",""), col="#0000ff22")

R绘图基础(6)各类图型-图片17

蜂群图

7、分枝树

  1. > require(graphics)
  2. > opar<-par(mfrow=c(2,1),mar=c(4,3,0.5,0.5))
  3. > hc <- hclust(dist(USArrests), "ave")
  4. > plot(hc,main="")
  5. > plot(hc, hang = -1,main="")
  6. > par(opar)

R绘图基础(6)各类图型-图片18

分枝树

8、文氏图

  1. > library(limma)
  2. > Y <- matrix(rnorm(100*6),100,6)
  3. > Y[1:10,3:4] <- Y[1:10,3:4]+3
  4. > Y[1:20,5:6] <- Y[1:20,5:6]+3
  5. > design <- cbind(1,c(0,0,1,1,0,0),c(0,0,0,0,1,1))
  6. > fit <- eBayes(lmFit(Y,design))
  7. > results <- decideTests(fit)
  8. > a <- vennCounts(results)
  9. > print(a)
  10. x1 x2 x3 Counts
  11. [1,] 0 0 0 89
  12. [2,] 0 0 1 11
  13. [3,] 0 1 0 0
  14. [4,] 0 1 1 0
  15. [5,] 1 0 0 0
  16. [6,] 1 0 1 0
  17. [7,] 1 1 0 0
  18. [8,] 1 1 1 0
  19. attr(,"class")
  20. [1] "VennCounts"
  21. > vennDiagram(a)
  22. > vennDiagram(results,include=c("up","down"),counts.col=c("red","green"))

R绘图基础(6)各类图型-图片19

文氏图

发表评论

匿名网友

拖动滑块以完成验证
加载失败