Home > database >  Adding the median value to every box (not ggplot)
Adding the median value to every box (not ggplot)

Time:11-20

I have a boxplot from the code below and i want to add median values.

boxplot(ndvi_pct_sep~edge_direction, data= data_sample, subset = edge_direction %in% c(64,4, 1,16),ylab="NDVI2028-2016", xlab="Forest edge direction",names=c("north", "south", "east", "west"))

enter image description here

. I want to add the median values to the boxplots, any idea how to do it?

CodePudding user response:

It will likely involve using legends - since I don't have your data I cant make it perfect, but the below code should get you started using the ToothGrowth data contained in R. I am showing a base R and ggplot example (I know you said no ggplot, but others may use it).

# Load libraries
library(dplyr); library(ggplot2)

# get median data
mediandata <- ToothGrowth %>% group_by(dose) %>% summarise(median = median(len, na.rm = TRUE))
l <- unname(unlist(mediandata))
tg <- ToothGrowth # for convenience 
tg$dose <- as.factor(tg$dose)

### Base R approach
boxplot(len ~ dose, data = tg,
        main = "Guinea Pigs' Tooth Growth",
        xlab = "Vitamin C dose mg",
        ylab = "tooth length", col = "red")
for (i in 1:3){
  legend(i-0.65,l[i 3] 5, legend = paste0("Median: ",l[i 3]), bty = "n")
}

### ggplot approach
ggplot(data = tg, aes(dose, len))   
  theme_classic()   theme(legend.position = "none")  
  geom_boxplot() 
  annotate("text",
           x = c(1,2,3),
           y = l[4:6] 1, # shit so you can read it
           label = l[4:6])


Base R: BaseR

ggplot: enter image description here

CodePudding user response:

Here's a straightforward solution with text and without forloop:

Toy data:

set.seed(12)
df <- data.frame(
  var1 = sample(LETTERS[1:4], 100, replace = TRUE),
  var2 = rnorm(100)
)

Calculate the medians:

library(dplyr)
med <- df %>%
  group_by(var1) %>%
  summarise(medians = median(var2)) %>%
  pull(medians)

Alternatively, in base R:

bx <- boxplot(df$var2 ~ df$var1)
med <- bx$stats[3,1:4]

Boxplot:

boxplot(df$var2 ~ df$var1)

Annotate boxplots:

text(1:4, med, round(med,3), pos = 3, cex = 0.6)

enter image description here

  • Related