How to make a box plot showing several different ranges and the overlapping range in R?

Viewed 114

I would like to make a box plot or a similar in order to visualise the range of a three different target variables (T1, T2, T3) as a function of V1. For example the range of T1 is from 2 to 7, the range for T2 is from 1 to 5 and the range for T3 is from 3 to 7. I would also like to be able to visualise a fourth box representing only the overlapping range i.e. from 3 to 5 in this example.

Thank you in advance!

Lot <- c(1:9)
V1 <- c(2, 5, 7 ,1 ,5 ,3, 4, 5, 7)
T1 <- c(1, 1, 1, 0, 0, 0, 0, 0, 0)
T2 <- c(0, 0, 0, 1, 1, 0, 0, 0, 0)
T3 <- c(0, 0, 0, 0, 0, 1, 1, 1, 1)
df <- data.frame(Lot, V1, T1, T2, T3)

enter image description here

1 Answers
Lot <- c(1:9)
V1 <- c(2, 5, 7 ,1 ,5 ,3, 4, 5, 7)
T1 <- c(1, 1, 1, 0, 0, 0, 0, 0, 0)
T2 <- c(0, 0, 0, 1, 1, 0, 0, 0, 0)
T3 <- c(0, 0, 0, 0, 0, 1, 1, 1, 1)
df <- data.frame(Lot, V1, T1, T2, T3)

First I would calculate the overlap

ranges <- apply(df[,3:ncol(df)], 2, function(x) range(df$V1[x == 1]))
ranges
     T1 T2 T3
[1,]  2  1  3
[2,]  7  5  7
ranges <- cbind(ranges, overlap = c(max(ranges[1,]), min(ranges[2,])))
ranges
     T1 T2 T3 overlap
[1,]  2  1  3       3
[2,]  7  5  7       5  

Now we can plot it with ggplot. First we have to create a data frame. The names column must be specified as a factor to keep the order of the variables. is_overlap column is not necessary, only if you want to color the overlap bar differently.

df_range <- data.frame(name = factor(colnames(ranges), levels = colnames(ranges)),
                       min = ranges[1,], max = ranges[2,], is_overlap = FALSE)
df_range$is_overlap[nrow(df_range)] <- TRUE

library(ggplot2)

ggplot(df_range) + geom_linerange(aes(x = name, ymin = min, ymax = max,
                                      color = is_overlap),  size=6) 

enter image description here

Related