跳轉到內容

R 程式設計/圖形

來自華夏公益教科書

R 至少包含三個圖形系統,標準的 graphics 包,用於 Trellis 圖的 lattice[1] 以及圖形語法 ggplot2[2]。R 具有良好的圖形功能,但有一些替代方案,例如 gnuplot


互動式圖形

[edit | edit source]

本節討論了一些在不使用 R 指令碼的情況下繪製圖形的方法。

playwith 包提供了一個圖形使用者介面來定製圖形,新增標題、網格、一些文字等,它會匯出您需要的 R 程式碼,如果您想複製分析[3]。如果您想了解更多資訊,可以檢視網站上的螢幕截圖 (連結)。另請參閱“R you Ready”上的示例 [1]。此包需要 GTK+ 庫。

library("playwith")
playwith(plot(x1))

還有一個圖形使用者介面 GrapheR,它使初學者非常容易繪製圖形[4]。此解決方案是跨平臺的。

> library(GrapheR)

latticist (連結) 是另一個類似的專案。

另請注意,一些圖形使用者介面,例如 RKward 和 R Commander,使得繪製圖形變得容易。

標準 R 圖形

[edit | edit source]

在本節中,我們將介紹如果您想在預設圖形系統中定製圖形,您需要了解的內容。

  • plot() 是圖形的主要函式。引數可以是單個點,例如 0 或 c(.3,.7),單個向量,一對向量或許多其他 R 物件。
  • par() 是另一個重要的函式,它定義了繪圖的預設設定。
  • 還有許多其他繪圖函式,它們特定於某些任務,例如 hist()boxplot() 等。它們中的大多數都接受與 plot() 函式相同的引數。
> N <- 10^2
> x1 <- rnorm(N) 
> x2 <- 1 + x1 + rnorm(N)
> plot(0) 
> plot(0,1) 
> plot(x1) 
> plot(x1,x2) # scatter plot x1 on the horizontal axis and x2 on the vertical axis
> plot(x2 ~ x1) # the same but using a formula (x2 as a function of x1)
> methods(plot) # show all the available methods for plot (depending on the number of loaded packages).

標題、圖例和註釋

[edit | edit source]

標題

[edit | edit source]

main 給出主標題,sub 給出副標題。它們可以作為 plot() 函式的引數傳遞,也可以使用 title() 函式。xlab 為 x 軸的名稱,ylab 為 y 軸的名稱。

 plot(x1,x2, main = "Main title", sub = "sub title" , ylab = "Y axis", xlab = "X axis")
 plot(x1,x2 ,  ylab = "Y axis", xlab = "X axis")
 title(main = "Main title", sub = "sub title" )

文字的大小可以使用引數 cex.maincex.labcex.subcex.axis 來修改。這些引數定義了縮放因子,即引數的值乘以文字的大小。如果您選擇 cex.main=2,則主標題將是平時大小的兩倍。

圖例

[edit | edit source]

legend()。位置可以是“bottomleft”、“bottomright”、“topleft”、“topright”或精確座標。

plot(x1, type = "l", col = 1, lty = 1) 
lines(x2, col = 2, lty = 2) 
legend("bottomleft", legend = c("x1","x2"), col = 1:2, lty = 1:2)

邊距中的文字

[edit | edit source]

mtext() 將一些文字放在邊距中。邊距可以在底部 (1)、左側 (2)、頂部 (3) 或右側 (4)。

plot(x1, type = "l", col = 1, lty = 1) ; mtext("some text", side = 1) # the bottom
plot(x1, type = "l", col = 1, lty = 1) ; mtext("some text", side = 2) # the left
plot(x1, type = "l", col = 1, lty = 1) ; mtext("some text", side = 3) # the top
plot(x1, type = "l", col = 1, lty = 1) ; mtext("some text", side = 4) # the right margin

圖形中的文字

[edit | edit source]

text()

數學註釋

[edit | edit source]

我們可以使用 expression() 新增數學符號,並在公式中使用 substitute() 進行一些替換。

?plotmath # gives help for mathematical annotations

型別

[edit | edit source]

繪圖的型別可以是 

  • n 表示無(不列印任何內容),
  • p 表示點,
  • l 表示線,
  • b 表示兩者,
  • o 表示兩者疊加,
  • h 表示直方圖狀
  • 以及 s/S 表示階梯。
R 程式碼 輸出
x1 <- rnorm(50) 
png("plottype.png")
par(mfrow = c(2,2))
plot(x1, type = "p", main = "points", ylab = "", xlab = "")
plot(x1, type = "l", main = "lines", ylab = "", xlab = "")
plot(x1, type = "b", main = "both", ylab = "", xlab = "")
plot(x1, type = "o", main = "both overplot", ylab = "", xlab = "")
dev.off()
點選圖形進行縮放

預設輸出會列印軸。我們可以使用 axes=FALSE 來移除它們。我們也可以使用 axis() 函式來更改它們。

> plot(x1,x2,axes=FALSE)
>
> plot(x1,x2,axes=FALSE)
> axis(1,col="red",col.axis="blue",font.axis=3)
> axis(2,col="red",col.axis="blue",font.axis=2,las=2)

las 指定軸標籤的樣式。它可以是 0、1、2 或 3。

  • 0 : 始終平行於軸 [預設],
  • 1 : 始終水平,
  • 2 : 始終垂直於軸,
  • 3 : 始終垂直。
R 程式碼 輸出
x1 <- rnorm(100)
par(mfrow = c(2,2))
plot(x1, las = 0, main = "las = 0", sub = "always parallel to the axis", xlab = "", ylab = "")
plot(x1, las = 1, main = "las = 1", sub = "always horizontal", xlab = "", ylab = "") 
plot(x1, las = 2, main = "las = 2", sub = "always perpendicular to the axis", xlab = "", ylab = "")
plot(x1, las = 3, main = "las = 3", sub = "always vertical", xlab = "", ylab = "")
點選圖形

還可以透過新增 axis(4,) 在右側新增另一個 y 軸。

邊距

[edit | edit source]

邊距可以用英寸或行來計算。預設值為 par(mar = c(5,4,4,2)),這意味著底部有 5 行,左側有 4 行,頂部有 4 行,右側有 2 行。這可以使用 par() 函式來修改。如果您想以英寸為單位指定邊距,請使用 par(mai = c(bottom, left, top, right)。如果您想以行為單位修改邊距,請使用 par(mar = c(bottom, left, top, right)。請參閱 ?par 瞭解有關此主題的更多資訊。

可以使用col引數更改點或線的顏色,fg用於前景顏色(框和軸),bg用於背景顏色。

  • show.col(object=NULL)Hmisc)包繪製主要 R 顏色及其數字程式碼。
  • R 中所有顏色的列表 (pdf)
colors() # list the r colors
show.col(object=NULL) # graphs the main R colors
plot(x1, col = "blue")
plot(x1, col = "red")
plot(x1, col = "red", col.axis = "dodgerblue", col.lab = "firebrick", col.main = "darkgreen", col.sub = "cyan4", main = "Testing colors", sub = "sub titles", ylab = "y axis", xlab = "x axis")
  • 我們還可以使用rgb()函式生成新顏色。第一個引數是紅色的強度,第二個是綠色的強度,第三個是藍色的強度。預設情況下它們在 0 到 1 之間變化,但可以使用選項max = 255進行修改。col2rgb()返回 R 顏色的 RGB 程式碼。col2hex()gplots)給出十六進位制程式碼。col2grey()col2gray()TeachingDemos)將顏色轉換為灰度。
> mycolor <- rgb(.2,.4,.6)
> plot(x1, col = mycolor)
> col2rgb("pink")
      [,1]
red    255
green  192
blue   203
> library("gplots")
> col2hex("pink")
[1] "#FFC0CB"

對於點,可以使用pch選項更改符號,該選項取 0 到 25 之間的整數值或單個字元。pch也可以取向量作為引數。在這種情況下,第一個點將使用向量的第一個元素作為符號,依此類推。

plot(x1, type = "p", pch = 0)
plot(x1, type = "p", pch = 10)
plot(x1, type = "p", pch = 25)
plot(x1, type = "p", pch = "a")
plot(x1, type = "p", pch = "*")
plot(x1[1:26], type = "p", pch = 0:25)
plot(x1[1:26], type = "p", pch = letters)

以下程式碼在同一圖上顯示所有符號

x <- rep(1,25)
plot(x, pch = 1:25, axes = F, xlab = "", ylab = "")
text(1:25,.95,labels = 1:25)

points()將點新增到現有圖中。

> plot(x1, pch = 0) # plot x1 
> points(x2, pch = 1, col = "red") # add x2 to the existing plot

我們可以使用lty更改線型。引數是一個字串("blank"、"solid"、"dashed"、"dotted"、"dotdash"、"longdash"或"twodash")或一個整數(0=blank、1=solid(預設)、2=dashed、3=dotted、4=dotdash、5=longdash、6=twodash)。可以使用lwd更改線寬。預設值為lwd=1lwd=2意味著寬度是正常寬度的兩倍。

plot(x1, type = "l", lty = "blank")
plot(x1, type = "l", lty = "solid")
plot(x1, type = "l", lty = "dashed")
plot(x1, type = "l", lty = "dotted")
plot(x1, type = "l", lty = "dotdash")
plot(x1, type = "l", lty = "longdash")
plot(x1, type = "l", lty = "twodash")

lines()在圖形上新增額外的線。

plot(x1, type = "l", lty = "solid")
lines(x2, type = "l", lty = "dashed", col = "red")

abline()在當前圖上新增水平線 (h=)、垂直線 (v=) 或線性函式 (a= 為常數,b= 為斜率)。abline()還可以繪製迴歸線。

> plot(x1, type = "l", lty = "solid")
> abline(h= -3, lty = "dashed", col = "gray")
> abline(v = 0, lty = "dashed", col = "gray")
> abline(a = -3 , b = .06, lty = "dotted", col = "red")

每個圖都由一個框框起來。bty指定框型別。

plot(x1, bty = "o") # the default
plot(x1, bty = "n") # no box
plot(x1, bty = "l")
plot(x1, bty = "7")
plot(x1, bty = "u")
plot(x1, bty = "c")
plot(x1, bty = "]")

另請參見box(),它將一個框新增到現有圖中。

grid()在當前圖形上新增一個網格。

> plot(x1)
> grid()

雖然網格有一個可選引數 nx 用於設定網格線的數量,但無法明確地告訴它將這些線放在哪裡(它通常不會將它們放在整數值處)。更精確且易於管理的替代方法是使用 abline()。

> abline(v=(seq(0,100,5)), col="lightgray", lty="dotted")
> abline(h=(seq(0,100,5)), col="lightgray", lty="dotted")

箭頭和線段

[編輯 | 編輯原始碼]

多邊形

[編輯 | 編輯原始碼]

其他圖形

[編輯 | 編輯原始碼]

我們還可以使用calibrate包中的circle()函式將圓圈新增到圖中。

您可以選擇圖表的背景。例如,您可以使用par(bg=)更改背景顏色。

par(bg="whitesmoke")
par(bg="transparent")

疊加圖

[編輯 | 編輯原始碼]

matplot()可以同時繪製多個圖。

N <- 100
x1 <- rnorm(N)
x2 <- rnorm(N) + x1 + 1
y <- 1 + x1 + x2 + rnorm(N)
mydat <- data.frame(y,x1,x2)
matplot(mydat[,1],mydat[,2:3], pch = 1:2)

多個圖

[編輯 | 編輯原始碼]

使用par(),我們可以在同一圖上顯示多個圖形。mfrow = c(3,2)在同一圖上列印 6 個圖形,有 3 行 2 列。mfcol = c(3,2)執行相同的操作,但順序不同。

par(mfrow = c(3,2))
plot(x1, type = "n")
plot(x1, type = "p")
plot(x1, type = "l")
plot(x1, type = "h")
plot(x1, type = "s")
plot(x1, type = "S")

par(mfcol = c(3,2))
plot(x1, type = "n")
plot(x1, type = "p")
plot(x1, type = "l")
plot(x1, type = "h")
plot(x1, type = "s")
plot(x1, type = "S")


繪製函式

[編輯 | 編輯原始碼]
  • curve()繪製函式。這可以使用選項add = TRUE新增到現有圖中。
  • plot()也可以繪製函式。
curve(x^2, from = -1 , to = 1, main = "Quadratic function", ylab = "f(x)=x^2")

plot(rnorm(100))
curve((x/100)^2, add = TRUE, col = "red")

匯出圖形

[編輯 | 編輯原始碼]

如何匯出圖形?

  • 首先,您可以繪製圖形,並使用上下文選單(在 Windows 和 Linux 上右鍵單擊,或在 Mac 上按住 Control 鍵並單擊)來複制或儲存圖形。可用選項取決於您的作業系統。在 Windows 上,您還可以使用 CTRL + C 將當前圖形複製到剪貼簿作為點陣圖檔案(光柵圖形),或使用 CTRL + W 將其作為 Windows 圖元檔案(向量圖形)複製。然後,您可以將其貼上到其他應用程式中。
  • 您可以在繪製之前新增pdf("filename.pdf")png("filename.png")jpeg("filename.jpg")bmp("filename.bmp")tiff("filename.tiff"),並在繪製之後新增dev.off(),將圖匯出為pdfpngjpegbmptiff
  • 您還可以使用savePlot()函式儲存現有圖形。
  • Sweave 還會生成 ps 和 pdf 圖形(參見 Sweave 部分)。

最好使用向量裝置,如pdfpssvg

如何知道所有可用裝置的列表?

  • ?Devices
  • 使用capabilities()函式檢視計算機上所有可用裝置的列表。
?Devices
> capabilities()
    jpeg      png     tiff    tcltk      X11     aqua http/ftp  sockets 
    TRUE     TRUE     TRUE     TRUE    FALSE    FALSE     TRUE     TRUE 
  libxml     fifo   cledit    iconv      NLS  profmem    cairo 
    TRUE    FALSE     TRUE     TRUE     TRUE     TRUE    FALSE
png("r_plot.png", width = 420, height = 340)
plot(x1, main = " Example")
dev.off()

pdf("r_plot.pdf", width = 420, height = 340) 
plot(x1, main = " Example")
dev.off()

postscript(file="graph1.ps",horizontal=F,pagecentre=F,paper="special",width=8.33,height=5.56) 
plot(x1, main = "Example")
dev.off()

plot(x1, main = "Example")
savePlot("W:/Bureau/plot.pdf", type = "pdf")
savePlot("W:/Bureau/plot.png", type = "png")

我們還可以使用svg()函式匯出到SVG

svg("scatterplot.svg", width = 7, height = 7)
plot(x, y)
dev.off()

RSvgDevice庫在 R 的早期版本中使用,現在似乎已經過時。

高階主題

[編輯 | 編輯原始碼]

動畫圖

[編輯 | 編輯原始碼]

animation包提供了動態圖形功能。可以將動畫匯出為 flash、mpeg 或 gif 格式。aniwiki 網站上有更多示例:http://animation.yihui.name/

您還可以使用googleVis包建立運動圖表[5]


互動式圖形

[編輯 | 編輯原始碼]

iplots包提供了一種在 R 中進行互動式資料視覺化的方式[6] ·[7]

要建立可以在網路瀏覽器中檢視的互動式動畫繪圖,可以使用 animint 包。主要思路是將互動式動畫定義為一個包含兩個新美學特徵的 ggplots 列表

  • showSelected=變量表示僅顯示對應於變數所選值的子集資料。
  • clickSelects=變量表示單擊繪圖元素將更改變數的當前所選值。
[編輯 | 編輯原始碼]

在本節中,我們回顧了各種統計圖,並回顧了使用 R 繪製它們的各種替代方法。這包括標準圖形包、lattice 包和 ggplot2 包的程式碼。此外,我們還從 commons 倉庫 中添加了一些示例。我們只添加了包含 R 程式碼的示例。您可以點選任何圖形並找到 R 程式碼。

折線圖

[編輯 | 編輯原始碼]

要繪製折線圖,請使用通用 plot() 函式並設定 type="l"

> x <- seq(0, 2*pi, pi/10)
> plot(x, sin(x), type="l")

然後,您可以使用 lines() 函式在同一繪圖上新增更多線條。

> lines(x, cos(x))

散點圖

[編輯 | 編輯原始碼]
  • plot(x,y)
  • plot(y ~ x)
  • xyplot(y ~ x) (lattice)
  • qplot(x,y) (ggplot2)

對數刻度

[編輯 | 編輯原始碼]

有時,繪製變數的對數並對軸使用對數刻度非常有用。可以使用 plot() 函式中的 log 選項來繪製變數的對數。

  • 對於對數對數圖,使用 log = "xy"
  • 對於僅在 x 軸上的對數,使用 log = "x"
  • 對於僅在 x 軸上的對數,使用 log = "y"
plot(x, y , log = "xy")

在繪圖中標記點

[編輯 | 編輯原始碼]
  • 可以使用 text() 函式新增標籤。
  • textxy() (calibrate) 使新增標籤變得容易。
N <- 10
u <-rnorm(N)
x <- 1 + rnorm(N)
y <- 1 + x + u
plot(x, y)
textxy(x, y,labs = signif(x,3), cx=0.7)

直方圖

[編輯 | 編輯原始碼]
  • hist()
  • histogram() (lattice)

您可以在 非引數方法 頁面瞭解更多關於直方圖的資訊。

箱線圖

[編輯 | 編輯原始碼]

箱線圖 

  • boxplot()

另請參閱

[編輯 | 編輯原始碼]

條形圖

[編輯 | 編輯原始碼]

參見維基百科上的 條形圖

  • barplot() 以表格作為引數並返回條形圖。
  • qlot() (ggplot2) 使用 geom = "bar" 選項以變數作為引數並返回條形圖[8]
  • barchart() 以變數作為引數並返回條形圖。

另請參見維基百科上的 點圖

  • dotchart()
  • pie()

樹狀圖

[編輯 | 編輯原始碼]

treemap 包中的 tmPlot() 函式使得繪製 樹狀圖 變得容易。

置信區間圖

[編輯 | 編輯原始碼]

標準誤差條形圖對於繪製包含置信區間的多個估計值非常有用。

  • Hmisc 包有一個 errbar() 函式。此函式以置信區間的上限和下限作為引數[9]
  • Gelman 和 Hill 的 arm 包中的 coefplot() 函式。此函式旨在顯示估計結果。它以點估計和標準誤差作為引數。
coefs <- c(0.2, 1.4, 2.3, 0.5,.3) # vector of point estimates
se <- c(0.12, 0.24, 0.23, 0.15,.2) # standard errors of point estimates
variable <- 1:5 # variable names
library("arm")
# we use CI = qnorm(.975) to have 95% confidence interval
coefplot(coefs, se, variable, vertical = T, CI = qnorm(.975)) 
coefplot(coefs, se, variable, vertical = F, CI = qnorm(.975))
library("Hmisc")
errbar(variable, coefs, coefs - qnorm(.975) * se, coefs + qnorm(.975) * se)

另請參閱

  • sfsmisc 包中還有另一個 errbar() 函式。
  • plotCI() (gplots) 也繪製誤差條。
  • plotmeans() (gplots)
  • ciplot() (hacks)
  • 另請參見維基百科上的 誤差條
  • contour(), image(), persp()
  • plot3d() (rgl)
  • wireframe() (lattice)
  • Paul Murrell 的 grid[10]
  • diagram[11]
  • Rgraphviz
  • igraph

弧線圖

[編輯 | 編輯原始碼]

也可以繪製弧形圖[12]

樹狀圖

[編輯 | 編輯原始碼]

可以在 R 中繪製樹狀圖[13]

樹狀圖

[編輯 | 編輯原始碼]

可以使用 treemap 包中的 treemap() 函式繪製樹狀圖[14]

有 

  • wordcloud 包中的 wordcloud() 函式
  • tagcloud 包中的 tagcloud() 函式

時間線

[編輯 | 編輯原始碼]
  • timeline 包中的 timeline()

另請參閱

[編輯 | 編輯原始碼]

參考文獻

[編輯 | 編輯原始碼]
  1. D. Sarkar。Lattice:使用 R 進行多元資料視覺化。Springer,2008。 ISBN 9780387759685.
  2. ggplot2:用於資料分析的優雅圖形(使用 R),作者:Hadley Wickham,以及他自己的網站上的一些示例:http://had.co.nz/ggplot2/
  3. playwith:http://code.google.com/p/playwith/
  4. Hervé,Maxime (2011)。 "GrapheR:用於在 R 中繪製可自定義圖形的多平臺 GUI" (PDF)The R Journal3 (2)。
  5. googleVis 包的教程:http://stackoverflow.com/questions/4646779/embedding-googlevis-charts-into-a-web-site/4649753#4649753
  6. http://www.r-bloggers.com/interactive-graphics-with-the-iplots-package-from-%E2%80%9Cr-in-action%E2%80%9D/
  7. http://www.r-statistics.com/2012/01/interactive-graphics-with-the-iplots-package-from-r-in-action/ 使用 iplots 包進行互動式圖形] - R 實戰 一書中的一個章節
  8. Hadley Wickham ggplot2:用於資料分析的優雅圖形,Springer Verlag,2009
  9. errbar() 中的預設輸出在 R 版本 2.8.1 和 R 版本 2.9.2 之間發生了變化。軸不再預設顯示
  10. Paul Murrell 使用 R 繪製圖表,The R Journal,2009 http://journal.r-project.org/2009-1/RJournal_2009-1_Murrell.pdf
  11. (示例:使用二叉樹圖描述伯努利過程)
  12. Gaston Sanchez (2013 年 2 月 3 日)。 "R 中的弧形圖:悲慘世界". 檢索於 2013 年 2 月 5 日。 {{cite web}}: 檢查日期值:|accessdate=|date= (幫助)
  13. Gaston Sanchez (2012 年 10 月 3 日)。 "7 種在 R 中繪製樹狀圖的方法". 檢索於 2013 年 2 月 5 日。 {{cite web}}: 檢查日期值:|accessdate=|date= (幫助); 換行符在 |date= 中的第 9 個位置 (幫助)
  14. http://cran.r-project.org/web/packages/treemap/treemap.pdf
  15. http://www.stat.auckland.ac.nz/~paul/RGraphics/rgraphics.html
  16. http://had.co.nz/ggplot2/
上一頁:資料管理 索引 下一頁:描述性統計
華夏公益教科書