2.1 Bar Charts/Bar Plots

Objective

To create a bar chart/bar plot in R with the barplot function using categorical data, which is a collection of numbers that represent frequencies (or counts) of events or outcomes that fall into different groups or categories. [Note: If you are trying to display distributions of quantitative data, choose a histogram instead. Bar charts are for categorical data only. BAR CHARTS ARE NOT THE SAME AS HISTOGRAMS!]

Background

A bar chart uses rectangular segments to visualize categorical data. The lengths of the bars are proportional to the values they represent, and the bars can be oriented vertically or horizontally.

  • Bar charts can be an especially suitable alternative to a pie chart when there are many categories to be compared. For me, it is never pleasant to examine a pie chart that has more than 10 slices, because the slices just overwhelm me.

  • Good bar charts are labeled nicely, with a clear description of the categories that are being counted on the horizontal (x) axis, and a label on the vertical (y) axis that indicates whether frequencies or counts are displayed.

  • Membership into each category should be mutually exclusive. That is, you don’t want an observation to appear in multiple bars.

  • You will always have to consider whether a pie chart or a bar chart is a better way to display your data. If you are trying to illustrate a collection of items that naturally add up to 100%, a pie chart may be appropriate. However, if there are multiple categories where it may be difficult to distinguish which slice is bigger (such as one observation of 28% and another observation of 29%) a bar chart may be more appropriate. When small variations between categories should be communicated to your audience, bar charts are typically more effective than pie charts in presenting your data.

  • If you want to display your data in terms of TWO categorical variables, choose a segmented bar chart (described in a separate chapter).

Even More Caution: There is a BIG DIFFERENCE between a bar chart and a histogram! Even though a bar chart looks really similar to a histogram at first glance, take a close look at what kind of data is on the horizontal (x) axis. In a bar chart, the horizontal axis lists categories. In a histogram, the horizontal axis will contain ranges of numbers that represent a continuum (e.g. 0-10, 10-20, 20-30 and so forth). Also, in a bar chart, there will be some space between the bars indicating that the categories are separate from one another - whereas with a histogram, there will be no space between the bars! The bars will be very cozy in a histogram, mashed up against one another like they're at a crowded party, whereas the bars in a bar chart need a little more breathing room, and thus are distanced from one another.

If You Counted Your Observations Already (Quick Start with Base R)

For small data sets, you may have already tallied up your observations, and you don’t need to load a whole file in to create your bar chart. Here is an example of data generated by opening one package of regular M&Ms to look at the distribution of colors, working with your data as a vector. I counted 12 blue ones, 6 brown ones, 8 green ones, and so forth:

Note that even though I called my variable mm.counts, you can call your variable whatever you want. Just be sure to use that variable name in all future commands. For example, if you call your variable snakes, you want to make sure all future commands use that variable name, e.g. names(snakes).

We can also create a NEW variable to store the color names, so that we can use them to make colored bars in our bar chart that correspond to the M&M colors. I'm going to cal this new variable mm.colors:

Now, you can check to make sure that your data was entered correctly:

blue brown green orange red yellow
12 6 8 10 6 7

The barplot command knows how to plot data that’s in this format. Type in this code to produce your bar plot:

If you want the bars to be colored, add a list of colors using the col argument:

If You Need R to Count Observations for You

In most cases, you will have tens or thousands of observations – it would be impractical to count all of them. I have a file containing data from 1922 M&Ms that my students examined over two semesters. Tallying up how many colors and defects are in that data set would take forever if you had to do it manually SO DO NOT TRY TO DO IT MANUALLY, but fortunately, there’s an easier way with R so long as the data has been recorded in case format with ONE CASE PER ROW. First, load my data, which is published to the web from Google Sheets. It originally had a super long URL but I got a shorter one that you see below. I gave my data the name mnms:

In the case above, I've published my M&M data to the web as a CSV file. The argument "header=TRUE" means that the first row of my data file contains variable names. Once this command is executed, I'll have a data frame called mnms that contains seven variables. The first four are student (who logged the observation), id (the order I pulled the M&Ms from the bag; first M&M pulled would be "1"), color, and defect. I have six color codes (BL = blue, BR = brown, G = green, Y = yellow, O = orange, R = red) and four defect codes (N = no defects, C = cracked or chipped, L = letter is missing or improperly printed on the M&M, and M = multiple defects).

Finally, each student collected information about the entire bag to use later in the semester. The variables full.bag.weight and empty.bag.weight record the weight, in grams, before and after M&Ms were consumed; total.number reflects the number of M&Ms in the bag upon opening. Note that this data is not perfectly tidy… the total and the bag weight are measurements on the bag, not the individual candy.

First, make R count your M&Ms. You’re going to use this table later to verify the plot.

BL BR G O R Y
311 240 375 420 319 257

In base R, just feed barplot that table using barplot(table(color)). In ggplot, it’s a little more complicated, especially if you want to make the bars the same color as the M&Ms you observed. Since R doesn’t understand that BL means blue (and so on), let’s create a new tibble called mnms2 that will recode our color codes into color names that R understands:

Now we can send just the color data to ggplot by using the select command. When we use scale_fill_identity as an option to ggplot, that’s what tells R to literally interpret the color names and make the bar colors the same as the M&M colors:

It’s also easy to add labels by tacking on more arguments to ggplot:

Additional Arguments for the Base R barplot

Bar charts, like pie charts, are used to visualize the distribution of proportions (or counts) of observation in categories. Whether you use counts or proportions on the vertical (y) axis for a given data set, your bar charts will look exactly the same! However, if you are using proportions, the bar chart has a different name - it's called a relative frequency bar chart. Using base R, you can create one using barplot(table(color))/sum(table(color)). As with all of the examples in this chapter, you can feed any categorical variable to the barplot command.

There are many optional arguments that you can add to your bar chart using barplot, some of which you've seen in the examples above. Here are my favorites:

Option What it does
main Specify a main title to be displayed above chart
xlab Specify text to describe the x-axis
ylab Specify text to describe the y-axis
col=mm.colors Sets the color palette to the colors that you have designated in the vector mm.colors
names.arg=c("first name","second name") Instead of labeling the x-axis with the categories from the raw data, this argument enables you to set up new labels for the bars, which can be useful if you are generating a bar chart from data within a data frame
legend.text=TRUE Adds a box with a legend to the plot
horiz=TRUE Orients the display of the bars horizontally instead of vertically
border="black" Give each bar a border (any color will work)
density=10 Makes shaded bars instead of solid (I like to choose values between 8 and 22 here)

Other Resources: