Unable to put counter label on mustache in outlier box

I'm trying to put observation marks at the end of a boxplot mustache, but it doesn't seem to work when there are outliers.

I tried to compare the max / min values ​​with what, in my opinion, is the calculated whisker length [quartile 1 (or quartile 3) + (or -) 1.5 * interquartile range]. But the labels are not placed either in the max / min value or at the end of the whisker.

An example of use mtcarsand the y axis for an autopsy to demonstrate:

library(ggplot2,dplyr)

  mtcars %>%
    select(qsec, cyl,am) %>%

    ggplot(aes(factor(cyl),qsec,fill=factor(am))) + 
    stat_boxplot(geom = "errorbar") + ## Draw horizontal lines across ends of whiskers
    geom_boxplot(outlier.shape=1, outlier.size=3, 
                 position =  position_dodge(width = 0.75)) +
    scale_y_reverse() +
    geom_text(data = mtcars %>%
                select(qsec,cyl,am) %>%
                group_by(cyl, am) %>%
                summarize(min_qsec = min(qsec),Count = n(),med = median(qsec),
                          q1 = quantile(qsec,0.25), 
                          q3 = quantile(qsec,0.75), iqr = IQR(qsec),
                          qsec = mean(qsec),
                          lab_pos = max(min_qsec, q1-1.5*iqr)),
              aes(y=lab_pos,label = Count), position = position_dodge(width = 0.75))

What produces:

enter image description here

Labels for am(1)at cyl(4)and am(0)at cyl(8)are offset.

lab_pos , ? , ggplot2 dplyr,

+2
1

, , :

label_data <- mtcars %>%
  select(qsec, cyl, am) %>%
  group_by(cyl, am) %>%
  summarize(min_qsec = min(qsec),
            Count = n(),
            med = median(qsec),
            q1 = quantile(qsec, 0.25), 
            q3 = quantile(qsec, 0.75),
            iqr = IQR(qsec),
            lab_pos = min(ifelse(qsec > q1-1.5*iqr, qsec, NA), na.rm = TRUE),
            qsec = mean(qsec))

mtcars %>%
  select(qsec, cyl,am) %>%
  ggplot(aes(factor(cyl),qsec,fill=factor(am))) + 
  stat_boxplot(geom = "errorbar") + ## Draw horizontal lines across ends of whiskers
  geom_boxplot(outlier.shape=1, outlier.size=3, 
               position =  position_dodge(width = 0.75)) +
  scale_y_reverse() +
  geom_text(data = label_data, aes(y = lab_pos,label = Count),
            position = position_dodge(width = 0.75), vjust = 0, fontface = "bold")

enter image description here

, .

+1

Source: https://habr.com/ru/post/1690885/


All Articles