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 Proportional Stacked Bar Graph

Making a Proportional Stacked Bar Graph

Problem

You want to make a stacked bar graph that shows proportions (also called a 100% stacked bar graph).

Solution

First, scale the data to 100% within each stack. This can be done by using ddply() from the plyr package, with transform(). Then plot the resulting data, as shown in Figure 3-20:

library(gcookbook) # For the data set
library(plyr)
# Do a group-wise transform(), splitting on "Date"
ce <- ddply(cabbage_exp, "Date", transform,
            percent_weight = Weight / sum(Weight) * 100)

ggplot(ce, aes(x=Date, y=percent_weight, fill=Cultivar)) +
    geom_bar(stat="identity")
Proportional stacked bar graph
Figure 3-20. Proportional stacked bar graph

Discussion

To calculate the percentages within each Weight group, we used the ddply() function. In the example here, the ddply() function splits the input data frame, cabbage_exp, by the specified variable, Weight, and applies a function, transform(), to each piece. (Any remaining arguments in the ddply() call are passed along to the function.)


  

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