Clark
Clark

Reputation: 23

How to highlight specific ranges in various boxplots in R?

I have a dataset of scores (from 0 to 100) on different dimensions (A,B,C,D). Using the following code:

dat=stack(dat)
dat$ind <- factor(dat$ind,levels=rev(unique(dat$ind)))
ggplot(dat, aes(values,ind)) + 
geom_boxplot() + 
xlab("Dimension Score") + 
ylab ("Dimension")

I create a plot that looks like this:

Boxplot

Now I need to highlight specific ranges for each of the dimensions:

A: 45 to 60
B: 70 to 85
C: 40 to 55
D: 35 to 50

How do I do this? Thank you in advance for your help.

Upvotes: 2

Views: 313

Answers (1)

Matthew Skiffington
Matthew Skiffington

Reputation: 332

Use geom_rect, e.g. below. ymin and ymax of factor correspond to their mapping to integers. This should get you started.

library(ggplot2)

values <- c(
  runif(100,0,100),
  rgamma(100,10,1),
  rnorm(100,50,30),
  rnorm(100,70,10)
  )

ind <- rep(c("A","B","C","D"),each = 100)
dat <- data.frame(values,ind)

rects <- data.frame(
  start = c(45,70,40,35),
  end = c(60,85,55,50),
  ymin = c(0.5,1.5,2.5,3.5),
  ymax = c(1.5,2.5,3.5,4.5),
  group = as.factor(c("A","B","C","D"))
)

dat$ind <- factor(dat$ind,levels=rev(unique(dat$ind)))
ggplot(data = dat) + 
  geom_boxplot(mapping = aes(values,ind)) + 
  xlab("Dimension Score") + 
  ylab ("Dimension") +
  geom_rect(data=rects, inherit.aes=FALSE, aes(xmin=start, 
                                               xmax=end, 
                                               ymin=ymin,
                                               ymax=ymax, 
                                               group=group,
                                               fill=group), 
            color="transparent", , alpha=0.3)

enter image description here

Cheers

Upvotes: 1

Related Questions