If I wish to label outliers in the boxplot and use Grubbs' test for outlier detection, I can use Grubbs' test while doing data preprocessing and then label the outliers on the boxplot. How could I improve my codes?
Here is my origimal data:
SFP2<-structure(list(Pos_heliaphen = c("Y07", "Y16", "Y36", "Y45",
"Z06", "Z23", "Z36", "Z45"), traitement = c("WS", "WS", "WS",
"WS", "WS", "WS", "WS", "WS"), Variete = c("SPE", "SPE", "SPE",
"SPE", "SPE", "SPE", "SPE", "SPE"), Date_obs = structure(c(1685318400,
1685318400, 1685318400, 1685318400, 1685318400, 1685318400, 1685318400,
1685318400), tzone = "UTC", class = c("POSIXct", "POSIXt")),
SF_Plante_Totale = c(103461.423, 107125.5471, 87559.8568,
108760.509, 95280.1512, 117435.0697, 129047.8228, 106354.3793
)), row.names = c(NA, -8L), class = c("tbl_df", "tbl", "data.frame"
))
Here is the code I tried:
library(ggplot2)
library(outliers)
test_result <- grubbs.test(SFP2$SF_Plante_Totale, type = 10, two.sided = TRUE)
print(test_result)
p <- ggplot(SFP2, aes(x = Pos_heliaphen, y = SF_Plante_Totale)) +
geom_boxplot() +
labs(title = "Boxplot with Grubbs' Test Outlier Detection")
if (test_result$p.value < 0.05) {
p <- p + geom_point(aes(x = Pos_heliaphen, y = test_result$alternative * test_result$statistic),
color = "red", size = 3) +
geom_text(aes(x = Pos_heliaphen, y = test_result$alternative * test_result$statistic),
label = "Outlier", color = "red", vjust = 1.5)
}
print(p)
How can I have the right boxplot with outliers analysed by Grubbs test to be presented in the figure?
