Boxplots using R – Multiple values

(This post explains how to use R to create multiple boxplots in the same graph)

If you have been using R with Rcmdr and have taken a look at the boxplots that you can create with it, then you already know that there are not many options that you can set for the plots. You can only create a boxplot based on one variable from your active dataset (variables with data that you have loaded in your current workspace).

But you might wish to create a boxplot with more than one boxplots in the same graph.

In order to create a graph like the one shown here you would have to use R from command line.

Start R and load the Data

First of all we should start the R program from the command line:
$ R
Now let us create some vectors with some data.

> a = c(115, 234, 789, 234, 432, 546, 677, 432, 890, 987, 852)
> b = c(1, 1, 1, 2, 2, 3, 3, 2, 2, 2, 3)

Create the data frame

In order to use the boxplot function of R to create boxplots like the ones listed above we have to place our data in an R data frame. We can easily create a data frame in R like
> c = data.frame(a_label = a, b_label = b)
This command will create a data frame named c with two columns a_label, b_label. The two columns represent two variables with these labels. To populate the columns we use the two vectors we created earlier a and b. The two vectors must have the same number of elements. Each row is identified uniquely. In order to see the data frame we created we type c in the command line.

If you only wish to view one column you can type for example c$a_label that will print

> c$a_label
[1] 115 234 789 234 432 546 677 432 890 987 852

Create the Boxplot

Now let us create a boxplot that will depict in the x-axis the different values of b_label variable and will draw one boxplot for each value depicting the corresponding values of a_label.

> boxplot(a_label~b_label, data=c, main="Boxplot Test",
xlab="x-axis B label", ylab="y-axis A label ")

This will produce the following boxplot

Resources

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s