Introduction

This tutorial will help you learn to use R to create a basic bar plot. A basic bar plot is a visual image of a distrubition of two categorical variables.

For this example, I am using the data set called VADeaths. This data set is a preloaded dataset on R. For a list of other data sets that are pre-installed, you can run the function data().

Since I have chosen my data set, I want to learn additional information about it. To explore your preloaded data set, use the following function:

Preview Data

In order to preview your data, you must load your data set. Do this using data() and putting the name of the dataset in the ().

Then take a look at your data by previewing the first few rows as follows:

##       Rural Male Rural Female Urban Male Urban Female
## 50-54       11.7          8.7       15.4          8.4
## 55-59       18.1         11.7       24.3         13.6
## 60-64       26.9         20.3       37.0         19.3
## 65-69       41.0         30.9       54.6         35.1
## 70-74       66.0         54.3       71.1         50.0

Note that the echo = FALSE parameter was added to the code chunk to prevent printing of the R code that generated the plot.

You can also preview your data by calling it directly by name as demonstrated below:

##       Rural Male Rural Female Urban Male Urban Female
## 50-54       11.7          8.7       15.4          8.4
## 55-59       18.1         11.7       24.3         13.6
## 60-64       26.9         20.3       37.0         19.3
## 65-69       41.0         30.9       54.6         35.1
## 70-74       66.0         54.3       71.1         50.0

Create Subset of Data

This is a very large data set, but I am only interested in a small portion. Analyzing a smaller subset of the data will help me to draw more a meaningful conclusion.

In order to subset your data, choose the variables you are interested in analyzing and subset by using square brackets. You can name the variable whatever you’d like. In this case, I created RuralWomenVADeaths. I want to see the data for all five age ranges (1:5) for the Urban Females group. I have demonstrated below:

## 50-54 55-59 60-64 65-69 70-74 
##   8.4  13.6  19.3  35.1  50.0

Create Bar Plot

Now that I have my subset of data, I will use the basic R plot function barplot() to create my plot. Put the name of the subset you defined in the last step into the brackets.

Customize Bar Plot with Title and Labels

I want to start the customization process by adding a title. I can do so by usin the following function:

I want to also label my x and my y axis. I can add xlab = " " and ylab = " " to what I just did:

Bonus Additional Greyscale Option

To add a greyscale option, use the following addition to your code grey.colors(). Put the number of bars you have displayed in your graph in the () for a gradient effect as demonstrated below.