barplot() 函式

在條形圖中,因子水平被放置在 x 軸上,並且在 y 軸上考慮各種因子水平的頻率(或比例)。對於每個因子水平,構造一個均勻寬度的條,其高度與因子水平頻率(或比例)成比例。

barplot() 函式位於 R 系統庫的圖形包中。barplot() 函式必須至少提供一個引數。R 幫助將其稱為 heights,它必須是向量或矩陣。如果是向量,其成員是各種因子水平。

為了說明 barplot(),請考慮以下資料準備:

> grades<-c("A+","A-","B+","B","C")
> Marks<-sample(grades,40,replace=T,prob=c(.2,.3,.25,.15,.1))
> Marks
[1] "A+" "A-" "B+" "A-" "A+" "B"  "A+" "B+" "A-" "B"  "A+" "A-"
[13] "A-" "B+" "A-" "A-" "A-" "A-" "A+" "A-" "A+" "A+" "C"  "C" 
[25] "B"  "C"  "B+" "C"  "B+" "B+" "B+" "A+" "B+" "A-" "A+" "A-"
[37] "A-" "B"  "C"  "A+"
> 

Marks 向量的條形圖來自

> barplot(table(Marks),main="Mid-Marks in Algorithms")

https://i.stack.imgur.com/BDqWz.jpg

請注意,barplot() 函式將因子級別放在級別的 lexicographical order 中的 x 軸上。使用引數 names.arg,在情節線條可被放置在作為載體指出,訂單成績

# plot to the desired horizontal axis labels
> barplot(table(Marks),names.arg=grades ,main="Mid-Marks in Algorithms")

StackOverflow 文件

可以使用 col= 引數繪製彩色條。

> barplot(table(Marks),names.arg=grades,col = c("lightblue", 
        "lightcyan", "lavender", "mistyrose",  "cornsilk"),
         main="Mid-Marks in Algorithms")

https://i.stack.imgur.com/e5KoJ.jpg

可以獲得帶有水平條形的條形圖,如下所示:

> barplot(table(Marks),names.arg=grades,horiz=TRUE,col = c("lightblue",
          "lightcyan", "lavender", "mistyrose",  "cornsilk"),
           main="Mid-Marks in Algorithms")

https://i.stack.imgur.com/qg4NG.jpg

可以如下獲得在 y 軸上具有比例的條形圖 :

> barplot(prop.table(table(Marks)),names.arg=grades,col = c("lightblue",
           "lightcyan", "lavender", "mistyrose",  "cornsilk"),
            main="Mid-Marks in Algorithms")

https://i.stack.imgur.com/15zCn.jpg

可以使用 cex.names 引數增加 x 軸上因子級名稱的大小。

> barplot(prop.table(table(Marks)),names.arg=grades,col = c("lightblue",
          "lightcyan", "lavender", "mistyrose",  "cornsilk"),
           main="Mid-Marks in Algorithms",cex.names=2)

https://i.stack.imgur.com/ZDXEB.jpg

barplot()heights 引數可以是矩陣。例如,它可以是矩陣,其中列是在類中採用的各種主題,行可以是等級的標籤。考慮以下矩陣:

> gradTab
     Algorithms Operating Systems Discrete Math
  A-         13                10             7
  A+         10                 7             2
  B           4                 2            14
  B+          8                19            12
  C           5                 2             5

要繪製堆疊條,只需使用以下命令:

> barplot(gradTab,col = c("lightblue","lightcyan",
       "lavender", "mistyrose",  "cornsilk"),legend.text = grades,
        main="Mid-Marks in Algorithms")

https://i.stack.imgur.com/h6N2L.jpg

要繪製並列條形,請使用 besides 引數,如下所示:

 > barplot(gradTab,beside = T,col = c("lightblue","lightcyan",
       "lavender", "mistyrose",  "cornsilk"),legend.text = grades,
        main="Mid-Marks in Algorithms")

https://i.stack.imgur.com/jZTwk.jpg

使用 horiz=T 引數可以獲得水平條形圖:

> barplot(gradTab,beside = T,horiz=T,col = c("lightblue","lightcyan",
       "lavender", "mistyrose",  "cornsilk"),legend.text = grades,
        cex.names=.75,main="Mid-Marks in Algorithms")

https://i.stack.imgur.com/EAp9L.jpg