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