Bar Charts in R
There are a number of important types of plots that are used in descriptive statistics. A common plot that is frequently used in newspapers and magazines is the bar chart, where the height of each bar helps the reader visualize the amount of data falling in a particular category. Take, for example, the responses of children who were asked their favorite color of M and M candies.
Note that the data in the table are percentages, summing to 100%.
A Simple Bar Chart
We'll first enter the data from the table above, storing the list in the variable mypie
You can obtain help on R's combine command by typing ?c at the prompt. This command is used to concatenate elements into a single list, particularly useful when entering data manually. You can see the contents of the variable by typing x and hitting the Enter key.
> x  40 30 20 10
It is a simple task to create a bar chart using the data stored in x.
The command barplot(x) produces the bar chart shown in Figure 1.
Figure 1. A simple bar chart representing the percentages of children favoring red, blue, green and brown candies.
In the upcoming exercises, we'll explore further the capabilities of R's barplot command. You can read more about this command by entering the command ?barplot and reading the resulting help file.
Adding Labels to the Pie Chart
We can add "names" to the percentages of colored candies favored by the children.
The names command attaches a "name" to each piece of data. We can see the result of this command by typing the variable name (mypie) and hitting the Enter key.
> x Red Blue Green Brown 40 30 20 10
Note how each piece of data now has a "name" or "header." We can access individual elements of the list with R's indexing capability. For example, to access the first element of the list (R starts indexing at one), enter:
> x Red 40
However, since the data have "names" attached, we can access each data item through its "name."
> x['Red'] Red 40
The barplot command knows how to apply these "names" to the bar chart.
When "names" are added to each piece of data (as we did to the variable x), R's barplot command automatically adds these names as labels to the corresponding "bars," as shown in Figure 2.
Figure 2. Adding labels to each "slice of pie."
Using Custom Colors
It won't do that the "Red" slice is colored "White." Let's see how we can use customized colors for each "bar." First, we store the corresponding colors for each slice in the variable mycolors.
Next, we pass the colors in mycolors to the col argument of the function barplot.
This last command produces the pie chart shown in Figure 3.
Figure 3. Adding custom colors to each "bar."
We hope you enjoyed this very short introducion to bar charts using R. To find out more about what can be accomplished with R's barplot command, remember to type ?barplot, hit Enter, and read the resulting help file.