Book Image

R Graph Essentials

Book Image

R Graph Essentials

Overview of this book

Table of Contents (11 chapters)
R Graph Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Creating bar charts


Let's see how to create bar charts in R. We will create a simple bar chart using the barplot() command, which is easy to use. First, we set up a vector of numbers. Then we count them using the table() command and plot the counts. The table() command creates a simple table of counts of the elements in a dataset. Enter the following vector into R:

H <- c(2,3,3,3,4,5,5,5,5,6)

Now, we count each element using the table() command as follows:

counts <- table(H)
counts

The output is as follows:

H
2 3 4 5 6 
1 3 1 4 1    

Now we plot the counts.

barplot(counts)

Here is the bar chart:

The horizontal axis records the elements in your dataset, while the vertical axis gives the counts of each element. You will see that the barplot() command does not perform the count directly, so we used the table() command first.

You can plot your data directly if you omit the table() command. In that case, the height of the bars will match the actual values of the dataset. This technique is...