joey francis
joey francis

Reputation: 1

How do I display box-plots of different data sets above each other in R?

new to R and just wondering is it possible to display these two box plots either side by side or above each other to allow for comparison, rather then producing two seperate box plots.

PBe <- PB$`Enterococci (cfu/100ml)`
BRe <- BR$`Enterococci (cfu/100ml)`
boxplot(BRe, horizontal = TRUE, col = "3", outline=FALSE)

boxplot(PBe, horizontal = TRUE, col = "4", outline=FALSE)

Upvotes: 0

Views: 182

Answers (2)

Allan Cameron
Allan Cameron

Reputation: 174248

We obviously don't have your data, so let's make a minimal reproducible example.

First we create two data frames, one called PB and one called BR. Each has a numeric column called Enterococci (cfu/100ml) containing random numbers between 100 and 1000:

set.seed(1)
PB <- data.frame(a = sample(100:1000, 100, TRUE))
BR <- data.frame(a = sample(100:1000, 50, TRUE))
names(PB) <- "Enterococci (cfu/100ml)"
names(BR) <- "Enterococci (cfu/100ml)"

Now, if we extract these columns as per your code, we can concatenate them together using c

PBe <- PB$`Enterococci (cfu/100ml)`
BRe <- BR$`Enterococci (cfu/100ml)`
value <- c(PBe, BRe)

Now, the trick is to create another vector that labels which data frame these numbers originally came from as a factor variable. We can do that with:

dataset <- factor(c(rep("PB", nrow(PB)), rep("BR", nrow(BR))))

And now we can just call plot on these two vectors. This will automatically give us a side-by-side boxplot:

plot(dataset, value, xlab = "Data set", ylab = "Enterococci (cfu/100ml)")

enter image description here

If you would prefer it to be horizontal, we can do:

boxplot(value ~ dataset, horizontal = TRUE,
        ylab = "Data set", 
        xlab = "Enterococci (cfu/100ml)")

enter image description here

Upvotes: 0

Onyambu
Onyambu

Reputation: 79288

You could use the boxplot function directly:

boxplot(list(BRe = BRe, PBe = PBE), col = c(3, 4))

You could add all the other parameters as you wish

Upvotes: 2

Related Questions