【r<-基礎|實戰(zhàn)|繪圖】基本圖形的繪制

主題:

  • 將變量的分布進行可視化的展示;
  • 通過結(jié)果變量進行跨組比較。

條形圖

函數(shù)barplot()的最簡單用法是:

? barplot(height)

其中的height是一個向量或者一個矩陣。

接下來示例中,我們繪制一項探索類風濕性關節(jié)炎新療法研究的結(jié)果。數(shù)據(jù)已經(jīng)包含在隨vcd包分發(fā)的Arthritis數(shù)據(jù)框中。(請確保在使用前已經(jīng)安裝vcd包,使用命令install.packages("vcd")

簡單條形圖

height是一個向量,則它的值就確定了各條形圖的高度,并將繪制一幅垂直的條形圖。使用選項horiz=TRUE則會生成一幅水平條形圖。

在關節(jié)研究中,變量Improved記錄了對每位接受了安慰劑或藥物治療的病人的治療結(jié)果:

> library(vcd)
載入需要的程輯包:grid
> library(grid)
> counts <- table(Arthritis$Improved)
> counts

  None   Some Marked 
    42     14     28 

我們可以使用一幅垂直或水平的條形圖來繪制變量counts。代碼如下(交互模式):

> barplot(counts,
+         main="Simple Bar Plot",
+         xlab="Improvement", ylab="Frequency")
> barplot(counts,
+         main="Horizontal Bar Plot",
+         xlab="Frequency", ylab="Improvement",
+         horiz=TRUE)
simple_bar_plot.png
horiz_bar_plot.png

生成因素變量的條形圖

若要繪制的類別型變量是一個因子或有序因子,就可以使用函數(shù)plot()快速創(chuàng)建一幅垂直條形圖,而無需使用table()函數(shù)將其表格化。下面的代碼同樣可以繪制出與上圖相同的結(jié)果:

> plot(Arthritis$Improved, main="Simple Bar Plot",
+     xlab="Improvement", ylab="Frequency")
> plot(Arthritis$Improved, main="Horizontal Bar plot",
+     xlab="Frequency", ylab="Improvement", horiz=TRUE)

堆砌條形圖和分組條形圖

如果height是一個矩陣而不是一個向量,則繪圖結(jié)果將是一幅堆砌條形圖分組條形圖。beside=FALSE設置成堆砌(默認),beside=TRUE設置為分組條形圖。代碼如下:

> library(vcd)
> counts <- table(Arthritis$Improved, Arthritis$Treatment)
> counts
        
         Placebo Treated
  None        29      13
  Some         7       7
  Marked       7      21
> 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)
stacked_bar_plot.png
grouped_bar_plot.png

注意它是依據(jù)數(shù)據(jù)框的行名來生成分類的。

均值條形圖

我們可以使用數(shù)據(jù)整合函數(shù)并將結(jié)果傳遞給barplot()函數(shù),來創(chuàng)建表示均值、中位數(shù)、標準差等的條形圖。

> states <- data.frame(state.region, state.x77)
> 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")

mean_bar_plot.png

注意:使用title()函數(shù)與調(diào)用plot()時添加main選項是等價的。

條形圖的微調(diào)

有若干種方式可以微調(diào)條形圖的外觀。具體就是調(diào)節(jié)一些相關的設置參數(shù),例如cex.name可以用來調(diào)整字號。詳細參考一些文檔。par()函數(shù)能夠讓你對R的默認圖形作出大量修改,這里只給出一個示例:

par(mar=c(5, 8, 4, 2))  # 增加y邊界大小
par(las=2)              # 旋轉(zhuǎn)條形的標簽
counts <- table(Arthritis$Improved)
barplot(counts,
        main="Treatment Outcome",
        horiz=TRUE,
        cex.names = 0.8,    # 縮小字體大小,讓標簽更合適
        names.arg = c("No Improvement", "Some Improvement",
                      "Marked Improvement")) # 修改標簽文本
treatment_bar_plot.png

棘狀圖

棘狀圖(spinogram):對堆砌條形圖進行了重縮放,這樣每個條形的高度均為1,每一段的高度即表示比例。此圖可以由vcd包的函數(shù)spine()繪制。以下生成一個簡單的示例:

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

餅圖

多數(shù)統(tǒng)計學家不喜歡餅圖,更推薦使用條形圖或點圖。因為相對于面積,人們對長度的判斷更精確。(所以在此也不詳述了)

餅圖可以由下面函數(shù)創(chuàng)建:

pie(x, labels)

直方圖

直方圖展示了連續(xù)型變量的分布??梢允褂萌缦潞瘮?shù)創(chuàng)建直方圖:

hist(x)

x是一個由數(shù)據(jù)值組成的數(shù)值向量。參數(shù)freq=FALSE表示根據(jù)概率密度而不是頻數(shù)繪制圖形。參數(shù)breaks用于控制組的數(shù)量。默認等距切分。以下提供繪制四種直方圖的代碼:

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") # 指定組數(shù)和顏色

hist(mtcars$mpg,
     freq=FALSE,
     breaks=12,
     col="red",
     xlab="Miles Per Gallon",
     main="Histogram, rug plot, density curve")
# 軸須圖(rug plot)是實際數(shù)據(jù)值的一種一維呈現(xiàn)方式
# 如果數(shù)據(jù)中有許多的結(jié)(相同的值),可以使用下列代碼將其數(shù)據(jù)打散
# rug(jitter(mtcars$mpg, amount=0.01))
rug(jitter(mtcars$mpg))
# 這條密度曲線是一個核密度估計,為數(shù)據(jù)的分布提供了更加平滑的描述,會在下節(jié)具體講述。
lines(density(mtcars$mpg), col="blue", lwd=2) # 添加軸須圖

x <- mtcars$mpg
h <- hist(x,
          breaks=12,
          xlab="Miles Per Gallon",
          main="Histogram with normal curve and box")
# 疊加正態(tài)曲線
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()                              # 添加密度曲線和外框

hist_example_plot.png

核密度圖

核密度估計是用于估計隨機變量概率密度的一種非參數(shù)方法,不失為一種用來觀察連續(xù)型變量分布的有效方法。

繪制密度圖的方法(不疊加到另一幅圖):

plot(density(x))

如果想要疊加到其他圖上,可以使用lines()函數(shù)。

核密度圖

par(mfrow=c(2,1))
d <- density(mtcars$mpg)

plot(d)                      # 默認設置創(chuàng)建最簡圖形

d <- density(mtcars$mpg)
plot(d, main="Kernel Density of Miles Per Gallon")
polygon(d, col="red", border="blue") # 邊界為藍色,用紅色填充
rug(mtcars$mpg, col="brown")         # 棕色軸須圖
density_default_plot.png

可以比較的核密度圖

核密度圖可以用于比較組間,使用sm包中的sm.density.compare()函數(shù)可向圖形疊加兩組或更多的核密度圖。使用格式為:

sm.density.compare(x, factor)

其中x是數(shù)值向量,factor是一個分組變量。

library(sm)
attach(mtcars)

# 創(chuàng)建分組因子
# 將數(shù)值型向量cyl中的(4,6,8)轉(zhuǎn)換為因子
cyl.f <- factor(cyl, levels=c(4,6,8),
                labels = c("4 cylinder", "6 cylinder", 
                           "8 cylinder"))
# 繪制密度圖
sm.density.compare(mpg, cyl, xlabel="Miles Per Gallon")
title(main="MPG Distribution by Car Cylinders")

# 通過鼠標點擊添加圖例
# 第一個參數(shù)locator(1)表示用鼠標點擊放置圖例的位置;第二個參數(shù)是由標簽組成的字符向量,第三個參數(shù)值使用向量colfill為cyl.f的每一個水平指定一種顏色。
colfill <- c(2:(1+length(levels(cyl.f))))
legend(locator(1), levels(cyl.f), fill=colfill)

detach(mtcars)
density_compare_plot.png

箱線圖

箱線圖同樣是一種用來可視化分布和組間差異的絕佳圖形手段(非常常用)。它通過繪制連續(xù)變量的五數(shù)總括——最小值、下四分位數(shù)、中位數(shù)、上四分位數(shù)以及最大值來描述連續(xù)型變量的分布。

箱線圖能夠顯示出可能為離群點的觀測(范圍正負1.5*IQR以外的值,IQR表示四分位距,上四分位數(shù)與下四分位數(shù)之間的差值)。

例如:

boxplot(mtcars$mpg, main="Box Plot", ylab="Miles per Gallon")
box_plot.png

默認情況下,兩條須的延伸極限不會超過盒型各端加1.5倍四分位距的范圍,超過的都會用點表示。執(zhí)行boxplot.stats(mtcars)即可輸出構(gòu)建圖形的統(tǒng)計量。

使用并列箱線圖進行跨組比較

使用格式:

boxplot(formula, data=dataframe)

第一個參數(shù)是公式,第二個是數(shù)據(jù)框或者列表。添加參數(shù)varwidth=TRUE將使箱線圖的寬度與其樣本大小的平方跟成正比。參數(shù)horizontal=TRUE可以反轉(zhuǎn)坐標軸。

# 研究不同的發(fā)動機缸數(shù)對每加侖汽油行駛的英里數(shù)的影響
boxplot(mpg ~ cyl, data=mtcars,
        main="Car Mileage Data",
        xlab="Number of Cylinders",
        ylab="Miles Per Gallon")
car_mileage_data_plot.png

凹槽圖

箱線圖靈活多變,可以添加notch=TRUE,得到含凹槽的箱線圖。若兩個箱的凹槽互不重疊,則表明它們的中位數(shù)有顯著性差異。

boxplot(mpg ~ cyl, data=mtcars,
        notch=TRUE,
        varwidth=TRUE,
        col="red",
        main="Car Mileage Data",
        xlab="Number of Cylinders",
        ylab="Miles Per Gallon")
car_mil_data_plot.png

交叉因子箱線圖

為多個分組因子繪制箱線圖。

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=T,
        col=c("gold", "darkgreen"),
        main="MPG Distribution by Auto Type",
        xlab="Auto Type", ylab="Miles Per Gallon")

mpg_dis_plot.png

點圖

點圖提供了一種在簡單水平刻度上繪制大量有標簽值的方法。你可以使用dotchart()函數(shù)創(chuàng)建點圖,格式為:

dotchart(x, labels=)

其中x是一個數(shù)值向量,而labels則是由每個點的標簽組成的向量??梢酝ㄟ^添加參數(shù)groups來選定一個因子,用以指定x中元素的分組方式。還可以用gcolor控制不同組標簽的顏色,cex可以控制標簽的大小。下面是一個示例:

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

分組、排序、著色后的點圖

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 = .7,
         groups = x$cyl,
         gcolor = "black",
         color = x$color,
         pch = 19,
         main = "Gas Mileage for Car Models\ngrouped by cylinder.",
         xlab = "Miles Per Gallon")

dotchart_example2.png

還有許多關于點圖的變種。

本文參考

本文參考R in Action第二版記錄,請注意原作版權(quán)。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容