Bar Graph

A bar plot or bar graph is a chart of rectangular bars with their lengths proportional to the values or proportions that they represent. It is good for displaying the distribution of a categorical variable. A bar plot is often preferred than a pie chart. In a bar plot, one doesn't need to include all the categories to make up a whole. To generate a bar plot, the function barplot() can be used.

A simple bar plot

A simple bar plot can be generated for a vector of data as shown below. The plot shows the number of male and female participants in the ACTIVE study. Note that the function table() calculates the number of male and female participants in the variable sex of the data set active. One can also "attach" the data and use the variable sex directly.The most useful options include:

  • names.arg: label the bars. The order should correspond to the data.
  • xlab: label for x axis
  • ylab: label for y axis
  • main: title of the plot
> usedata('active') > attach(active) > gender.count<-table(sex) > > barplot(gender.count, names.arg=c('Male','Female'), main='Distribution of gender', xlab='Gender', ylab='Count') > barplot(gender.count, names.arg=c('Male','Female'), main='Distribution of gender', xlab='Gender', ylab='Count') >


Clustered (side by side or stacked) bar plot

A clustered bar plot can be generated for a matrix of data. As an example, we compare the gender distribution across the 4 experimental groups (cognitive training, reasoning training, speed training and control) in the ACTIVE study. The most useful options include:

  • names.arg: label the bar groups. The order should correspond to the data.
  • col: color of the bars
  • legend: legend within each group
  • beside: put the bars side by side (TRUE), or stack them up (beside=FALSE)
  • xlim and ylim: the minimum and maximum values of the x-axis and y-axis.
> usedata('active') > attach(active) > counts <- table(sex, group) > barplot(counts,beside=T,legend=c('M','F')) > barplot(counts,col=c('red','blue'), + names.arg=c('Cognitive', 'Reasoning', 'Speed', 'Control'), + beside=T,legend=c('M','F'), xlim=c(1,15)) >


Compare a Pie chart to a Bar graph

When comparing groups, bar graph is easier to visualize the difference. See an example below.

> a<-c(17, 18, 20, 22, 23) > > b<-c(20, 20, 19, 21, 20) > > par(mfrow=c(2,2)) # plot figures in a 2 by 2 layout > > par(mar=c(0,0,2,0)) # change the margins of the plots, bottom,left,upper,right > > pie(a, main='a',col=rainbow(5)) > > pie(b, main='b',col=rainbow(5)) > > par(mar=c(3,2,2,3)) > > barplot(a,col=rainbow(5),names.arg=1:5) > > barplot(b,col=rainbow(5),names.arg=1:5) >

To cite the book, use: Zhang, Z. & Wang, L. (2017-2022). Advanced statistics using R. Granger, IN: ISDSA Press. https://doi.org/10.35566/advstats. ISBN: 978-1-946728-01-2.
To take the full advantage of the book such as running analysis within your web browser, please subscribe.