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

3. Bar Graphs > Making a Basic Bar Graph

Making a Basic Bar Graph

Problem

You have a data frame where one column represents the x position of each bar, and another column represents the vertical (y) height of each bar.

Solution

Use ggplot() with geom_bar(stat="identity") and specify what variables you want on the x- and y-axes (Figure 3-1):

library(gcookbook) # For the data set
ggplot(pg_mean, aes(x=group, y=weight)) + geom_bar(stat="identity")
Bar graph of values (with stat="identity"), with a discrete
            x-axis
Figure 3-1. Bar graph of values (with stat="identity”) with a discrete x-axis

Discussion

When x is a continuous (or numeric) variable, the bars behave a little differently. Instead of having one bar at each actual x value, there is one bar at each possible x value between the minimum and the maximum, as in Figure 3-2. You can convert the continuous variable to a discrete variable by using factor():


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

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

  

Start a Free Trial


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