DataViz R

How to create BoxPlot in R and extract outliers

Outlier detection is a very broad topic, and boxplot is a part of that. Here is how to create a boxplot in R and extract outliers. There are few things to consider when creating a boxplot in R or anywhere else. Is boxplot showing all the necessary information? Sometimes it is important how many data points you have. Maybe you have to build a boxplot by subcategories?

Here is my data. If you want to know more about how to build an R data frame from scratch, check this out.

As you can see in the preview, there might be big enough differences between weekdays or working days and weekends. It is important to investigate outliers also in those categories. To learn more about the method by which outliers are detected with boxplot, go here.

In addition to this data frame, I divided the days into two categories – working day and weekend.

Boxplot by subcategories

It is easily done with a base function boxplot.

With boxplot()$out you can take a look at the outliers by each subcategory.

How to extract R data frame rows with boxplot outliers

To get all rows from the data frame that contains boxplot detected outliers, you can use a subset function.

To successfully visualize boxplot with all data points and highlight outliers in another color, I made some additional columns to my data frame – OUTLIER and INLIER. As you can see, I added plot argument to boxplot function, because otherwise the plot is made by default.

The initial code looks like this.


R boxplot with data points and outliers in a different color

Here is ggplot2 based code to do that.

I also used package ggrepel and function geom_text_repel to deal with data labels. It helps to position them in a way that is easy to read.

Ggplot2 geom_jitter parameter position and function position_jitter was very important to synchronize how data points and data labels will position themselves with each other.

By using stat_boxplot, I added additional error bars to ggplot boxplot to better see upper and lower limits.

Here are other great examples and my inspiration – boxplot with jitter.

Here is the full code used in this post.


0 comments on “How to create BoxPlot in R and extract outliers

Leave a Reply

Your email address will not be published. Required fields are marked *