Creating stacked bar charts

When we want to visualize more than one summarized numeric variable over the category of another variable, we need to produce a stacked bar chart. In this case, each bar represents summary statistics of each variable. The different variables occupy different heights with various colors in that single bar.

Getting ready

To produce stacked bar charts, we will use the same summarized data that we created in the Creating bar charts recipe.

How to do it…

The command that produces the stacked bar chart is exactly the same as the simple bar chart. The only difference is that we need a new argument, which is stack=TRUE:

barchart(disA+disB+disC~factor(age),data=dis_dat,stack=TRUE)
How to do it…

How it works…

The first argument is the formula that specifies the variables to be displayed in the plot. The left-hand side indicates how many components there will be in each of the bars. The right-hand side indicates the grouping information. The stack=TRUE argument makes sure that the bar plot will be stacked, which means that each of the variables will occupy a certain height in a single bar with specific colors.

There's more…

The default implementation does not specify the title of the plot, and it also does not specify the x axis, y axis, and more importantly, it does not produce the legend key. Without the legend key, it is difficult to communicate the information contained in the plot. Here is the code that updates the initial bar chart:

barchart(
 disA+disB+disC~factor(age),
 data=dis_dat,
 auto.key=list(column=3),
 main="Mean incubation period comparison 
 
 among different age group",
 xlab="Age group",
 ylab="Mean incubation period (weeks)",stack=TRUE)

In this new code snippet, auto.key produces the legend key with three columns. The production of the chart title is specified by main, x axis label is specified by xlab, and y axis label is specified by ylab. One important thing in this new code is the use of within the text of the chart title; we use this control to create a new line when the title is long. This breaks the text into two lines.

There's more…

See also

In the next recipe, we will see how we can visualize a cross-tabulated frequency distribution through a bar chart.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.12.52