Creating boxplots

In this section, we will learn how to create boxplots. Using the medical dataset, let's produce a simple boxplot of patient weight before treatment, grouped by the three levels of treatment. We use the syntax geom = "boxplot" and again we choose a nice color from the Hexadecimal Color Chart. Enter the following syntax:

qplot(TREATMENT, WEIGHT_2, data = T,   geom = "boxplot",   xlab = " TREATMENT", ylab = "WEIGHT (kg)", fill = I("#99CCFF"))

Here is the boxplot:

Creating boxplots

If we do not wish to create a grouped boxplot and want a boxplot of all of the data taken together, we simply omit the categorical variable from the qplot() command. Anyway, within any boxplot, we can include the data as points—positioned according to the levels of the factor variable. Simply include "point" within geom as follows:

qplot(TREATMENT, WEIGHT_2, data = T, geom = c("boxplot","point"),xlab = "TREATMENT", ylab = "WEIGHT (kg)", fill =I("#669900"))

The boxplot, along with the raw data, looks like this:

Creating boxplots

Including the data gives us additional insight into the variation of weight across the three levels. Now, let's create a box for each level of ethnicity using as.factor(), or simply factor(cyl). Again, we use the Hexadecimal Color Chart to give a different color to each box. To do this, we use the c() operator to include three colors within fill = I(). Enter the following syntax into R:

qplot(as.factor(ETH), WEIGHT_2, data = T,   geom = "boxplot", xlab = "ETHNICITY", ylab = "WEIGHT (kg)", fill = I(c("#66CC99", "#9999CC", "#CC6666"))) 

Now the boxplot looks like this:

Creating boxplots

We have produced an attractive boxplot with different colors for each box. Remember that if the categorical variable is not initially a factor, then you can turn it into a factor using either as.factor() or factor(). Then, you can proceed to create your grouped boxplot.

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

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