Book Image

R Graphs Cookbook Second Edition

Book Image

R Graphs Cookbook Second Edition

Overview of this book

Table of Contents (22 chapters)
R Graphs Cookbook
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

Creating stacked bar charts


Stacked bar charts are another form of bar chart used to compare values across categories. As the name implies, the bars for each category are stacked on top of each other instead of being placed next to each other.

Getting ready

We will use the same dataset and color scheme as the last recipe, so ensure that you have the RColorBrewer package installed and loaded:

install.packages("RColorBrewer")
library(RColorBrewer)

How to do it...

Let's draw a stacked bar chart of sales figures across the five cities:

citysales<-read.csv("citysales.csv")

barplot(as.matrix(citysales[,2:4]), 
legend.text=citysales$City,
args.legend=list(bty="n",horiz=TRUE),
col=brewer.pal(5,"Set1"),border="white",
ylim=c(0,200),ylab="Sales Revenue (1,000's of USD)",
main="Sales Figures")

How it works...

If you compare the code for this example and the last recipe, you will see that the main difference is that we did not use the beside argument. By default, it is set to FALSE, which results in a stacked...