简体   繁体   中英

How to draw small hyphen lines in x-axis in R

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

在此处输入图像描述

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM