Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

2. Quickly Exploring Data > Creating a Histogram

Creating a Histogram

Problem

You want to view the distribution of one-dimensional data with a histogram.

Solution

To make a histogram (Figure 2-8), use hist() and pass it a vector of values:

hist(mtcars$mpg)

# Specify approximate number of bins with breaks
hist(mtcars$mpg, breaks=10)
Left: histogram with base graphics; right: with more
            bins
Figure 2-8. Left: histogram with base graphics; right: with more bins. Notice that because the bins are narrower, there are fewer items in each bin.

With the ggplot2 package, you can get a similar result using qplot() (Figure 2-9):

qplot(mtcars$mpg)
Left: histogram with qplot() from ggplot2, with default
            bin width; right: with wider bins
Figure 2-9. Left: histogram with qplot() from ggplot2, with default bin width; right: with wider bins

If the vector is in a data frame, you can use the following syntax:


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free 10-Day Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint