1

Here is part of my data set

df<-read.table (text=" Group Speed 
1   19
1   12
1   20
1   14
1   13
1   13
2   17
2   11
2   20
2   15
2   12
3   18
3   19
3   14
3   18
3   20
3   18
3   16
3   11
4   12
4   18
4   17
4   20
5   11
5   11
5   20
5   18

", header=TRUE)

I want to draw small hyphen lines under the Group

I have used ggplot2 to get the following plot

ggplot(df, aes(x=Group, y=Speed)) + 
geom_boxplot()

The outcome is similar to this. I want to draw the hyphen red lines for Groups1 and 4

enter image description here

user330
  • 1,256
  • 1
  • 7
  • 12
  • Maybe have a look at the ggh4x package. – Peter May 20 '22 at 08:22
  • There are ways to color the axis labels (https://stackoverflow.com/q/38862303/7912251) or to add underlines to them (https://stackoverflow.com/q/30470293/7912251), you could probably adjust that to your needs. Although I would be surprised if there was a way to only color the underline but not the text. Alternatively, you could experiment with a geom_line under the plot but that seems tricky in multiple aspects. – PhJ May 20 '22 at 08:23

1 Answers1

4

Here is a way inspired in this answer to another SO question.
The trick to draw outside the plot area is to set clip = "off". You can play with hyph_len and the value y = 8.75 to have segments of different lengths and positioned close to the labels.

library(ggplot2)

hyph_len <- 0.15
hyphens <- data.frame(start = c(1 - hyph_len, 4 - hyph_len),
                      end = c(1 + hyph_len, 4 + hyph_len))

ggplot(df, aes(x = factor(Group), y = Speed)) + 
  geom_boxplot() +
  annotate("segment", 
           x = hyphens$start, xend = hyphens$end,
           y = 8.75, yend = 8.75,
           col = "red",
           size = 2) +
  coord_cartesian(ylim = c(10, 20), clip = "off") +
  theme(plot.margin = unit(c(1,1,1,0), "lines"))

Created on 2022-05-20 by the reprex package (v2.0.1)

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66